@@ -57,6 +57,14 @@ def create_function_schema(self, definitions):
57
57
58
58
return functions
59
59
60
+ # Represent a tool call as an object
61
+ def create_tool_call (self , name , parameters ):
62
+ return {
63
+ "type" : "function" ,
64
+ "name" : name ,
65
+ "parameters" : parameters ,
66
+ }
67
+
60
68
# Wrap a content block in a text or an image object
61
69
def wrap_block (self , block ):
62
70
if isinstance (block , bytes ):
@@ -125,22 +133,24 @@ def call(self, messages, functions=None):
125
133
if functions :
126
134
tool_calls = message .tool_calls or []
127
135
combined_tool_calls = [
128
- {
129
- "type" : "function" ,
130
- "name" : tool_call .function .name ,
131
- "parameters" : parse_json (tool_call .function .arguments ),
132
- }
136
+ self .create_tool_call (
137
+ tool_call .function .name , parse_json (tool_call .function .arguments )
138
+ )
133
139
for tool_call in tool_calls
134
140
if parse_json (tool_call .function .arguments ) is not None
135
141
]
136
142
137
- # Sometimes, Llama function calls are not parsed by the inference provider. This code parses them manually.
143
+ # Sometimes, function calls are returned unparsed by the inference provider. This code parses them manually.
138
144
if message .content and not tool_calls :
139
145
tool_call_matches = re .search (r"\{.*\}" , message .content )
140
146
if tool_call_matches :
141
147
tool_call = parse_json (tool_call_matches .group (0 ))
142
- if tool_call .get ("name" ) and tool_call .get ("parameters" ):
143
- combined_tool_calls .append (tool_call )
148
+ # Some models use "arguments" as the key instead of "parameters"
149
+ parameters = tool_call .get ("parameters" , tool_call .get ("arguments" ))
150
+ if tool_call .get ("name" ) and parameters :
151
+ combined_tool_calls .append (
152
+ self .create_tool_call (tool_call .get ("name" ), parameters )
153
+ )
144
154
return None , combined_tool_calls
145
155
146
156
return message .content , combined_tool_calls
@@ -194,7 +204,7 @@ def call(self, messages, functions=None):
194
204
# Return response text and tool calls separately
195
205
if functions :
196
206
tool_calls = [
197
- { "type" : "function" , "name" : block .name , "parameters" : block .input }
207
+ self . create_tool_call ( block .name , block .input )
198
208
for block in completion .content
199
209
if block .type == "tool_use"
200
210
]
0 commit comments