graph.py 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041
  1. import os
  2. from langchain.chat_models import init_chat_model
  3. from typing import Annotated
  4. from typing_extensions import TypedDict
  5. from langgraph.graph import StateGraph, START, END
  6. from langgraph.graph.message import add_messages
  7. class State(TypedDict):
  8. # Messages have the type "list". The `add_messages` function
  9. # in the annotation defines how this state key should be updated
  10. # (in this case, it appends messages to the list, rather than overwriting them)
  11. messages: Annotated[list, add_messages]
  12. graph_builder = StateGraph(State)
  13. os.environ["OPENAI_API_KEY"] = "sk-..."
  14. llm = init_chat_model("openai:gpt-4.1")
  15. def chatbot(state: State):
  16. return {"messages": [llm.invoke(state["messages"])]}
  17. # The first argument is the unique node name
  18. # The second argument is the function or object that will be called whenever
  19. # the node is used.
  20. graph_builder.add_node("chatbot", chatbot)
  21. graph_builder.add_edge(START, "chatbot")
  22. graph = graph_builder.compile()
  23. img_data = graph.get_graph().draw_mermaid_png()
  24. with open("graph.png", "wb") as f:
  25. f.write(img_data)