Skip to content

Parallel Tool Calls

Call multiple tools in parallel within a single response.

This example assumes using Xai; is in scope and apiKey contains your Xai API key.

 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
var client = new XaiClient(apiKey);
var modelId = GetModelId();

// Define multiple tools that the model can call simultaneously.
var tools = new List<ChatCompletionTool>
{
    new ChatCompletionTool
    {
        Type = ChatCompletionToolType.Function,
        Function = new FunctionDefinition
        {
            Name = "get_weather",
            Description = "Get the current weather for a location.",
            Parameters = JsonSerializer.Deserialize<JsonElement>("""
                {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "The city name."
                        }
                    },
                    "required": ["location"]
                }
                """),
        },
    },
    new ChatCompletionTool
    {
        Type = ChatCompletionToolType.Function,
        Function = new FunctionDefinition
        {
            Name = "get_time",
            Description = "Get the current time for a timezone.",
            Parameters = JsonSerializer.Deserialize<JsonElement>("""
                {
                    "type": "object",
                    "properties": {
                        "timezone": {
                            "type": "string",
                            "description": "The IANA timezone name."
                        }
                    },
                    "required": ["timezone"]
                }
                """),
        },
    },
};

// Enable `parallelToolCalls` so the model can invoke multiple tools at once.
var response = await client.Chat.CreateChatCompletionAsync(
    model: modelId,
    messages:
    [
        new ChatCompletionMessage
        {
            Role = ChatCompletionMessageRole.User,
            Content = "What's the weather in Tokyo and what time is it in America/New_York?",
        },
    ],
    tools: tools,
    parallelToolCalls: true,
    toolChoice: new OneOf<CreateChatCompletionRequestToolChoice?, ChatCompletionNamedToolChoice>(
        CreateChatCompletionRequestToolChoice.Auto));

var choice = response.Choices![0];
    "parallel tool calls should produce at least 2 tool calls");

var functionNames = choice.Message.ToolCalls.Select(tc => tc.Function.Name).ToList();

foreach (var tc in choice.Message.ToolCalls)
{
    Console.WriteLine($"{tc.Function.Name}({tc.Function.Arguments})");
}