-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2-ToolGraph.py
More file actions
73 lines (48 loc) · 1.71 KB
/
2-ToolGraph.py
File metadata and controls
73 lines (48 loc) · 1.71 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
from langchain_openai import ChatOpenAI
# to build graph
from langgraph.graph import StateGraph, START, END
from langgraph.graph import MessagesState
from langgraph.prebuilt import ToolNode
from langgraph.prebuilt import tools_condition
# To create image
from utils.graph_img_generation import save_and_show_graph
# for printing messages
from langchain_core.messages import HumanMessage
from config.secret_keys import OPENAI_API_KEY
from config.config import get_llm
# defining the LLM
llm = get_llm()
# defining the tools
def multiply(a: int, b: int) -> int:
"""Multiply a and b.
Args:
a: first int
b: second int
"""
return a * b
# binding tools with llm
llm_with_tools = llm.bind_tools([multiply])
# Node
def tool_calling_llm(state: MessagesState):
return {"messages": [llm_with_tools.invoke(state["messages"])]}
# Build the graph
builder = StateGraph(MessagesState)
builder.add_node("tool_calling_llm", tool_calling_llm)
builder.add_node("tools", ToolNode([multiply]))
builder.add_edge(START, "tool_calling_llm")
builder.add_conditional_edges(
"tool_calling_llm",
# If the latest message (result) from assistant is a tool call -> tools_condition routes to tools
# If the latest message (result) from assistant is a not a tool call -> tools_condition routes to END
tools_condition,
)
builder.add_edge("tools", END)
graph = builder.compile()
# Use the utility function to save and optionally show the graph
save_and_show_graph(graph, filename="2-ToolGraph", show_image=False)
# To run the Graphs
user_msg = "multiply 2 and 3 and 6."
messages = [HumanMessage(content=user_msg)]
messages = graph.invoke({"messages": messages})
for m in messages['messages']:
m.pretty_print()