imashutosh51

Langgraph_sample_Code

Jun 2nd, 2026 (edited)
48
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.27 KB | None | 0 0
  1. from typing import Annotated
  2. from langchain_core.tools import tool
  3. from langchain_openai import ChatOpenAI
  4. from langgraph.graph import StateGraph, START, END
  5. from langgraph.graph.message import add_messages
  6. from langgraph.prebuilt import ToolNode, tools_condition
  7. from typing_extensions import TypedDict
  8. class State(TypedDict):
  9.     messages: Annotated[list, add_messages]
  10. @tool
  11. def add(a: int, b: int) -> int:
  12.     """Add two numbers."""
  13.     return a + b
  14.  
  15. tools = [add]
  16.  
  17. llm = ChatOpenAI(
  18.     model="gpt-4o-mini",
  19.     temperature=0
  20. )
  21.  
  22. llm_with_tools = llm.bind_tools(tools)
  23.  
  24. def llm_tool(state: State):
  25.     response = llm_with_tools.invoke(state["messages"])
  26.  
  27.     return {
  28.         "messages": [response]
  29.     }
  30.  
  31. graph_builder = StateGraph(State)
  32. graph_builder.add_node("llm_tool", llm_tool)
  33. graph_builder.add_node("tools", ToolNode(tools))
  34. graph_builder.add_edge(START, "llm_tool")
  35. graph_builder.add_conditional_edges(
  36.     "llm_tool",
  37.     tools_condition
  38. )
  39. graph_builder.add_edge("tools", "llm_tool")
  40. graph = graph_builder.compile()
  41.  
  42. result = graph.invoke(
  43.     {
  44.         "messages": [
  45.             {
  46.                 "role": "user",
  47.                 "content": "What is 2 + 4?"
  48.             }
  49.         ]
  50.     }
  51. )
  52.  
  53. for msg in result["messages"]:
  54.     print(msg)
Advertisement
Add Comment
Please, Sign In to add comment