radkit 0.0.5

Rust AI Agent Development Kit
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
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
//! XAI Grok LLM provider implementation.
//!
//! API Documentation: <https://docs.x.ai/api>
//! Model Names: <https://docs.x.ai/docs>

use std::sync::Arc;

use serde_json::{json, Value};

use crate::errors::{AgentError, AgentResult};
use crate::models::{BaseLlm, Content, ContentPart, LlmResponse, Role, Thread, TokenUsage};
use crate::tools::{BaseToolset, ToolCall};

const GROK_BASE_URL: &str = "https://api.x.ai/v1/chat/completions";

/// XAI Grok LLM implementation.
///
/// Provides access to Grok models through the XAI API.
/// The API is OpenAI-compatible with some differences in token counting.
///
/// # Authentication
///
/// The API key can be provided explicitly or loaded from the `XAI_API_KEY`
/// environment variable via [`from_env`](GrokLlm::from_env).
///
/// # Model Selection
///
/// Common model names:
/// - `grok-beta` - Grok Beta
/// - `grok-vision-beta` - Grok Vision Beta
///
/// # Token Counting Bug
///
/// **Important**: Grok has a known bug where `reasoning_tokens` in
/// `completion_tokens_details` is NOT included in the top-level `completion_tokens`.
/// This implementation automatically corrects this by adding `reasoning_tokens`
/// to `completion_tokens` for accurate usage tracking.
///
/// # Examples
///
/// ```ignore
/// use radkit::models::providers::GrokLlm;
/// use radkit::models::{BaseLlm, Thread};
///
/// // From environment variable
/// let llm = GrokLlm::from_env("grok-beta")?;
///
/// // With explicit API key
/// let llm = GrokLlm::new("grok-beta", "xai-...");
///
/// // Generate content
/// let thread = Thread::from_user("Explain quantum computing");
/// let response = llm.generate_content(thread, None).await?;
/// println!("{}", response.content().first_text().unwrap_or("No response"));
/// ```
pub struct GrokLlm {
    model_name: String,
    api_key: String,
    base_url: String,
    max_tokens: Option<u32>,
    temperature: Option<f32>,
}

impl GrokLlm {
    /// Environment variable name for the XAI API key.
    pub const API_KEY_ENV: &str = "XAI_API_KEY";

    /// Creates a new Grok LLM instance with explicit API key.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The model to use (e.g., "grok-beta")
    /// * `api_key` - XAI API key
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let llm = GrokLlm::new("grok-beta", "xai-...");
    /// ```
    pub fn new(model_name: impl Into<String>, api_key: impl Into<String>) -> Self {
        Self {
            model_name: model_name.into(),
            api_key: api_key.into(),
            base_url: GROK_BASE_URL.to_string(),
            max_tokens: None,
            temperature: None,
        }
    }

    /// Creates a new Grok LLM instance loading API key from environment.
    ///
    /// Reads the API key from the `XAI_API_KEY` environment variable.
    ///
    /// # Arguments
    ///
    /// * `model_name` - The model to use (e.g., "grok-beta")
    ///
    /// # Errors
    ///
    /// Returns an error if the environment variable is not set or is empty.
    ///
    /// # Examples
    ///
    /// ```ignore
    /// let llm = GrokLlm::from_env("grok-beta")?;
    /// ```
    pub fn from_env(model_name: impl Into<String>) -> AgentResult<Self> {
        let api_key =
            std::env::var(Self::API_KEY_ENV).map_err(|_| AgentError::MissingConfiguration {
                field: Self::API_KEY_ENV.to_string(),
            })?;

        if api_key.is_empty() {
            return Err(AgentError::InvalidConfiguration {
                field: Self::API_KEY_ENV.to_string(),
                reason: "API key cannot be empty".to_string(),
            });
        }

        Ok(Self::new(model_name, api_key))
    }

    /// Sets a custom base URL for the API endpoint.
    #[must_use]
    pub fn with_base_url(mut self, base_url: impl Into<String>) -> Self {
        self.base_url = base_url.into();
        self
    }

    /// Sets the maximum number of tokens to generate.
    #[must_use]
    pub const fn with_max_tokens(mut self, max_tokens: u32) -> Self {
        self.max_tokens = Some(max_tokens);
        self
    }

    /// Sets the temperature for generation (0.0 to 2.0).
    ///
    /// Higher values produce more random outputs.
    #[must_use]
    pub const fn with_temperature(mut self, temperature: f32) -> Self {
        self.temperature = Some(temperature);
        self
    }

    /// Converts a Thread into Grok API request format (OpenAI-compatible).
    async fn build_request_payload(
        &self,
        thread: Thread,
        toolset: Option<Arc<dyn BaseToolset>>,
    ) -> AgentResult<Value> {
        let (system_prompt, events) = thread.into_parts();

        // Build messages array (OpenAI format)
        let mut messages = Vec::new();

        // Add system prompt as first message if present
        if let Some(system) = system_prompt {
            messages.push(json!({
                "role": "system",
                "content": system
            }));
        }

        Self::build_messages_from_events(events, &mut messages);

        // Build the base payload
        let mut payload = json!({
            "model": self.model_name,
            "messages": messages
        });

        // Add optional parameters
        if let Some(temperature) = self.temperature {
            payload["temperature"] = json!(temperature);
        }

        if let Some(max_tokens) = self.max_tokens {
            payload["max_tokens"] = json!(max_tokens);
        }

        // Add tools if provided
        Self::add_tools_to_payload(&mut payload, toolset).await;

        Ok(payload)
    }

    /// Builds OpenAI-formatted messages from thread events.
    fn build_messages_from_events(events: Vec<crate::models::Event>, messages: &mut Vec<Value>) {
        for event in events {
            let role = *event.role();
            let role_str = match &role {
                Role::User => "user",
                Role::Assistant => "assistant",
                Role::Tool => "tool",
                Role::System => "system",
            };

            let content = event.into_content();

            match role {
                Role::System | Role::User => {
                    Self::process_user_or_system_message(role_str, content, messages);
                }
                Role::Assistant => {
                    Self::process_assistant_message(content, messages);
                }
                Role::Tool => {
                    Self::process_tool_message(content, messages);
                }
            }
        }
    }

    /// Processes user or system messages.
    fn process_user_or_system_message(role_str: &str, content: Content, messages: &mut Vec<Value>) {
        if content.is_text_only() && !content.is_text_empty() {
            let text = content.joined_texts().unwrap_or_default();
            messages.push(json!({
                "role": role_str,
                "content": text
            }));
        } else {
            let mut content_parts = Vec::new();

            for part in content {
                match part {
                    ContentPart::Text(text) => {
                        content_parts.push(json!({
                            "type": "text",
                            "text": text
                        }));
                    }
                    ContentPart::Data(data) => {
                        if data.content_type.starts_with("image/") {
                            let image_url = match data.source {
                                crate::models::DataSource::Base64(b64) => {
                                    format!("data:{};base64,{}", data.content_type, b64)
                                }
                                crate::models::DataSource::Uri(uri) => uri,
                            };
                            content_parts.push(json!({
                                "type": "image_url",
                                "image_url": {
                                    "url": image_url
                                }
                            }));
                        }
                    }
                    ContentPart::ToolCall(_) | ContentPart::ToolResponse(_) => {}
                }
            }

            if !content_parts.is_empty() {
                messages.push(json!({
                    "role": role_str,
                    "content": content_parts
                }));
            }
        }
    }

    /// Processes assistant messages with optional tool calls.
    fn process_assistant_message(content: Content, messages: &mut Vec<Value>) {
        let mut texts = Vec::new();
        let mut tool_calls = Vec::new();

        for part in content {
            match part {
                ContentPart::Text(text) => texts.push(text),
                ContentPart::ToolCall(tool_call) => {
                    tool_calls.push(json!({
                        "type": "function",
                        "id": tool_call.id(),
                        "function": {
                            "name": tool_call.name(),
                            "arguments": tool_call.arguments().to_string()
                        }
                    }));
                }
                _ => {}
            }
        }

        let content_text = texts.join("\n\n");
        let mut message = json!({
            "role": "assistant",
            "content": content_text
        });

        if !tool_calls.is_empty() {
            message["tool_calls"] = json!(tool_calls);
        }

        messages.push(message);
    }

    /// Processes tool response messages.
    fn process_tool_message(content: Content, messages: &mut Vec<Value>) {
        for part in content {
            if let ContentPart::ToolResponse(tool_response) = part {
                let result = tool_response.result();
                let content_value = if result.is_success() {
                    result.data().to_string()
                } else {
                    json!({
                        "error": result.error_message().unwrap_or("Unknown error")
                    })
                    .to_string()
                };

                messages.push(json!({
                    "role": "tool",
                    "content": content_value,
                    "tool_call_id": tool_response.tool_call_id()
                }));
            }
        }
    }

    /// Adds tool configuration to the payload if tools are available.
    async fn add_tools_to_payload(payload: &mut Value, toolset: Option<Arc<dyn BaseToolset>>) {
        if let Some(toolset) = toolset {
            let tools_list = toolset.get_tools().await;
            if !tools_list.is_empty() {
                let tools: Vec<Value> = tools_list
                    .iter()
                    .map(|tool| {
                        let decl = tool.declaration();
                        json!({
                            "type": "function",
                            "function": {
                                "name": decl.name(),
                                "description": decl.description(),
                                "parameters": decl.parameters(),
                                "strict": false
                            }
                        })
                    })
                    .collect();

                payload["tools"] = json!(tools);
            }
        }
    }

    /// Parses Grok API response into Content (`OpenAI` format).
    fn parse_response(response_body: &Value) -> AgentResult<Content> {
        let mut content = Content::default();

        let first_choice = response_body
            .get("choices")
            .and_then(|v| v.as_array())
            .and_then(|arr| arr.first())
            .ok_or_else(|| AgentError::LlmProvider {
                provider: "Grok".to_string(),
                message: "Missing or invalid 'choices' field in response".to_string(),
            })?;

        let message = first_choice
            .get("message")
            .ok_or_else(|| AgentError::LlmProvider {
                provider: "Grok".to_string(),
                message: "Missing 'message' field in choice".to_string(),
            })?;

        if let Some(text) = message.get("content").and_then(|v| v.as_str()) {
            if !text.trim().is_empty() {
                content.push(ContentPart::Text(text.trim().to_string()));
            }
        }

        if let Some(tool_calls) = message.get("tool_calls").and_then(|v| v.as_array()) {
            for tool_call in tool_calls {
                let id = tool_call
                    .get("id")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| AgentError::LlmProvider {
                        provider: "Grok".to_string(),
                        message: "Missing 'id' in tool call".to_string(),
                    })?;

                let function =
                    tool_call
                        .get("function")
                        .ok_or_else(|| AgentError::LlmProvider {
                            provider: "Grok".to_string(),
                            message: "Missing 'function' in tool call".to_string(),
                        })?;

                let name = function
                    .get("name")
                    .and_then(|v| v.as_str())
                    .ok_or_else(|| AgentError::LlmProvider {
                        provider: "Grok".to_string(),
                        message: "Missing 'name' in tool call function".to_string(),
                    })?;

                let arguments = function.get("arguments").cloned().unwrap_or(Value::Null);
                let arguments = match arguments {
                    Value::String(s) => serde_json::from_str(&s).unwrap_or(Value::Null),
                    other => other,
                };

                content.push(ContentPart::ToolCall(ToolCall::new(id, name, arguments)));
            }
        }

        Ok(content)
    }

    /// Parses token usage from Grok API response.
    ///
    /// **Important**: Grok has a bug where `reasoning_tokens` in `completion_tokens_details`
    /// is NOT included in the main `completion_tokens`. This function corrects for this bug
    /// by adding `reasoning_tokens` to `completion_tokens` when present.
    fn parse_usage(response_body: &Value) -> TokenUsage {
        let Some(usage_obj) = response_body.get("usage") else {
            return TokenUsage::empty();
        };

        let prompt_tokens = usage_obj
            .get("prompt_tokens")
            .and_then(serde_json::Value::as_u64)
            .map(|v| u32::try_from(v).unwrap_or(u32::MAX));

        let mut completion_tokens = usage_obj
            .get("completion_tokens")
            .and_then(serde_json::Value::as_u64)
            .map(|v| u32::try_from(v).unwrap_or(u32::MAX));

        // Check for reasoning_tokens in completion_tokens_details
        let reasoning_tokens = usage_obj
            .get("completion_tokens_details")
            .and_then(|details| details.get("reasoning_tokens"))
            .and_then(serde_json::Value::as_u64)
            .map(|v| u32::try_from(v).unwrap_or(u32::MAX));

        // Fix Grok's bug: reasoning_tokens are NOT included in completion_tokens
        // We must add them manually for accurate token counting
        if let (Some(completion), Some(reasoning)) = (completion_tokens, reasoning_tokens) {
            completion_tokens = Some(completion + reasoning);
        }

        let total_tokens = usage_obj
            .get("total_tokens")
            .and_then(serde_json::Value::as_u64)
            .map(|v| u32::try_from(v).unwrap_or(u32::MAX));

        TokenUsage::partial(prompt_tokens, completion_tokens, total_tokens)
    }
}

#[cfg_attr(all(target_os = "wasi", target_env = "p1"), async_trait::async_trait(?Send))]
#[cfg_attr(
    not(all(target_os = "wasi", target_env = "p1")),
    async_trait::async_trait
)]
impl BaseLlm for GrokLlm {
    fn model_name(&self) -> &str {
        &self.model_name
    }

    async fn generate_content(
        &self,
        thread: Thread,
        toolset: Option<Arc<dyn BaseToolset>>,
    ) -> AgentResult<LlmResponse> {
        // Build request payload
        let payload = self.build_request_payload(thread, toolset).await?;

        // Create HTTP client
        let client = reqwest::Client::new();

        // Make request
        let response = client
            .post(&self.base_url)
            .header("Authorization", format!("Bearer {}", self.api_key))
            .header("Content-Type", "application/json")
            .json(&payload)
            .send()
            .await?;

        // Check for HTTP errors
        if !response.status().is_success() {
            let status = response.status();
            let error_body = response
                .text()
                .await
                .unwrap_or_else(|_| "Unknown error".to_string());

            return Err(match status.as_u16() {
                401 | 403 => AgentError::LlmAuthentication {
                    provider: "Grok".to_string(),
                },
                429 => AgentError::LlmRateLimit {
                    provider: "Grok".to_string(),
                },
                _ => AgentError::LlmProvider {
                    provider: "Grok".to_string(),
                    message: format!("HTTP {status}: {error_body}"),
                },
            });
        }

        // Parse response
        let response_body: Value = response.json().await?;

        // Parse content and usage
        let content = Self::parse_response(&response_body)?;
        let usage = Self::parse_usage(&response_body);

        Ok(LlmResponse::new(content, usage))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::models::Event;
    use crate::tools::BaseTool;

    struct TestTool;

    #[cfg_attr(all(target_os = "wasi", target_env = "p1"), async_trait::async_trait(?Send))]
    #[cfg_attr(
        not(all(target_os = "wasi", target_env = "p1")),
        async_trait::async_trait
    )]
    impl BaseTool for TestTool {
        fn name(&self) -> &'static str {
            "grok_tool"
        }

        fn description(&self) -> &'static str {
            "Test tool"
        }

        fn declaration(&self) -> crate::tools::FunctionDeclaration {
            crate::tools::FunctionDeclaration::new(
                "grok_tool",
                "Test tool",
                serde_json::json!({"type": "object"}),
            )
        }

        async fn run_async(
            &self,
            _args: std::collections::HashMap<String, Value>,
            _context: &crate::tools::ToolContext<'_>,
        ) -> crate::tools::ToolResult {
            crate::tools::ToolResult::success(serde_json::json!({}))
        }
    }

    struct SimpleToolset(Vec<Box<dyn BaseTool>>);

    #[cfg_attr(all(target_os = "wasi", target_env = "p1"), async_trait::async_trait(?Send))]
    #[cfg_attr(
        not(all(target_os = "wasi", target_env = "p1")),
        async_trait::async_trait
    )]
    impl BaseToolset for SimpleToolset {
        async fn get_tools(&self) -> Vec<&dyn BaseTool> {
            self.0.iter().map(std::convert::AsRef::as_ref).collect()
        }

        async fn close(&self) {}
    }

    #[tokio::test(flavor = "current_thread")]
    async fn build_request_payload_includes_tools() {
        let llm = GrokLlm::new("grok-beta", "api-key")
            .with_max_tokens(256)
            .with_temperature(0.4);

        let thread = Thread::from_system("System prompt")
            .add_event(Event::user("Hello"))
            .add_event(Event::assistant("Working"));

        let payload = llm
            .build_request_payload(
                thread,
                Some(Arc::new(SimpleToolset(vec![
                    Box::new(TestTool) as Box<dyn BaseTool>
                ]))),
            )
            .await
            .expect("payload");

        assert_eq!(payload["model"], json!("grok-beta"));
        assert_eq!(payload["max_tokens"], json!(256));
        let temperature = payload["temperature"].as_f64().expect("temperature");
        assert!((temperature - 0.4).abs() < 1e-6);

        let tools = payload["tools"].as_array().expect("tools array");
        assert_eq!(tools.len(), 1);
        assert_eq!(tools[0]["function"]["name"], json!("grok_tool"));
    }

    #[test]
    fn parse_response_extracts_text_and_tool_calls() {
        let _llm = GrokLlm::new("grok-beta", "api-key");
        let body = json!({
            "choices": [
                {
                    "message": {
                        "content": "Hello user",
                        "tool_calls": [
                            {
                                "id": "call-1",
                                "function": {
                                    "name": "lookup",
                                    "arguments": "{\"key\":\"value\"}"
                                }
                            }
                        ]
                    }
                }
            ],
            "usage": {
                "prompt_tokens": 9,
                "completion_tokens": 4,
                "total_tokens": 13,
                "completion_tokens_details": {
                    "reasoning_tokens": 3
                }
            }
        });

        let content = GrokLlm::parse_response(&body).expect("content");
        assert_eq!(content.first_text(), Some("Hello user"));
        let calls = content.tool_calls();
        assert_eq!(calls.len(), 1);
        assert_eq!(calls[0].name(), "lookup");

        let usage = GrokLlm::parse_usage(&body);
        assert_eq!(usage.input_tokens_opt(), Some(9));
        assert_eq!(usage.output_tokens_opt(), Some(7));
        assert_eq!(usage.total_tokens_opt(), Some(13));
    }

    #[test]
    fn parse_response_missing_choices_errors() {
        let _llm = GrokLlm::new("grok-beta", "api-key");
        let body = json!({});
        let err = GrokLlm::parse_response(&body).expect_err("expected error");
        match err {
            AgentError::LlmProvider { provider, .. } => assert_eq!(provider, "Grok"),
            other => panic!("unexpected error: {other:?}"),
        }
    }

    #[test]
    fn from_env_validates_presence() {
        let original = std::env::var(GrokLlm::API_KEY_ENV).ok();
        std::env::remove_var(GrokLlm::API_KEY_ENV);

        let missing = GrokLlm::from_env("model");
        assert!(matches!(
            missing,
            Err(AgentError::MissingConfiguration { .. })
        ));

        std::env::set_var(GrokLlm::API_KEY_ENV, "");
        let empty = GrokLlm::from_env("model");
        assert!(matches!(
            empty,
            Err(AgentError::InvalidConfiguration { .. })
        ));

        match original {
            Some(value) => std::env::set_var(GrokLlm::API_KEY_ENV, value),
            None => std::env::remove_var(GrokLlm::API_KEY_ENV),
        }
    }
}