7.7.4. OPENAI-04 — Tools and Function Calling
Function calling lets the model ask your program to run a function. The model
does not run anything itself — it returns a tool_calls request, your program
executes it, and you send the result back so the model can use it.
7.7.4.1. Declaring a tool
A Tool wraps a FunctionDef. parameters is a raw JSON-schema string
describing the arguments the model should fill in:
def weather_tool() : Tool {
let params = ("\{\"type\":\"object\"," +
"\"properties\":\{\"location\":\{\"type\":\"string\"\}\}," +
"\"required\":[\"location\"]\}")
return Tool(_type = "function",
_function = FunctionDef(name = "get_weather",
description = "Get the current weather for a location",
parameters = params))
}
(In daslang string literals { and } start interpolation, so literal JSON
braces are escaped as \{ / \}.)
7.7.4.2. Reading the tool call
Send the tools with the request. When the model wants a tool, content is
empty (some servers send content:null — sscan_json decodes that fine)
and tool_calls is populated:
let req = ChatCompletionRequest(model = "gpt-4o-mini",
messages <- [ChatMessage(role = "user", content = "What's the weather in Paris?")],
tools <- [weather_tool()])
let res = chat(client, req)
let tcall = res.response.choices[0].message.tool_calls[0]
print("name={tcall._function.name} args={tcall._function.arguments}\n")
7.7.4.3. Completing the round trip
Execute the function yourself, then send the result back as a message with role
tool, tagged with the tool_call_id the model gave you. The conversation
includes the user turn, the assistant’s tool-call turn, and your tool result:
let req2 = ChatCompletionRequest(model = "gpt-4o-mini", messages <- [
ChatMessage(role = "user", content = "What's the weather in Paris?"),
ChatMessage(role = "assistant", content = "",
tool_calls <- [ToolCall(id = tcall.id, _type = "function",
_function = ToolCallFunction(name = tcall._function.name,
arguments = tcall._function.arguments))]),
ChatMessage(role = "tool", tool_call_id = tcall.id,
content = "\{\"temp_c\":18,\"sky\":\"clear\"\}")])
let res2 = chat(client, req2)
// res2 now contains the model's natural-language answer using the tool result
7.7.4.4. Quick Reference
Type / field |
Description |
|---|---|
|
A declarable function ( |
|
Offer tools on a request |
|
The tool calls the model requested |
|
Function name + JSON argument string |
|
Return a tool result to the model |
See also
Full source: tutorials/dasOPENAI/04_tools_and_function_calling.das
Next tutorial: OPENAI-05 — Embeddings and Models