|
| 1 | +from langgraph.graph import END, START, StateGraph |
| 2 | + |
| 3 | +from template_langgraph.agents.basic_workflow_agent.models import AgentInput, AgentOutput, AgentState |
| 4 | +from template_langgraph.llms.azure_openais import AzureOpenAiWrapper |
| 5 | +from template_langgraph.loggers import get_logger |
| 6 | +from template_langgraph.tools.elasticsearch_tool import search_elasticsearch |
| 7 | +from template_langgraph.tools.qdrants import search_qdrant |
| 8 | + |
| 9 | +logger = get_logger(__name__) |
| 10 | + |
| 11 | + |
| 12 | +class BasicWorkflowAgent: |
| 13 | + def __init__(self, tools=None): |
| 14 | + if tools is None: |
| 15 | + # Default tool for searching Qdrant and Elasticsearch |
| 16 | + tools = [ |
| 17 | + search_qdrant, |
| 18 | + search_elasticsearch, |
| 19 | + # Add other tools as needed |
| 20 | + ] |
| 21 | + self.llm = AzureOpenAiWrapper().chat_model.bind_tools( |
| 22 | + tools=tools, |
| 23 | + ) |
| 24 | + |
| 25 | + def create_graph(self): |
| 26 | + """Create the main graph for the agent.""" |
| 27 | + # Create the workflow state graph |
| 28 | + workflow = StateGraph(AgentState) |
| 29 | + |
| 30 | + # Create nodes |
| 31 | + workflow.add_node("initialize", self.initialize) |
| 32 | + workflow.add_node("do_something", self.do_something) |
| 33 | + |
| 34 | + # Create edges |
| 35 | + workflow.add_edge(START, "initialize") |
| 36 | + workflow.add_edge("initialize", "do_something") |
| 37 | + workflow.add_edge("do_something", END) |
| 38 | + |
| 39 | + # Compile the graph |
| 40 | + return workflow.compile() |
| 41 | + |
| 42 | + def initialize(self, state: AgentState) -> AgentState: |
| 43 | + """Initialize the agent with the given state.""" |
| 44 | + logger.info(f"Initializing BasicWorkflowAgent with state: {state}") |
| 45 | + # Here you can add any initialization logic if needed |
| 46 | + return state |
| 47 | + |
| 48 | + def do_something(self, state: AgentState) -> AgentState: |
| 49 | + """Perform some action with the given state.""" |
| 50 | + logger.info(f"Doing something with state: {state}") |
| 51 | + # Here you can add the logic for the action |
| 52 | + return state |
| 53 | + |
| 54 | + def run_agent(self, input: AgentInput) -> AgentOutput: |
| 55 | + """Run the agent with the given input.""" |
| 56 | + logger.info(f"Running BasicWorkflowAgent with question: {input.model_dump_json(indent=2)}") |
| 57 | + app = self.create_graph() |
| 58 | + initial_state: AgentState = { |
| 59 | + "request": input.request, |
| 60 | + } |
| 61 | + final_state = app.invoke(initial_state) |
| 62 | + logger.info(f"Final state after running agent: {final_state}") |
| 63 | + return AgentOutput( |
| 64 | + response=final_state.get("response", "No response"), |
| 65 | + ) |
| 66 | + |
| 67 | + def draw_mermaid_png(self) -> bytes: |
| 68 | + """Draw the graph in Mermaid format.""" |
| 69 | + return self.create_graph().get_graph().draw_mermaid_png() |
0 commit comments