Repository navigation
Expand file tree
/
Copy pathsimple_agent_lngraph_tools.py
More file actions
135 lines (95 loc) · 3.94 KB
/
Copy pathsimple_agent_lngraph_tools.py
File metadata and controls
135 lines (95 loc) · 3.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
import os
from typing import Annotated, TypedDict
from dotenv import load_dotenv
from openai import OpenAI
from langchain_openai import ChatOpenAI
from langgraph.graph import StateGraph, END
from langchain_community.tools.tavily_search import TavilySearchResults
# Load environment variables from .env file
load_dotenv()
openai_key = os.getenv("OPENAI_API_KEY")
tavily = os.getenv("TAVILY_API_KEY")
llm_name = "gpt-6-luna" # gpt-4o-mini shuts down Jan 14, 2027
client = OpenAI(api_key=openai_key)
model = ChatOpenAI(api_key=openai_key, model=llm_name, reasoning_effort="none")
# STEP 1: Build a Basic Chatbot
from langgraph.graph.message import add_messages
class State(TypedDict):
# Messages have the type "list". The `add_messages` function
# in the annotation defines how this state key should be updated
# (in this case, it appends messages to the list, rather than overwriting them)
messages: Annotated[list, add_messages]
graph_builder = StateGraph(State)
# create tools
tool = TavilySearchResults(max_results=2)
tools = [tool]
# rest = tool.invoke("What is the capital of France?")
# print(rest)
model_with_tools = model.bind_tools(tools)
# Below, implement a BasicToolNode that checks the most recent
# message in the state and calls tools if the message contains tool_calls
import json
from langchain_core.messages import ToolMessage
from langgraph.prebuilt import ToolNode, tools_condition
def bot(state: State):
# print(state.items())
print(state["messages"])
return {"messages": [model_with_tools.invoke(state["messages"])]}
# instantiate the ToolNode with the tools
tool_node = ToolNode(tools=[tool])
graph_builder.add_node("tools", tool_node) # Add the node to the graph
# The `tools_condition` function returns "tools" if the chatbot asks to use a tool, and "__end__" if
# it is fine directly responding. This conditional routing defines the main agent loop.
graph_builder.add_conditional_edges(
"bot",
tools_condition,
)
# The first argument is the unique node name
# The second argument is the function or object that will be called whenever
# the node is used.
graph_builder.add_node("bot", bot)
# STEP 3: Add an entry point to the graph
graph_builder.set_entry_point("bot")
# ADD MEMORY NODE
# from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.checkpoint.memory import MemorySaver
# memory = SqliteSaver.from_conn_string(":memory:")
memory = MemorySaver()
# memory = InMemoryStore()
# STEP 5: Compile the graph
# graph = graph_builder.compile(checkpointer=memory) # no need for checkpointer memory anymore
graph = graph_builder.compile(
checkpointer=memory
) # no need for checkpointer memory anymore
# MEMORY CODE CONTINUES ===
# Now we can run the chatbot and see how it behaves
# PICK A TRHEAD FIRST
config = {
"configurable": {"thread_id": 1}
} # a thread where the agent will dump its memory to
user_input = "Hi there! My name is Bond. and I have been happy for 100 years"
# The config is the **second positional argument** to stream() or invoke()!
events = graph.stream(
{"messages": [("user", user_input)]}, config, stream_mode="values"
)
for event in events:
event["messages"][-1].pretty_print()
user_input = "do you remember my name, and how long have I been happy for?"
# The config is the **second positional argument** to stream() or invoke()!
events = graph.stream(
{"messages": [("user", user_input)]}, config, stream_mode="values"
)
for event in events:
event["messages"][-1].pretty_print()
snapshot = graph.get_state(config)
print(snapshot)
# from langchain_core.messages import BaseMessage
# while True:
# user_input = input("User: ")
# if user_input.lower() in ["quit", "exit", "q"]:
# print("Goodbye!")
# break
# for event in graph.stream({"messages": [("user", user_input)]}):
# for value in event.values():
# if isinstance(value["messages"][-1], BaseMessage):
# print("Assistant:", value["messages"][-1].content)