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:nullsscan_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

Tool / FunctionDef

A declarable function (parameters = JSON schema)

req.tools <- [ ]

Offer tools on a request

message.tool_calls

The tool calls the model requested

ToolCall._function.name / .arguments

Function name + JSON argument string

role = "tool" + tool_call_id

Return a tool result to the model