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

# OpenAI Agent Builder (Assistants API)

> Build intelligent agents with OpenAI Assistants API for task automation and decision making

## Overview

Create sophisticated AI agents using OpenAI's Assistants API. Build agents with code interpretation, file search, and custom function calling capabilities.

***

## Prerequisites

<CardGroup cols={2}>
  <Card title="OpenAI Account" icon="openai">
    Sign up at [platform.openai.com](https://platform.openai.com)
  </Card>

  <Card title="API Key" icon="key">
    Generate API key with Assistants access
  </Card>

  <Card title="Assistant Created" icon="robot">
    Build assistant via OpenAI Playground or API
  </Card>

  <Card title="AgentFlow Admin" icon="user-shield">
    Admin access required
  </Card>
</CardGroup>

***

## Step 1: Create OpenAI Assistant

### Using OpenAI Playground

<Steps>
  <Step title="Access Playground">
    1. Go to [platform.openai.com/playground](https://platform.openai.com/playground)
    2. Select **Assistants** mode
  </Step>

  <Step title="Configure Assistant">
    * **Name**: `Research & Analysis Agent`
    * **Model**: `gpt-4-turbo`
    * **Instructions**:

    ```
    You are a research and analysis expert. Use your tools to:
    1. Search through provided files and documents
    2. Execute code for data analysis
    3. Call functions to retrieve external data

    Always cite sources and show your reasoning.
    ```
  </Step>

  <Step title="Enable Tools">
    * ✅ **Code Interpreter**: For data analysis and calculations
    * ✅ **File Search**: For document analysis
    * ✅ **Functions**: For custom integrations
  </Step>

  <Step title="Add Functions">
    Define custom functions:

    ```json theme={null}
    {
      "name": "get_customer_data",
      "description": "Retrieve customer information from CRM",
      "parameters": {
        "type": "object",
        "properties": {
          "customer_id": {
            "type": "string",
            "description": "The customer ID"
          }
        },
        "required": ["customer_id"]
      }
    }
    ```
  </Step>

  <Step title="Save Assistant">
    Click **Save** and copy the Assistant ID

    ```
    asst_abc123xyz789
    ```
  </Step>
</Steps>

### Using OpenAI API

Create programmatically:

```python theme={null}
from openai import OpenAI

client = OpenAI(api_key="your_api_key")

assistant = client.beta.assistants.create(
    name="Research & Analysis Agent",
    instructions="""You are a research and analysis expert.
    Use tools to search documents, analyze data, and retrieve information.""",
    model="gpt-4-turbo",
    tools=[
        {"type": "code_interpreter"},
        {"type": "file_search"},
        {
            "type": "function",
            "function": {
                "name": "get_customer_data",
                "description": "Retrieve customer info",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "customer_id": {"type": "string"}
                    },
                    "required": ["customer_id"]
                }
            }
        }
    ]
)

print(f"Assistant ID: {assistant.id}")
```

***

## Step 2: Create AI Connection in AgentFlow

### Manual Setup

1. **Admin Dashboard** → **AI Models** → **Add Model**

2. Configuration:
   * **Name**: `OpenAI Research Assistant`
   * **Model ID**: `openai-agent-builder`
   * **Description**: `Research agent with code interpretation and file search`

3. API Settings:
   * **Endpoint**: `https://api.openai.com/v1/assistants/{{assistant_id}}/runs`
   * **Method**: POST

4. Headers:
   ```json theme={null}
   {
     "Authorization": "Bearer {{openai_api_key}}",
     "Content-Type": "application/json",
     "OpenAI-Beta": "assistants=v2"
   }
   ```

5. Request Schema:
   ```json theme={null}
   {
     "assistant_id": "{{assistant_id}}",
     "thread_id": "{{thread_id}}",
     "instructions": "{{instructions}}",
     "additional_instructions": "{{additional_instructions}}",
     "tools": [
       {"type": "code_interpreter"},
       {"type": "file_search"},
       {
         "type": "function",
         "function": {
           "name": "custom_function",
           "description": "Custom function for specific tasks"
         }
       }
     ],
     "metadata": {
       "user_id": "{{user_id}}",
       "session_id": "{{session_id}}",
       "timestamp": "{{timestamp}}"
     }
   }
   ```

6. Response Path: `data.run_result`

7. **Save**

***

## Step 3: Import via YAML

### YAML Configuration

Create `openai-agent-builder-config.yaml`:

```yaml theme={null}
name: "OpenAI Agent Builder"
model_id: "openai-agent-builder"
description: "Execute OpenAI Agent Builder agents for intelligent task automation"
endpoint: "https://api.openai.com/v1/assistants/{{assistant_id}}/runs"
method: "POST"

headers:
  Authorization: "Bearer {{openai_api_key}}"
  Content-Type: "application/json"
  OpenAI-Beta: "assistants=v2"

request_schema:
  assistant_id: "{{assistant_id}}"
  thread_id: "{{thread_id}}"
  instructions: "{{instructions}}"
  additional_instructions: "{{additional_instructions}}"
  tools:
    - type: "code_interpreter"
    - type: "file_search"
    - type: "function"
      function:
        name: "custom_function"
        description: "Custom function for specific tasks"
  metadata:
    user_id: "{{user_id}}"
    session_id: "{{session_id}}"
    timestamp: "{{timestamp}}"

response_path: "data.run_result"

message_format:
  preset: "openai_assistant"
  mapping:
    role:
      source: "role"
      target: "messages[0].role"
      transform: "openai_role"
    content:
      source: "content"
      target: "messages[0].content"
      transform: "none"
    timestamp:
      source: "timestamp"
      target: "metadata.timestamp"
      transform: "iso8601"
  customFields:
    - name: "agent_configuration"
      value:
        platform: "openai"
        model: "gpt-4-turbo"
        version: "assistants-v2"
        capabilities: ["code_interpreter", "file_search", "function_calling"]
      type: "object"
    - name: "execution_settings"
      value:
        max_completion_tokens: 4000
        temperature: 0.7
        timeout: 300
        stream: false
      type: "object"

suggestion_prompts:
  - "Create an agent to analyze customer feedback and generate insights"
  - "Build an agent for automated code review and suggestions"
  - "Set up an agent for data analysis and report generation"
  - "Create an agent for content moderation and classification"
  - "Build an agent for automated customer support responses"
```

### Import Process

1. Update `assistant_id` with your actual ID
2. **Admin Dashboard** → **AI Models** → **Import Model**
3. Upload YAML
4. Enter OpenAI API key
5. **Import**

***

## Step 4: Assign to Group

1. **Admin Dashboard** → **Groups**
2. Select group (e.g., "Analytics Team")
3. **Manage Models** → Enable **OpenAI Assistant**
4. Configure:
   * **Code Interpreter**: Enabled
   * **File Upload**: 20 files max
   * **Custom Functions**: Enabled
   * **Max Tokens**: 4000
5. **Save**

***

## Step 5: Use in Chat

### Interacting with Assistant

1. **Chat** → **New Conversation**
2. Select **OpenAI Research Assistant**
3. Start conversation

### Example Interactions

<CodeGroup>
  ```text Data Analysis theme={null}
  Analyze this sales data and create visualizations:
  Q1: $1.2M, Q2: $1.8M, Q3: $2.1M, Q4: $2.5M

  Calculate growth rate, create a trend chart, and forecast Q1 next year.
  ```

  ```text Code Execution theme={null}
  Write and execute Python code to:
  1. Generate 1000 random data points
  2. Calculate mean, median, std deviation
  3. Create a histogram
  4. Identify outliers
  ```

  ```text File Analysis theme={null}
  I've uploaded our customer feedback survey. Analyze the responses, categorize by sentiment, and identify the top 3 pain points.
  ```

  ```text Custom Function theme={null}
  Get customer data for ID: CUST-12345 and analyze their purchase history. Suggest personalized product recommendations.
  ```
</CodeGroup>

***

## Tool Capabilities

### Code Interpreter

Execute Python code for analysis:

<CodeGroup>
  ```python Data Analysis theme={null}
  import pandas as pd
  import matplotlib.pyplot as plt

  # Your data
  data = pd.DataFrame({
      'Quarter': ['Q1', 'Q2', 'Q3', 'Q4'],
      'Revenue': [1200000, 1800000, 2100000, 2500000]
  })

  # Calculate growth
  data['Growth'] = data['Revenue'].pct_change() * 100

  # Create visualization
  plt.figure(figsize=(10,6))
  plt.plot(data['Quarter'], data['Revenue'], marker='o')
  plt.title('Quarterly Revenue Trend')
  plt.savefig('revenue_trend.png')
  ```

  ```python Statistical Analysis theme={null}
  import numpy as np
  from scipy import stats

  # Generate data
  data = np.random.normal(100, 15, 1000)

  # Analysis
  mean = np.mean(data)
  median = np.median(data)
  std = np.std(data)
  ci = stats.t.interval(0.95, len(data)-1,
                        loc=mean,
                        scale=stats.sem(data))

  print(f"Mean: {mean:.2f}")
  print(f"95% CI: {ci}")
  ```

  ```python Machine Learning theme={null}
  from sklearn.linear_model import LinearRegression
  import numpy as np

  # Simple prediction model
  X = np.array([[1], [2], [3], [4]])
  y = np.array([1.2, 1.8, 2.1, 2.5])

  model = LinearRegression()
  model.fit(X, y)

  # Forecast
  next_quarter = model.predict([[5]])
  print(f"Q1 Forecast: ${next_quarter[0]:.1f}M")
  ```
</CodeGroup>

### File Search

Upload and analyze documents:

<Steps>
  <Step title="Upload Files">
    Via API or Playground:

    ```python theme={null}
    file = client.files.create(
        file=open("customer_feedback.pdf", "rb"),
        purpose="assistants"
    )

    client.beta.assistants.update(
        assistant_id="asst_abc123",
        file_ids=[file.id]
    )
    ```
  </Step>

  <Step title="Query Documents">
    Ask questions about uploaded files:

    ```
    "What are the main themes in the customer feedback?"
    "Summarize the key findings from the Q4 report"
    "Find all mentions of pricing concerns"
    ```
  </Step>

  <Step title="Get Citations">
    Assistant provides source references:

    ```
    According to page 12 of the feedback report...
    ```
  </Step>
</Steps>

### Function Calling

Integrate with external systems:

<Steps>
  <Step title="Define Function">
    ```json theme={null}
    {
      "name": "get_customer_data",
      "description": "Retrieve customer information from CRM",
      "parameters": {
        "type": "object",
        "properties": {
          "customer_id": {
            "type": "string",
            "description": "Customer ID"
          },
          "include_history": {
            "type": "boolean",
            "description": "Include purchase history"
          }
        },
        "required": ["customer_id"]
      }
    }
    ```
  </Step>

  <Step title="Handle Function Calls">
    ```python theme={null}
    if run.status == "requires_action":
        tool_call = run.required_action.submit_tool_outputs.tool_calls[0]

        if tool_call.function.name == "get_customer_data":
            args = json.loads(tool_call.function.arguments)
            customer_data = fetch_from_crm(args["customer_id"])

            client.beta.threads.runs.submit_tool_outputs(
                thread_id=thread.id,
                run_id=run.id,
                tool_outputs=[{
                    "tool_call_id": tool_call.id,
                    "output": json.dumps(customer_data)
                }]
            )
    ```
  </Step>
</Steps>

***

## Advanced Configuration

### Thread Management

Manage conversation threads:

```python theme={null}
# Create thread
thread = client.beta.threads.create()

# Add message
message = client.beta.threads.messages.create(
    thread_id=thread.id,
    role="user",
    content="Analyze this data..."
)

# Run assistant
run = client.beta.threads.runs.create(
    thread_id=thread.id,
    assistant_id=assistant.id
)

# Check status
while run.status != "completed":
    run = client.beta.threads.runs.retrieve(
        thread_id=thread.id,
        run_id=run.id
    )
    time.sleep(1)

# Get response
messages = client.beta.threads.messages.list(
    thread_id=thread.id
)
```

### Streaming Responses

Enable real-time streaming:

```python theme={null}
with client.beta.threads.runs.stream(
    thread_id=thread.id,
    assistant_id=assistant.id
) as stream:
    for event in stream:
        if event.type == "thread.message.delta":
            print(event.data.delta.content[0].text.value, end="")
```

### Custom Instructions

Dynamic instruction override:

```python theme={null}
run = client.beta.threads.runs.create(
    thread_id=thread.id,
    assistant_id=assistant.id,
    additional_instructions="""
    For this analysis:
    - Focus on trends from the last quarter
    - Highlight any anomalies
    - Provide actionable recommendations
    """
)
```

***

## Use Cases

### 1. Data Analysis Agent

```yaml theme={null}
Assistant Config:
  Name: "Data Analysis Expert"
  Model: gpt-4-turbo
  Tools: [code_interpreter]
  Instructions: |
    Analyze data using Python, pandas, numpy.
    Create visualizations with matplotlib.
    Provide statistical insights and predictions.

Example Query:
  "Analyze customer churn data and identify key factors"
```

### 2. Document Research Agent

```yaml theme={null}
Assistant Config:
  Name: "Research Assistant"
  Model: gpt-4-turbo
  Tools: [file_search]
  Instructions: |
    Search through documents to answer questions.
    Always cite sources.
    Provide comprehensive summaries.

Example Query:
  "What does our compliance policy say about data retention?"
```

### 3. Customer Support Agent

```yaml theme={null}
Assistant Config:
  Name: "Support Bot"
  Model: gpt-4-turbo
  Tools: [file_search, function(get_ticket_info)]
  Instructions: |
    Help customers with their issues.
    Search knowledge base for solutions.
    Escalate complex issues to humans.

Example Query:
  "Customer CUST-123 is having login issues"
```

***

## Monitoring & Debugging

### Run Status Tracking

Monitor assistant execution:

```python theme={null}
run = client.beta.threads.runs.retrieve(
    thread_id=thread.id,
    run_id=run.id
)

print(f"Status: {run.status}")
# queued, in_progress, requires_action, completed, failed
```

### Error Handling

Handle common errors:

```python theme={null}
try:
    run = client.beta.threads.runs.create(
        thread_id=thread.id,
        assistant_id=assistant.id
    )
except openai.APIError as e:
    print(f"API Error: {e}")
except openai.RateLimitError as e:
    print(f"Rate limit exceeded: {e}")
except Exception as e:
    print(f"Unexpected error: {e}")
```

### Usage Tracking

Monitor token usage:

```python theme={null}
run = client.beta.threads.runs.retrieve(
    thread_id=thread.id,
    run_id=run.id
)

print(f"Tokens used: {run.usage.total_tokens}")
print(f"Prompt tokens: {run.usage.prompt_tokens}")
print(f"Completion tokens: {run.usage.completion_tokens}")
```

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="Assistant Not Responding">
    **Check**:

    * Assistant is not deleted
    * API key has Assistants beta access
    * Thread ID is valid
    * No rate limits hit

    **Fix**: Recreate assistant or thread
  </Accordion>

  <Accordion title="Function Not Called">
    **Check**:

    * Function definition is correct
    * Description is clear
    * Parameters match expected format

    **Fix**: Improve function description
  </Accordion>

  <Accordion title="File Search Not Working">
    **Check**:

    * Files are uploaded successfully
    * File IDs are attached to assistant
    * Supported file types (PDF, TXT, DOCX)

    **Fix**: Verify file upload and attachment
  </Accordion>

  <Accordion title="Code Execution Failed">
    **Cause**: Invalid Python code or timeout

    **Fix**:

    * Validate code syntax
    * Reduce computation complexity
    * Check for infinite loops
  </Accordion>
</AccordionGroup>

***

## Cost Management

### Pricing Structure

| Component        | Cost                            |
| ---------------- | ------------------------------- |
| GPT-4-turbo      | $0.01/1K input, $0.03/1K output |
| Code Interpreter | \$0.03/session                  |
| File Search      | \$0.10/GB/day                   |
| Storage          | \$0.20/GB/month                 |

### Optimization Tips

<CardGroup cols={2}>
  <Card title="Model Selection" icon="microchip">
    Use GPT-3.5-turbo for simple tasks
  </Card>

  <Card title="File Management" icon="file">
    Delete unused files regularly
  </Card>

  <Card title="Thread Cleanup" icon="broom">
    Archive old threads
  </Card>

  <Card title="Token Limits" icon="coins">
    Set max\_tokens appropriately
  </Card>
</CardGroup>

***

## Best Practices

1. **Clear Instructions**: Be specific about assistant behavior
2. **Tool Selection**: Only enable necessary tools
3. **Error Handling**: Implement robust error handling
4. **Testing**: Test with various inputs before deployment
5. **Monitoring**: Track usage and costs regularly
6. **Security**: Validate all function inputs/outputs

***

## Next Steps

<CardGroup cols={2}>
  <Card title="LangChain Agents" icon="link" href="/examples/langchain-agent">
    Alternative agent framework
  </Card>

  <Card title="Cloud Functions" icon="cloud" href="/examples/cloud-run-function">
    Custom serverless logic
  </Card>

  <Card title="Workflow Automation" icon="diagram-project" href="/examples/make-workflow">
    Combine with Make.com
  </Card>

  <Card title="Analytics" icon="chart-line" href="/analytics/usage-metrics">
    Monitor assistant performance
  </Card>
</CardGroup>
