grok_api 0.1.3

Rust client library for the Grok AI API (xAI)
Documentation
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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
# Tool Support in grok_api


This document describes the tool/function calling support in the `grok_api` crate. Tool calling allows the AI model to request execution of functions and receive their results, enabling dynamic interactions beyond simple text completion.

## Overview


The Grok API supports tool calling (also known as function calling), which allows the model to:
1. Decide when to call external functions based on the conversation
2. Request function execution with specific parameters
3. Receive function results and incorporate them into responses
4. Continue the conversation with context from function results

## Implementation Details


### 1. ChatMessage Structure


The `ChatMessage` struct now fully supports all message types including tool results:

```rust
pub struct ChatMessage {
    pub role: String,
    pub content: Option<MessageContent>,
    pub tool_calls: Option<Vec<ToolCall>>,
    pub tool_call_id: Option<String>,  // NEW: Required for role: "tool"
}
```

**Fields:**
- `role`: The message sender ("system", "user", "assistant", or "tool")
- `content`: The message content (text or multipart)
- `tool_calls`: Tool calls made by the assistant (only for assistant messages)
- `tool_call_id`: ID linking tool results to their calls (required for tool messages)

### 2. Helper Constructors


#### Creating Tool Result Messages


Use the new `ChatMessage::tool()` constructor to create tool result messages:

```rust
let result = ChatMessage::tool("Function returned: success", "call_abc123");
```

This serializes to:
```json
{
  "role": "tool",
  "content": "Function returned: success",
  "tool_call_id": "call_abc123"
}
```

#### Creating Assistant Messages with Tool Calls


```rust
let tool_calls = vec![ToolCall { /* ... */ }];
let msg = ChatMessage::assistant_with_tools(None, tool_calls);
```

This serializes to:
```json
{
  "role": "assistant",
  "content": null,
  "tool_calls": [/* ... */]
}
```

### 3. MessageContent Enhancements


The `MessageContent` type now has improved usability:

#### Display Trait


You can now print content directly:

```rust
let content = MessageContent::Text("Hello".to_string());
println!("{}", content);  // Prints: Hello
```

For multipart content:
```rust
let parts = MessageContent::Parts(vec![
    ContentPart::Text { text: "Check this: ".to_string() },
    ContentPart::ImageUrl { /* ... */ },
]);
println!("{}", parts);  // Prints: Check this: [Image: url]
```

#### Text Helper Method


Get text content with a simple method:

```rust
let content = MessageContent::Text("Hello".to_string());
assert_eq!(content.text(), "Hello");

// For multipart, returns first text part or empty string
let parts = MessageContent::Parts(vec![]);
assert_eq!(parts.text(), "");
```

### 4. ToolCall Structure


The `ToolCall` struct properly serializes for the Grok API:

```rust
pub struct ToolCall {
    pub id: String,                    // Unique identifier
    pub call_type: String,             // Serializes as "type"
    pub function: FunctionCall,        // Function details
}
```

**Important:** The `call_type` field is serialized as `"type"` in JSON using `#[serde(rename = "type")]`.

### 5. Function Call Parsing


Parse function arguments easily:

```rust
let tool_call = ToolCall { /* ... */ };
let args: serde_json::Value = tool_call.function.parse_arguments()?;

// Access parameters
let location = args["location"].as_str().unwrap();
```

## Usage Example


### Basic Tool Calling Flow


```rust
use grok_api::{ChatMessage, GrokClient};
use serde_json::json;

#[tokio::main]

async fn main() -> grok_api::Result<()> {
    let client = GrokClient::builder()
        .api_key(std::env::var("GROK_API_KEY")?)
        .build()?;

    // 1. Define available tools
    let tools = vec![
        json!({
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get current weather",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "City name"
                        }
                    },
                    "required": ["location"]
                }
            }
        })
    ];

    // 2. Start conversation
    let mut messages = vec![
        ChatMessage::system("You are a helpful assistant."),
        ChatMessage::user("What's the weather in Tokyo?"),
    ];

    // 3. Send request with tools
    let response = client
        .chat_with_history(&messages)
        .model("grok-beta")
        .tools(tools.clone())
        .send()
        .await?;

    // 4. Check for tool calls
    if response.has_tool_calls() {
        // Add assistant's message with tool calls
        let assistant_msg = response.message().unwrap();
        messages.push(ChatMessage {
            role: assistant_msg.role.clone(),
            content: assistant_msg.content.clone(),
            tool_calls: assistant_msg.tool_calls.clone(),
            tool_call_id: None,
        });

        // 5. Execute each tool call
        for tool_call in response.tool_calls().unwrap() {
            let args = tool_call.function.parse_arguments()?;
            
            // Execute your function
            let result = match tool_call.function.name.as_str() {
                "get_weather" => {
                    let location = args["location"].as_str().unwrap();
                    get_weather(location) // Your implementation
                }
                _ => "Unknown function".to_string(),
            };

            // 6. Add tool result using the helper
            messages.push(ChatMessage::tool(result, &tool_call.id));
        }

        // 7. Send tool results back
        let final_response = client
            .chat_with_history(&messages)
            .model("grok-beta")
            .tools(tools)
            .send()
            .await?;

        // 8. Get the final answer
        if let Some(content) = final_response.content() {
            println!("Assistant: {}", content);
        }
    }

    Ok(())
}

fn get_weather(location: &str) -> String {
    format!(r#"{{"location": "{}", "temp": "72°F", "condition": "Sunny"}}"#, location)
}
```

## Preventing Infinite Loops


When implementing tool calling, always:

1. **Track conversation history:** Maintain the full message list including all tool calls and results
2. **Add assistant messages:** Include the assistant's message with tool calls before adding tool results
3. **Use correct message types:** Use `ChatMessage::tool()` for tool results, not user or assistant messages
4. **Set tool_call_id:** Every tool result must reference its corresponding tool call ID
5. **Limit iterations:** Implement a maximum number of tool call rounds to prevent endless loops

### Anti-Pattern Example (DO NOT DO THIS)


```rust
// ❌ BAD: Missing conversation context
loop {
    let response = client.chat("Tell me the weather").send().await?;
    // This loses context and may cause repeated tool calls
}
```

### Correct Pattern


```rust
// ✅ GOOD: Maintaining full conversation history
let mut messages = vec![ChatMessage::user("Tell me the weather")];
let mut iterations = 0;
const MAX_ITERATIONS: usize = 5;

while iterations < MAX_ITERATIONS {
    let response = client
        .chat_with_history(&messages)
        .tools(tools.clone())
        .send()
        .await?;

    if !response.has_tool_calls() {
        // Got final answer
        break;
    }

    // Add assistant message with tool calls
    messages.push(/* assistant message with tool_calls */);

    // Execute tools and add results
    for tool_call in response.tool_calls().unwrap() {
        let result = execute_tool(tool_call);
        messages.push(ChatMessage::tool(result, &tool_call.id));
    }

    iterations += 1;
}
```

## Serialization Format


### Tool Message JSON


```json
{
  "role": "tool",
  "content": "Weather data: 72°F, Sunny",
  "tool_call_id": "call_abc123"
}
```

### Assistant with Tool Calls JSON


```json
{
  "role": "assistant",
  "content": null,
  "tool_calls": [
    {
      "id": "call_abc123",
      "type": "function",
      "function": {
        "name": "get_weather",
        "arguments": "{\"location\":\"Tokyo\"}"
      }
    }
  ]
}
```

## Testing


The crate includes comprehensive tests for tool support:

- `test_tool_message_creation`: Verifies tool message constructor
- `test_tool_message_serialization`: Validates JSON format
- `test_assistant_with_tool_calls_serialization`: Tests assistant tool calls
- `test_round_trip_tool_message`: Ensures serialization/deserialization works
- `test_tool_call_type_rename`: Confirms `call_type` serializes as `"type"`

Run tests with:
```bash
cargo test --lib
```

## Examples


See `examples/tools_example.rs` for a complete working example demonstrating:
- Multiple tool definitions
- Tool call handling
- Result processing
- Conversation continuation

Run with:
```bash
cargo run --example tools_example
```

## Migration Guide


If you have existing code using the `grok_api` crate:

### Before (No Tool Support)


```rust
let messages = vec![ChatMessage::user("Hello")];
let response = client.chat_with_history(&messages).send().await?;
```

### After (With Tool Support)


```rust
let tools = vec![/* tool definitions */];
let mut messages = vec![ChatMessage::user("Hello")];

let response = client
    .chat_with_history(&messages)
    .tools(tools)
    .send()
    .await?;

if response.has_tool_calls() {
    // Handle tool calls
    for tool_call in response.tool_calls().unwrap() {
        let result = execute_tool(tool_call);
        messages.push(ChatMessage::tool(result, &tool_call.id));
    }
    // Send tool results back...
}
```

## API Reference


### New Methods


- `ChatMessage::tool(content, tool_call_id)` - Create tool result message
- `MessageContent::text()` - Get text content or empty string
- `ChatResponse::has_tool_calls()` - Check if response includes tool calls
- `ChatResponse::tool_calls()` - Get tool calls slice
- `Model::parse(s)` - Parse model from string (renamed from `from_str`)

### Updated Structs


- `ChatMessage` now includes `tool_call_id` field
- `MessageContent` implements `Display` trait

## Best Practices


1. **Define Clear Tool Descriptions**: Help the model understand when to use each tool
2. **Validate Arguments**: Always validate parsed arguments before execution
3. **Handle Errors Gracefully**: Return error information as tool results
4. **Limit Tool Iterations**: Prevent infinite loops with max iteration counts
5. **Log Tool Calls**: Debug by logging tool calls and results
6. **Use Appropriate Models**: Some models handle tools better than others
7. **Structure Tool Results**: Return JSON strings for structured data

## Troubleshooting


### Model Not Calling Tools


- Ensure tool descriptions are clear and relevant
- Check that the model supports tool calling
- Verify tool definitions follow the correct JSON schema

### Infinite Tool Call Loops


- Implement iteration limits
- Maintain full conversation history
- Always add assistant messages before tool results
- Ensure `tool_call_id` matches the original call

### Serialization Errors


- Verify `tool_call_id` is set for tool messages
- Check that `call_type` is "function"
- Ensure tool result content is a string

## Additional Resources


- [Grok API Documentation]https://docs.x.ai/api
- [OpenAI Function Calling Guide]https://platform.openai.com/docs/guides/function-calling (Similar patterns)
- `examples/tools_example.rs` - Complete working example
- `src/models.rs` - Full type definitions

## Changelog


### Version 0.1.2 (2025-01-15)


- ✅ Added `tool_call_id` field to `ChatMessage`
- ✅ Added `ChatMessage::tool()` helper constructor
- ✅ Implemented `Display` trait for `MessageContent`
- ✅ Added `MessageContent::text()` helper method
- ✅ Added serialization verification tests
- ✅ Renamed `Model::from_str()` to `Model::parse()` (clippy fix)
- ✅ Fixed `has_tool_calls()` to use `is_some_and()` (clippy fix)
- ✅ Created comprehensive tool usage example
- ✅ All tests passing with clippy clean

---

**Note**: This implementation is based on the Grok API specification and follows patterns similar to OpenAI's function calling API.