Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- from typing import Annotated
- from langchain_core.tools import tool
- from langchain_openai import ChatOpenAI
- from langgraph.graph import StateGraph, START, END
- from langgraph.graph.message import add_messages
- from langgraph.prebuilt import ToolNode, tools_condition
- from typing_extensions import TypedDict
- class State(TypedDict):
- messages: Annotated[list, add_messages]
- @tool
- def add(a: int, b: int) -> int:
- """Add two numbers."""
- return a + b
- tools = [add]
- llm = ChatOpenAI(
- model="gpt-4o-mini",
- temperature=0
- )
- llm_with_tools = llm.bind_tools(tools)
- def llm_tool(state: State):
- response = llm_with_tools.invoke(state["messages"])
- return {
- "messages": [response]
- }
- graph_builder = StateGraph(State)
- graph_builder.add_node("llm_tool", llm_tool)
- graph_builder.add_node("tools", ToolNode(tools))
- graph_builder.add_edge(START, "llm_tool")
- graph_builder.add_conditional_edges(
- "llm_tool",
- tools_condition
- )
- graph_builder.add_edge("tools", "llm_tool")
- graph = graph_builder.compile()
- result = graph.invoke(
- {
- "messages": [
- {
- "role": "user",
- "content": "What is 2 + 4?"
- }
- ]
- }
- )
- for msg in result["messages"]:
- print(msg)
Advertisement
Add Comment
Please, Sign In to add comment