forked from i-am-bee/beeai-framework
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtool_calling.py
More file actions
71 lines (59 loc) · 2.14 KB
/
tool_calling.py
File metadata and controls
71 lines (59 loc) · 2.14 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
import asyncio
import json
import re
import sys
import traceback
from beeai_framework.backend import (
AnyMessage,
ChatModel,
ChatModelParameters,
MessageToolResultContent,
SystemMessage,
ToolMessage,
UserMessage,
)
from beeai_framework.errors import FrameworkError
from beeai_framework.tools import AnyTool, ToolOutput
from beeai_framework.tools.search.duckduckgo import DuckDuckGoSearchTool
from beeai_framework.tools.weather.openmeteo import OpenMeteoTool
async def main() -> None:
model = ChatModel.from_name("ollama:llama3.1", ChatModelParameters(temperature=0))
tools: list[AnyTool] = [DuckDuckGoSearchTool(), OpenMeteoTool()]
messages: list[AnyMessage] = [
SystemMessage("You are a helpful assistant. Use tools to provide a correct answer."),
UserMessage("What's the fastest marathon time?"),
]
while True:
response = await model.create(
messages=messages,
tools=tools,
)
tool_calls = response.get_tool_calls()
tool_results: list[ToolMessage] = []
for tool_call in tool_calls:
print(f"-> running '{tool_call.tool_name}' tool with {tool_call.args}")
tool: AnyTool = next(tool for tool in tools if tool.name == tool_call.tool_name)
assert tool is not None
res: ToolOutput = await tool.run(json.loads(tool_call.args))
result = res.get_text_content()
print(f"<- got response from '{tool_call.tool_name}'", re.sub(r"\s+", " ", result)[:90] + " (truncated)")
tool_results.append(
ToolMessage(
MessageToolResultContent(
result=result,
tool_name=tool_call.tool_name,
tool_call_id=tool_call.id,
)
)
)
messages.extend(tool_results)
answer = response.get_text_content()
if answer:
print(f"Agent: {answer}")
break
if __name__ == "__main__":
try:
asyncio.run(main())
except FrameworkError as e:
traceback.print_exc()
sys.exit(e.explain())