> For the complete documentation index, see [llms.txt](https://calliopeide.gitbook.io/calliopeide/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://calliopeide.gitbook.io/calliopeide/1.-ai-powered-development-system/1.1-autonomous-ai-agent.md).

# 1.1 Autonomous AI Agent

The core of Calliope is its autonomous AI agent system, which provides intelligent assistance for Soroban smart contract development. The agent is implemented with sophisticated features:

```python
# server/agent.py
def main():
    # Configure the Gemini AI model with specific parameters
    model = genai.GenerativeModel(
        model_name="gemini-2.0-flash",
        generation_config={
            "temperature": 0.2,  # Low temperature for more focused responses
            "top_p": 0.95,      # High top_p for diverse but relevant responses
            "top_k": 40,        # Moderate top_k for balanced sampling
            "max_output_tokens": 30720,  # Large token limit for complex responses
            "response_mime_type": "application/json",  # Force JSON responses
        }
    )
```

**1.1.1 Intelligent Command Execution**

The agent implements a sophisticated command execution system:

````python
def execute_command(cmd: str) -> str:
    print(f"Agent is executing command ```{cmd.replace("`", "'")}```")
    try:
        # Execute command with timeout and output capture
        output = subprocess.run(cmd, shell=True, text=True, 
                                capture_output=True, timeout=300)
        # Handle errors and return appropriate output
        if output.returncode != 0 and output.stderr:
            return f"ERROR: {output.stderr}\nOUTPUT: {output.stdout}"
        return output.stdout
    except subprocess.TimeoutExpired:
        return "COMMAND TIMED OUT (300s limit)"
    except Exception as e:
        return f"ERROR: {str(e)}"
````

Key Features:

1. Command Validation: Checks command syntax and safety
2. Timeout Management: Prevents infinite execution
3. Error Handling: Captures and formats errors
4. Output Processing: Formats command output
5. Resource Management: Controls system resources

**1.1.2 Response Processing**

The agent implements sophisticated response handling:

```python
def handle_model_response(response_text, chat):
    """Handle model response with advanced error recovery"""
    try:
        # Parse response with robust extraction
        parsed = extract_json(response_text)
        
        # Validate required fields
        if all(key in parsed for key in ["message", "commands"]):
            return parsed, None
        else:
            # Request correction for missing fields
            correction_prompt = """
Your previous response was missing required fields. Please provide a complete JSON response with:
1. "thinking" - Your reasoning process
2. "message" - What you want to tell the user
3. "commands" - Array of commands to execute
4. "task_complete" - Boolean indicating if task is done
5. "need_user_input" - Boolean indicating if user input is needed
"""
            # Get corrected response
            corrected_response = chat.send_message(correction_prompt)
            return extract_json(corrected_response.text), corrected_response
```

Features:

1. JSON Parsing: Robust JSON extraction
2. Field Validation: Checks required fields
3. Error Recovery: Handles malformed responses
4. Context Management: Maintains conversation context
5. Response Correction: Requests corrections when needed
