|
| 1 | +import functools |
| 2 | + |
| 3 | +from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder |
| 4 | +from langchain_core.runnables.base import RunnableSequence |
| 5 | +from langchain_core.tools import StructuredTool |
| 6 | +from langchain_openai import ChatOpenAI |
| 7 | +from langgraph.checkpoint.postgres.aio import AsyncPostgresSaver |
| 8 | +from langgraph.graph import MessagesState, StateGraph |
| 9 | +from langgraph.graph.state import CompiledStateGraph |
| 10 | +from langgraph.prebuilt import ToolNode, tools_condition |
| 11 | + |
| 12 | +from api.core.agent.prompts import SYSTEM_PROMPT |
| 13 | + |
| 14 | + |
| 15 | +class State(MessagesState): |
| 16 | + next: str |
| 17 | + |
| 18 | + |
| 19 | +def agent_factory( |
| 20 | + llm: ChatOpenAI, tools: list[StructuredTool], system_prompt: str |
| 21 | +) -> RunnableSequence: |
| 22 | + prompt = ChatPromptTemplate.from_messages( |
| 23 | + [ |
| 24 | + ("system", system_prompt), |
| 25 | + MessagesPlaceholder(variable_name="messages"), |
| 26 | + ] |
| 27 | + ) |
| 28 | + if tools: |
| 29 | + agent = prompt | llm.bind_tools(tools) |
| 30 | + else: |
| 31 | + agent = prompt | llm |
| 32 | + return agent |
| 33 | + |
| 34 | + |
| 35 | +def agent_node_factory( |
| 36 | + state: State, |
| 37 | + agent: RunnableSequence, |
| 38 | +) -> State: |
| 39 | + result = agent.invoke(state) |
| 40 | + return dict(messages=[result]) |
| 41 | + |
| 42 | + |
| 43 | +def graph_factory( |
| 44 | + agent_node: functools.partial, |
| 45 | + tools: list[StructuredTool], |
| 46 | + checkpointer: AsyncPostgresSaver | None = None, |
| 47 | + name: str = "agent_node", |
| 48 | +) -> CompiledStateGraph: |
| 49 | + graph_builder = StateGraph(State) |
| 50 | + graph_builder.add_node(name, agent_node) |
| 51 | + graph_builder.add_node("tools", ToolNode(tools)) |
| 52 | + |
| 53 | + graph_builder.add_conditional_edges(name, tools_condition) |
| 54 | + graph_builder.add_edge("tools", name) |
| 55 | + |
| 56 | + graph_builder.set_entry_point(name) |
| 57 | + graph = graph_builder.compile(checkpointer=checkpointer) |
| 58 | + return graph |
| 59 | + |
| 60 | + |
| 61 | +def get_graph( |
| 62 | + llm: ChatOpenAI, |
| 63 | + tools: list[StructuredTool] = [], |
| 64 | + system_prompt: str = SYSTEM_PROMPT, |
| 65 | + name: str = "agent_node", |
| 66 | + checkpointer: AsyncPostgresSaver | None = None, |
| 67 | +) -> CompiledStateGraph: |
| 68 | + agent = agent_factory(llm, tools, system_prompt) |
| 69 | + worker_node = functools.partial(agent_node_factory, agent=agent) |
| 70 | + return graph_factory(worker_node, tools, checkpointer, name) |
| 71 | + |
| 72 | + |
| 73 | +def get_config(): |
| 74 | + return dict( |
| 75 | + configurable=dict(thread_id="1"), |
| 76 | + ) |
0 commit comments