-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtoolcreationprac.py
More file actions
195 lines (148 loc) · 5.67 KB
/
Copy pathtoolcreationprac.py
File metadata and controls
195 lines (148 loc) · 5.67 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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
from langchain_ibm import ChatWatsonx
from langchain.agents import AgentType
from langchain.agents import Tool
from langchain_core.tools import tool
from typing import Dict, Union
from langgraph.prebuilt import create_react_agent
from typing import List
from langchain_openai import ChatOpenAI
from langchain.agents import initialize_agent
import re
llm = ChatWatsonx(
model_id="ibm/granite-4-h-small",
url="https://us-south.ml.cloud.ibm.com",
project_id="#",
)
llm_ai=ChatOpenAI(model="gpt-4.1-nano")
# response = llm.invoke("What is tool calling in LangChain?")
# print("\nResponse content", response.content)
def add_numbers(inputs:str) -> dict:
"""
Adds a list of numbers provided in the input dictionary or extracts numbers from a string.
Parameters:
- inputs (str):
string, it should contain numbers that can be extracted and summed.
Returns:
- dict: A dictionary with a single key "result" containing the sum of the numbers.
Example Input (Dictionary):
{"numbers": [10, 20, 30]}
Example Input (String):
"Add the numbers 10, 20, and 30."
Example Output:
{"result": 60}
"""
numbers = [int(x) for x in inputs.replace(",", "").split() if x.isdigit()]
result = sum(numbers)
return {"result": result}
add_numbers("1 2")
add_tool=Tool(
name="AddTool",
func=add_numbers,
description="Adds a list of numbers and returns the result.")
# using the @tool operator
@tool
def add_numbers(inputs:str) -> dict:
"""
Adds a list of numbers provided in the input string.
Parameters:
- inputs (str):
string, it should contain numbers that can be extracted and summed.
Returns:
- dict: A dictionary with a single key "result" containing the sum of the numbers.
Example Input:
"Add the numbers 10, 20, and 30."
Example Output:
{"result": 60}
"""
# Use regular expressions to extract all numbers from the input
numbers = [int(num) for num in re.findall(r'\d+', inputs)]
# numbers = [int(x) for x in inputs.replace(",", "").split() if x.isdigit()]
result = sum(numbers)
return {"result": result}
# print("Name: \n" , add_numbers.name)
# print("Description: \n" , add_numbers.description)
# print("Args: \n", add_numbers.args)
# test_input = "10 20 30 a b 40"
# print(add_numbers.invoke(test_input))
print("@tool Decorator Approach:")
# print(f"Has Schema: {hasattr(add_numbers, 'args_schema')}")
# print(f"Args Schema Info: {add_numbers.args}")
@tool
def add_numbers_with_options(numbers: List[float], absolute: bool = False) -> float:
"""
Adds a list of numbers provided as input.
Parameters:
- numbers (List[float]): A list of numbers to be summed.
- absolute (bool): If True, use the absolute values of the numbers before summing.
Returns:
- float: The total sum of the numbers.
"""
if absolute:
numbers = [abs(n) for n in numbers]
return sum(numbers)
# print(f"Has schema info: {add_numbers.args}")
# print(f"Has schema info: {add_numbers_with_options.args}")
@tool
def sum_numbers_with_complex_output(inputs:str) -> Dict[str, Union[float, str]]:
"""
Extracts and sums all integers and decimal numbers from the input string.
Parameters:
- inputs (str) : string that may contain numerical values
Returns:
- dict: A dictionary with the key "result". If numbers are found, the value is their sum (float).
If no numbers are found or an error occurs, the value is a corresponding message (str).
Example Input:
"Add 10, 20.5, and -3."
Example Output:
{"result": 27.5}
"""
matches = re.findall(r'-?\d+(?:\.\d+)?', inputs)
if not matches:
return {"result": "No numbers found in input."}
try:
numbers = [float(num) for num in matches]
total = sum(numbers)
return {"result": total}
except Exception as e:
return {"result": f"Error during summation: {str(e)}"}
@tool
def sum_numbers_from_text(inputs:str) -> float:
"""
Adds a list of numbers provided in the input string.
Args:
text: A string containing numbers that should be extracted and summed.
Returns:
The sum of all numbers found in the input.
"""
# Use regular expressions to extract all numbers from the input
numbers = [int(num) for num in re.findall(r'\d+', inputs)]
result = sum(numbers)
return result
# agent = initialize_agent([add_tool], llm, agent="zero-shot-react-description", verbose=True, handle_parsing_errors=True)
# response = agent.run("In 2023, the US GDP was approximately $27.72 trillion, while Canada's was around $2.14 trillion and Mexico's was about $1.79 trillion what is the total.")
# print(response)
# agent2 = initialize_agent(
# [sum_numbers_from_text],
# llm,
# agent="structured-chat-zero-shot-react-description",
# verbose=True,
# handle_parsing_error=True)
# response=agent2.invoke({"input": "Add 10, 20 30, and -30 absolute value "})
# print(response)
# agent_3 = initialize_agent([sum_numbers_with_complex_output], llm_ai, agent="openai-functions", verbose=True, handle_parsing_errors=True)
# response = agent_3.invoke({"input": "Add 10, 20 and 30"})
# print(response)
# agent_openai=initialize_agent(
# [add_numbers_with_options],
# llm_ai,
# agent="openai-functions",
# verbose=True,
# handling_parsing_error=True
# )
# response = agent_openai.invoke({
# "input": "Add -10, -20, and -30 using absolute values."
# })
# print(response)
agent_exec=create_react_agent(model=llm_ai, tools=[sum_numbers_from_text])
msgs = agent_exec.invoke({"messages": [("human", "Add the numbers -10, -20, -30")]})
print(msgs["messages"][-1].content)