liteforge 0.2.4

Rust SDK for LiteForge - LLM completions via OpenAI-compatible API
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
//! Code execution agent.

use super::context::{AgentContext, AgentState};
use super::sandbox::{ExecutionResult, Language, ProcessSandbox, Sandbox, SandboxConfig};
use super::step::{AgentStep, StepResult, StepType, TokenUsage};
use super::traits::{Agent, AgentConfig, AgentError, AgentResult};
use crate::client::AsyncForgeClient;
use crate::types::{ChatCompletionRequest, Message, ToolCall, ToolDefinition, ToolParameters};
use async_trait::async_trait;
use serde::{Deserialize, Serialize};
use std::sync::Arc;
use std::time::Instant;

/// Configuration for the code agent.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeAgentConfig {
    /// Base agent configuration.
    #[serde(flatten)]
    pub agent: AgentConfig,
    /// Sandbox configuration.
    #[serde(default)]
    pub sandbox: SandboxConfig,
    /// Default language for code execution.
    #[serde(default)]
    pub default_language: Option<Language>,
    /// Whether to auto-detect language.
    #[serde(default = "default_true")]
    pub auto_detect_language: bool,
    /// Maximum code length.
    #[serde(default = "default_max_code_length")]
    pub max_code_length: usize,
}

fn default_true() -> bool {
    true
}

fn default_max_code_length() -> usize {
    100_000
}

impl Default for CodeAgentConfig {
    fn default() -> Self {
        Self {
            agent: AgentConfig::new("code-agent").with_system_prompt(DEFAULT_SYSTEM_PROMPT),
            sandbox: SandboxConfig::default(),
            default_language: Some(Language::Python),
            auto_detect_language: true,
            max_code_length: default_max_code_length(),
        }
    }
}

impl CodeAgentConfig {
    /// Create a new code agent config.
    pub fn new() -> Self {
        Self::default()
    }

    /// Set the system prompt.
    pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.agent.system_prompt = Some(prompt.into());
        self
    }

    /// Set the model.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.agent.model = Some(model.into());
        self
    }

    /// Set sandbox configuration.
    pub fn with_sandbox(mut self, config: SandboxConfig) -> Self {
        self.sandbox = config;
        self
    }

    /// Set default language.
    pub fn with_default_language(mut self, language: Language) -> Self {
        self.default_language = Some(language);
        self
    }
}

const DEFAULT_SYSTEM_PROMPT: &str = r#"You are a code execution assistant. When asked to write and run code:

1. Analyze the request and determine the best approach
2. Write clean, well-documented code
3. Use the execute_code tool to run the code
4. Analyze the output and provide a clear explanation

Available languages: Python, JavaScript, Shell, Ruby

Guidelines:
- Write safe, efficient code
- Handle errors gracefully
- Explain what the code does and its output
- If the code fails, analyze the error and try to fix it
"#;

/// An agent that can write and execute code.
pub struct CodeAgent {
    client: AsyncForgeClient,
    config: CodeAgentConfig,
    context: AgentContext,
    sandbox: Arc<dyn Sandbox>,
    execution_history: Vec<CodeExecution>,
}

/// Record of a code execution.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct CodeExecution {
    /// The code that was executed.
    pub code: String,
    /// The language used.
    pub language: Language,
    /// The execution result.
    pub result: ExecutionResult,
}

impl CodeAgent {
    /// Create a new code agent.
    pub fn new(client: AsyncForgeClient) -> Self {
        Self::with_config(client, CodeAgentConfig::default())
    }

    /// Create a code agent with configuration.
    pub fn with_config(client: AsyncForgeClient, config: CodeAgentConfig) -> Self {
        let name = config.agent.name.clone();
        let max_steps = config.agent.max_steps;
        let mut context = AgentContext::new(&name);
        context.max_steps = max_steps;
        Self {
            client,
            config,
            context,
            sandbox: Arc::new(ProcessSandbox::new()),
            execution_history: Vec::new(),
        }
    }

    /// Create a code agent with a custom sandbox.
    pub fn with_sandbox<S: Sandbox + 'static>(mut self, sandbox: S) -> Self {
        self.sandbox = Arc::new(sandbox);
        self
    }

    /// Set the system prompt.
    pub fn with_system_prompt(mut self, prompt: impl Into<String>) -> Self {
        self.config.agent.system_prompt = Some(prompt.into());
        self
    }

    /// Set the model.
    pub fn with_model(mut self, model: impl Into<String>) -> Self {
        self.config.agent.model = Some(model.into());
        self
    }

    /// Get the execution history.
    pub fn execution_history(&self) -> &[CodeExecution] {
        &self.execution_history
    }

    /// Execute code directly.
    pub async fn execute_code(
        &mut self,
        code: &str,
        language: Option<Language>,
    ) -> AgentResult<ExecutionResult> {
        let language = language
            .or_else(|| {
                if self.config.auto_detect_language {
                    Language::detect(code)
                } else {
                    None
                }
            })
            .or(self.config.default_language)
            .ok_or_else(|| {
                AgentError::ConfigError("Could not determine language for code".to_string())
            })?;

        if code.len() > self.config.max_code_length {
            return Err(AgentError::ConfigError(format!(
                "Code exceeds maximum length of {} characters",
                self.config.max_code_length
            )));
        }

        let result = self
            .sandbox
            .execute(code, language, &self.config.sandbox)
            .await
            .map_err(|e| AgentError::Other(format!("Sandbox error: {}", e)))?;

        self.execution_history.push(CodeExecution {
            code: code.to_string(),
            language,
            result: result.clone(),
        });

        Ok(result)
    }

    /// Get the tool definition for code execution.
    fn code_execution_tool() -> ToolDefinition {
        let mut properties = serde_json::Map::new();
        properties.insert(
            "code".to_string(),
            serde_json::json!({
                "type": "string",
                "description": "The code to execute"
            }),
        );
        properties.insert(
            "language".to_string(),
            serde_json::json!({
                "type": "string",
                "enum": ["python", "javascript", "shell", "ruby"],
                "description": "The programming language (optional, will auto-detect if not provided)"
            }),
        );

        ToolDefinition {
            tool_type: "function".to_string(),
            function: crate::types::FunctionDefinition {
                name: "execute_code".to_string(),
                description: Some(
                    "Execute code in a sandboxed environment. Supports Python, JavaScript, Shell, and Ruby."
                        .to_string(),
                ),
                parameters: Some(ToolParameters {
                    schema_type: "object".to_string(),
                    properties,
                    required: Some(vec!["code".to_string()]),
                }),
            },
        }
    }

    async fn handle_tool_call(&mut self, tool_call: &ToolCall) -> AgentResult<String> {
        if tool_call.function.name != "execute_code" {
            return Err(AgentError::ToolError {
                tool_name: tool_call.function.name.clone(),
                message: "Unknown tool".to_string(),
            });
        }

        let args: serde_json::Value =
            serde_json::from_str(&tool_call.function.arguments).map_err(|e| {
                AgentError::ToolError {
                    tool_name: tool_call.function.name.clone(),
                    message: format!("Invalid arguments: {}", e),
                }
            })?;

        let code = args["code"].as_str().ok_or_else(|| AgentError::ToolError {
            tool_name: tool_call.function.name.clone(),
            message: "Missing 'code' argument".to_string(),
        })?;

        let language = args["language"]
            .as_str()
            .and_then(|l| match l.to_lowercase().as_str() {
                "python" => Some(Language::Python),
                "javascript" | "js" => Some(Language::JavaScript),
                "shell" | "bash" | "sh" => Some(Language::Shell),
                "ruby" | "rb" => Some(Language::Ruby),
                _ => None,
            });

        let result = self.execute_code(code, language).await?;

        Ok(serde_json::json!({
            "success": result.success(),
            "exit_code": result.exit_code,
            "stdout": result.stdout,
            "stderr": result.stderr,
            "execution_time_ms": result.execution_time_ms,
            "timed_out": result.timed_out
        })
        .to_string())
    }
}

#[async_trait]
impl Agent for CodeAgent {
    fn name(&self) -> &str {
        &self.config.agent.name
    }

    fn config(&self) -> &AgentConfig {
        &self.config.agent
    }

    fn context_mut(&mut self) -> &mut AgentContext {
        &mut self.context
    }

    fn context(&self) -> &AgentContext {
        &self.context
    }

    async fn step(&mut self) -> AgentResult<AgentStep> {
        let start = Instant::now();
        let step_number = self.context.current_step;

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

        // Add system prompt
        if let Some(ref prompt) = self.config.agent.system_prompt {
            messages.push(Message::system(prompt));
        }

        // Add conversation history
        messages.extend(self.context.memory.messages().iter().cloned());

        // Get model
        let model = self
            .config
            .agent
            .model
            .clone()
            .unwrap_or_else(|| "gpt-4".to_string());

        // Build request
        let mut request = ChatCompletionRequest::new(model, messages);

        // Add code execution tool
        request = request.tools(vec![Self::code_execution_tool()]);

        // Set temperature if configured
        if let Some(temp) = self.config.agent.temperature {
            request = request.temperature(temp);
        }

        // Make the request
        let response = self.client.chat_completions(request).await?;

        let choice = response
            .choices
            .first()
            .ok_or_else(|| AgentError::Other("No response from LLM".to_string()))?;

        // Check for tool calls
        if let Some(ref tool_calls) = choice.message.tool_calls {
            if !tool_calls.is_empty() {
                // Add assistant message with tool calls to memory
                self.context.memory.add_message(choice.message.clone());

                // Execute tool calls
                let mut tool_results = Vec::new();
                for tool_call in tool_calls {
                    let result = self.handle_tool_call(tool_call).await?;
                    tool_results.push((tool_call.id.clone(), result));
                }

                // Add tool results to memory
                for (id, result) in &tool_results {
                    self.context.memory.add_message(Message::tool(id, result));
                }

                let step = AgentStep::new(
                    step_number,
                    StepType::ToolCall {
                        tool_name: tool_calls
                            .iter()
                            .map(|c| c.function.name.clone())
                            .collect::<Vec<_>>()
                            .join(", "),
                        call_id: tool_calls.first().map(|c| c.id.clone()).unwrap_or_default(),
                    },
                )
                .with_result(StepResult::ToolCalls {
                    calls: tool_calls.clone(),
                })
                .with_duration(start.elapsed())
                .with_tokens(TokenUsage {
                    prompt_tokens: response
                        .usage
                        .as_ref()
                        .map(|u| u.prompt_tokens)
                        .unwrap_or(0),
                    completion_tokens: response
                        .usage
                        .as_ref()
                        .map(|u| u.completion_tokens)
                        .unwrap_or(0),
                    total_tokens: response.usage.as_ref().map(|u| u.total_tokens).unwrap_or(0),
                });

                return Ok(step);
            }
        }

        // No tool calls - this is the final response
        let content = choice.message.content.clone().unwrap_or_default();

        // Add to memory
        self.context.memory.add_message(choice.message.clone());
        self.context.state = AgentState::Completed;

        let step = AgentStep::new(step_number, StepType::Response)
            .with_result(StepResult::Done { response: content })
            .with_duration(start.elapsed())
            .with_tokens(TokenUsage {
                prompt_tokens: response
                    .usage
                    .as_ref()
                    .map(|u| u.prompt_tokens)
                    .unwrap_or(0),
                completion_tokens: response
                    .usage
                    .as_ref()
                    .map(|u| u.completion_tokens)
                    .unwrap_or(0),
                total_tokens: response.usage.as_ref().map(|u| u.total_tokens).unwrap_or(0),
            });

        Ok(step)
    }

    fn reset(&mut self) {
        self.context.reset();
        self.execution_history.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::agents::sandbox::MockSandbox;

    #[test]
    fn test_code_agent_config() {
        let config = CodeAgentConfig::new()
            .with_model("gpt-4")
            .with_default_language(Language::Python);

        assert_eq!(config.agent.model, Some("gpt-4".to_string()));
        assert_eq!(config.default_language, Some(Language::Python));
    }

    #[test]
    fn test_code_execution_tool() {
        let tool = CodeAgent::code_execution_tool();
        assert_eq!(tool.function.name, "execute_code");
        assert!(tool.function.description.is_some());
    }

    #[tokio::test]
    async fn test_code_agent_execute_code() {
        let client = AsyncForgeClient::new();
        let mock_sandbox = MockSandbox::new().with_result(ExecutionResult {
            exit_code: 0,
            stdout: "Hello, World!".to_string(),
            stderr: String::new(),
            execution_time_ms: 10,
            timed_out: false,
            output_files: Vec::new(),
        });

        let mut agent = CodeAgent::new(client).with_sandbox(mock_sandbox);

        let result = agent
            .execute_code("print('Hello, World!')", Some(Language::Python))
            .await
            .unwrap();

        assert!(result.success());
        assert_eq!(result.stdout, "Hello, World!");
        assert_eq!(agent.execution_history().len(), 1);
    }

    #[test]
    fn test_code_execution_record() {
        let record = CodeExecution {
            code: "print(42)".to_string(),
            language: Language::Python,
            result: ExecutionResult {
                exit_code: 0,
                stdout: "42\n".to_string(),
                stderr: String::new(),
                execution_time_ms: 5,
                timed_out: false,
                output_files: Vec::new(),
            },
        };

        assert!(record.result.success());
    }
}