> ## Documentation Index
> Fetch the complete documentation index at: https://agentdiff.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# Python Executor

> Execute Python code with API interception

## Overview

The `PythonExecutorProxy` intercepts Python HTTP libraries (`requests`, `urllib`) and routes API calls to isolated environments.

## Configuration

The executor automatically loads credentials from environment variables:

```bash theme={null}
export AGENT_DIFF_API_KEY="ad_live_sk_..."
export AGENT_DIFF_BASE_URL="https://api.agentdiff.dev"
```

## Basic Usage

```python theme={null}
from agent_diff import PythonExecutorProxy

# Create executor - auto-loads base_url and api_key from env vars
executor = PythonExecutorProxy(environment_id="env-123")

# Execute code
result = executor.execute("""
import requests

response = requests.post('https://slack.com/api/chat.postMessage', json={
    'channel': 'C01GENERAL99',
    'text': 'Hello from Python!'
})
print(response.json())
""")

print(result["stdout"])  # API response
print(result["status"])  # "success" or "error"
```

## Creating Framework Tools

### OpenAI Agents SDK

```python theme={null}
from agent_diff import PythonExecutorProxy, create_openai_tool
from agents import Agent

# Uses env vars automatically
executor = PythonExecutorProxy(env.environmentId)
tool = create_openai_tool(executor)

agent = Agent(
    name="Assistant",
    tools=[tool],
    instructions="Use execute_python to interact with Slack API..."
)
```

### LangChain

```python theme={null}
from agent_diff import PythonExecutorProxy, create_langchain_tool

executor = PythonExecutorProxy(env.environmentId)
tool = create_langchain_tool(executor)

# Use with LangChain agent
```

### smolagents

```python theme={null}
from agent_diff import PythonExecutorProxy, create_smolagents_tool

executor = PythonExecutorProxy(env.environmentId)
tool = create_smolagents_tool(executor)

# Use with smolagents CodeAgent
```

## Supported Libraries

The Python executor intercepts:

* **requests**: All HTTP methods
* **urllib.request**: urlopen, Request
* **httpx**: (Coming soon)
* **aiohttp**: (Coming soon)

## Execution Result

```python theme={null}
result = executor.execute(code)

# Result structure:
{
    "status": "success" | "error",
    "stdout": "...",     # Captured print() output
    "stderr": "...",     # Error output if any
    "exit_code": 0       # Process exit code
}
```

## Error Handling

```python theme={null}
result = executor.execute(code)

if result["status"] == "error":
    print(f"Execution failed: {result['stderr']}")
else:
    print(f"Output: {result['stdout']}")
```

## Example: Slack API Calls

```python theme={null}
result = executor.execute("""
import requests
import json

# List channels
channels = requests.get('https://slack.com/api/conversations.list').json()
print("Channels:", [c['name'] for c in channels['channels']])

# Post message
response = requests.post('https://slack.com/api/chat.postMessage', json={
    'channel': 'C01GENERAL99',
    'text': 'Hello!'
}).json()

print("Message sent:", response['ok'])
print("Timestamp:", response['ts'])
""")
```

## Example: Linear GraphQL

```python theme={null}
result = executor.execute("""
import requests

query = '''
mutation {
  issueCreate(input: {
    title: "Fix bug"
    teamId: "team-123"
  }) {
    success
    issue {
      id
      title
    }
  }
}
'''

response = requests.post('https://api.linear.app/graphql', json={
    'query': query
})

print(response.json())
""")
```

## Configuration Options

```python theme={null}
# Option 1: Environment variables (recommended)
# export AGENT_DIFF_API_KEY="ad_live_sk_..."
# export AGENT_DIFF_BASE_URL="https://api.agentdiff.dev"
executor = PythonExecutorProxy(environment_id="env-123")

# Option 2: Explicit configuration
executor = PythonExecutorProxy(
    environment_id="env-123",
    base_url="https://api.agentdiff.dev",
    api_key="ad_live_sk_..."  # Passed as Authorization header
)
```

## Next Steps

<CardGroup cols={2}>
  <Card title="TypeScript Executor" icon="js" href="/code-executor-proxy/typescript">
    Execute TypeScript/JavaScript code
  </Card>

  <Card title="Bash Executor" icon="terminal" href="/code-executor-proxy/bash">
    Execute shell commands
  </Card>
</CardGroup>
