-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathfunction_calling.py
More file actions
134 lines (112 loc) · 4.13 KB
/
Copy pathfunction_calling.py
File metadata and controls
134 lines (112 loc) · 4.13 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
# how can we train or finetune for a simple reasoning model
# that can solve your specific problems
# ---------
#
# This uses OpenAI SDK to build a simple LLM-based assistant.
from openai import OpenAI
from dotenv import load_dotenv
import os
from dataclasses import dataclass
from pprint import pprint
import json
@dataclass
class BookingStatus:
status: str = "pending"
# Tools Definition
def book_a_ride(pickup_location: str, dropoff_location: str):
""" Book a ride for a given pickup and dropoff location, which
is provided from the user query.
Args:
pickup_location: current user location.
dropoff_location: destination of the ride.
Returns:
booking_status: status of ride booking.
"""
# Just for testing.
print(f"pickup_location: {pickup_location}")
print(f"dropoff_location: {dropoff_location}")
return f"Here is your booking status: SUCCESS"
def get_fn_by_name(fn_name: str):
if fn_name == "book_a_ride":
return book_a_ride
TOOLS = [
{
"type": "function",
"function": {
"name": "book_a_ride",
"description": "Book a ride that given pickup and dropoff location user provided.",
"parameters": {
"type": "object",
"properties": {
"pickup_location": {
"type": "string",
"description": "Current location where the user is."
},
"dropoff_location": {
"type": "string",
"description": "The destination which the user would like to go to."
}
},
"required": ["pickup_location", "dropoff_location"]
}
}
}
]
if __name__ == "__main__":
# Load environment variables for security
load_dotenv()
MODEL_URL = os.getenv("ANTHROPIC_BASE_URL", "")
MODEL_NAME = os.getenv("MODEL_NAME", "")
API_KEY = os.getenv("ANTHROPIC_API_KEY", "")
print(f"MODEL NAME: {MODEL_NAME}")
print(f"MODEL URL: {MODEL_URL}")
assert MODEL_URL != "", "Please recheck MODEL URL in your environment variables .env"
# Initialize the OpenAI client
client = OpenAI(
api_key=API_KEY,
base_url=MODEL_URL
)
print(f"\nEstablished connection to {MODEL_URL}.")
query = "who is the president of American in 2020?"
query2 = "tôi muốn đặt xe đi từ 42 lê công kiều đến 65 hải phòng."
messages = [{"role": "user", "content": query2}]
# Model Inference
response = client.chat.completions.create(
model=MODEL_NAME,
messages=messages,
tools=TOOLS,
tool_choice="auto"
)
pprint(response.choices[0])
pprint("\n")
pprint(f"Response Output: {response.choices[0].message.model_dump()}")
# Add tool calls output (if any) back to messages list
messages.append(response.choices[0].message.model_dump())
# tools output parsing
if tool_calls := response.choices[0].message.tool_calls:
for tool_call in tool_calls:
if tool_call.type != "function":
continue
# get function name and its arguments from LLM output
# then execute it.
# WARNNING: the content from LLM returns is always string.
tool_call_id = tool_call.id
fn_name: str = tool_call.function.name
fn_arguments: dict = json.loads(tool_call.function.arguments)
fn_output = json.dumps(get_fn_by_name(fn_name)(**fn_arguments))
print(f"\nfn_output: {fn_output}")
# update messages list for later use with the LLM
messages.append({
"role": "tool",
"content": fn_output,
"tool_call_id": tool_call_id
})
pprint(messages)
# send everything back to the LLM for final answer generation.
response = client.chat.completions.create(
model=MODEL_NAME,
messages=messages,
tools=TOOLS
)
print(f'\n{response}')
print(f"\nFINAL RESPONSE: {response.choices[0].message.content}")