> ## 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.

# Anthropic Claude Integration

> Connect Anthropic Claude for advanced AI reasoning and analysis

## Overview

Integrate Anthropic's Claude models for sophisticated reasoning, analysis, and content generation. Claude excels at complex tasks requiring deep understanding and nuanced responses.

***

## Step 1: Create the AI Connection

### Get Your Anthropic API Key

1. Visit [Anthropic Console](https://console.anthropic.com/)
2. Sign in or create an account
3. Navigate to **API Keys**
4. Click **Create Key**
5. Copy and save your API key securely

<Warning>
  Anthropic API keys are sensitive credentials. Store them securely and never expose them in client-side code.
</Warning>

### Add Connection in AgentFlow

1. Go to **Admin Dashboard** → **AI Models**

2. Click **Add Model**

3. Fill in the basic information:
   * **Name**: `Anthropic Claude Sonnet`
   * **Model ID**: `anthropic-claude`
   * **Description**: `Integration with Anthropic Claude for advanced AI reasoning`

4. Configure the API settings:
   * **Endpoint**: `https://api.anthropic.com/v1/messages`
   * **Method**: `POST`

5. Add headers:
   ```json theme={null}
   {
     "x-api-key": "{{anthropic_api_key}}",
     "Content-Type": "application/json",
     "Anthropic-Version": "2023-06-01"
   }
   ```

6. Configure request schema:
   ```json theme={null}
   {
     "model": "claude-3-5-sonnet-20241022",
     "max_tokens": 4000,
     "temperature": 0.7,
     "top_p": 1,
     "top_k": 40,
     "system": "{{system_prompt}}",
     "messages": [
       {
         "role": "user",
         "content": "{{user_message}}"
       }
     ],
     "metadata": {
       "user_id": "{{user_id}}",
       "session_id": "{{session_id}}"
     }
   }
   ```

7. Set response path: `content[0].text`

8. Click **Save**

***

## Step 2: Import Configuration via YAML

### Understanding YAML Structure

The YAML configuration provides a complete model setup including:

* API endpoint and authentication
* Request/response formatting
* Message transformation rules
* Custom metadata fields

### YAML Configuration File

Create `anthropic-claude-config.yaml`:

```yaml theme={null}
name: "Anthropic Claude Integration"
model_id: "anthropic-claude"
description: "Integration with Anthropic Claude for advanced AI reasoning and analysis"
endpoint: "https://api.anthropic.com/v1/messages"
method: "POST"

headers:
  x-api-key: "{{anthropic_api_key}}"
  Content-Type: "application/json"
  Anthropic-Version: "2023-06-01"

request_schema:
  model: "claude-3-5-sonnet-20241022"
  max_tokens: 4000
  temperature: 0.7
  top_p: 1
  top_k: 40
  stop_sequences: []
  system: "{{system_prompt}}"
  messages:
    - role: "user"
      content: "{{user_message}}"
  metadata:
    user_id: "{{user_id}}"
    session_id: "{{session_id}}"

response_path: "content[0].text"

message_format:
  preset: "anthropic_claude"
  mapping:
    role:
      source: "role"
      target: "messages[{{message_index}}].role"
      transform: "anthropic_role"
    content:
      source: "content"
      target: "messages[{{message_index}}].content"
      transform: "none"
    timestamp:
      source: "timestamp"
      target: "metadata.timestamp"
      transform: "iso8601"
  customFields:
    - name: "claude_configuration"
      value:
        platform: "anthropic"
        model: "claude-3-5-sonnet-20241022"
        version: "2023-06-01"
        capabilities: ["reasoning", "analysis", "writing", "coding"]
      type: "object"
    - name: "generation_parameters"
      value:
        max_tokens: 4000
        temperature: 0.7
        top_p: 1
        top_k: 40
        stop_sequences: []
      type: "object"

suggestion_prompts:
  - "Analyze complex business problems and provide strategic solutions"
  - "Generate high-quality written content for various purposes"
  - "Review and improve existing code or documentation"
  - "Conduct thorough research on specific topics"
  - "Create detailed project plans and technical specifications"
```

### Import Steps

1. Go to **Admin Dashboard** → **AI Models**
2. Click **Import Model**
3. Choose your `anthropic-claude-config.yaml` file
4. Review auto-populated settings
5. Enter your Anthropic API key securely
6. Click **Import & Save**

<Info>
  The YAML import automatically sets up message transformation and Claude-specific formatting.
</Info>

***

## Step 3: Assign to a Group

### Create or Select a Group

1. Navigate to **Admin Dashboard** → **Groups**
2. Either:
   * **Create new group**: Click **New Group** → Name it (e.g., "Research Team")
   * **Select existing group**: Click on an existing group

### Assign the Model

1. Click **Manage Models** in the group settings
2. Find "Anthropic Claude" in the available models list
3. Toggle it **ON**
4. Set usage limits (optional):
   * Max requests per day
   * Token budget
   * Priority level
5. Click **Save Changes**

<Tip>
  Assign Claude to specialized groups for tasks requiring deep analysis and reasoning.
</Tip>

***

## Step 4: Use in Chat

### Starting a Claude Conversation

1. Go to **Chat Interface**
2. Click **New Conversation**
3. In the model selector, choose **Anthropic Claude**
4. Type your message and send!

### Best Use Cases

<CardGroup cols={2}>
  <Card title="Complex Analysis" icon="microscope">
    Deep business analysis, research synthesis, strategic planning
  </Card>

  <Card title="Technical Writing" icon="file-code">
    Documentation, technical specs, API references
  </Card>

  <Card title="Code Review" icon="code-review">
    Thorough code analysis, security reviews, optimization suggestions
  </Card>

  <Card title="Long-form Content" icon="book">
    Articles, reports, detailed guides, educational content
  </Card>
</CardGroup>

### Example Interactions

<CodeGroup>
  ```text Business Analysis theme={null}
  Analyze our SaaS pricing strategy for a B2B platform. Current tiers: Starter ($29), Pro ($99), Enterprise (custom). Monthly users: 1,200 (60% Starter, 30% Pro, 10% Enterprise). Suggest optimizations.
  ```

  ```text Code Review theme={null}
  Review this React component for performance issues, accessibility concerns, and best practices:

  [paste your code here]
  ```

  ```text Research theme={null}
  Synthesize the latest research on transformer architectures in NLP, focusing on efficiency improvements from 2023-2024.
  ```

  ```text Technical Writing theme={null}
  Write comprehensive API documentation for a RESTful endpoint that handles user authentication with OAuth 2.0.
  ```
</CodeGroup>

***

## Advanced Configuration

### Model Variants

Claude offers different model tiers:

| Model             | Best For             | Context Window |
| ----------------- | -------------------- | -------------- |
| Claude 3.5 Sonnet | Balanced performance | 200K tokens    |
| Claude 3 Opus     | Maximum capability   | 200K tokens    |
| Claude 3 Haiku    | Speed & efficiency   | 200K tokens    |

### Parameter Tuning

#### Temperature (0.0 - 1.0)

```yaml theme={null}
temperature: 0.7  # Default - balanced
temperature: 0.2  # More focused and deterministic
temperature: 0.9  # More creative and varied
```

#### Top-K Sampling

```yaml theme={null}
top_k: 40   # Default - good balance
top_k: 10   # More focused selection
top_k: 100  # Broader selection
```

#### Stop Sequences

```yaml theme={null}
stop_sequences: ["\n\nHuman:", "END"]  # Custom stop points
```

### System Prompts

Claude responds well to detailed system prompts:

```yaml theme={null}
system: |
  You are a senior technical architect with expertise in distributed systems.
  Provide detailed, technically accurate responses with code examples when relevant.
  Consider scalability, security, and maintainability in all recommendations.
```

***

## Troubleshooting

### Common Issues

<AccordionGroup>
  <Accordion title="API Key Invalid">
    **Solution**: Verify your API key in the Anthropic Console and regenerate if necessary. Ensure you're using the correct header format: `x-api-key`.
  </Accordion>

  <Accordion title="Rate Limit Errors">
    **Solution**: Claude has rate limits based on your tier:

    * Tier 1: 50 requests/min
    * Tier 2: 1,000 requests/min
    * Tier 3: 2,000 requests/min

    Implement exponential backoff or upgrade your tier.
  </Accordion>

  <Accordion title="Context Length Exceeded">
    **Solution**: Claude supports 200K tokens but responses are limited by `max_tokens`. Reduce conversation history or split long requests.
  </Accordion>

  <Accordion title="Response Truncated">
    **Solution**: Increase `max_tokens` in your configuration:

    ```yaml theme={null}
    max_tokens: 8000  # For longer responses
    ```
  </Accordion>
</AccordionGroup>

### Error Response Handling

Monitor these error types:

```json theme={null}
{
  "error": {
    "type": "invalid_request_error",
    "message": "messages: roles must alternate between 'user' and 'assistant'"
  }
}
```

Ensure proper message role alternation in your conversation history.

***

## Cost Management

### Token Optimization

1. **Monitor Usage**: Check **Analytics Dashboard** → **Model Usage**
2. **Set Limits**: Configure per-group token budgets
3. **Optimize Prompts**: Be concise while maintaining clarity
4. **Cache System Prompts**: Reuse system prompts across conversations

### Pricing Structure

| Model             | Input (per MTok) | Output (per MTok) |
| ----------------- | ---------------- | ----------------- |
| Claude 3.5 Sonnet | \$3.00           | \$15.00           |
| Claude 3 Opus     | \$15.00          | \$75.00           |
| Claude 3 Haiku    | \$0.25           | \$1.25            |

<Tip>
  Use Haiku for simple tasks and reserve Sonnet/Opus for complex reasoning.
</Tip>

***

## Integration Patterns

### Multi-Model Workflows

Combine Claude with other models:

1. **Claude for Analysis** → **GPT-4 for Code Generation**
2. **Claude for Research** → **GPT-3.5 for Summaries**
3. **Claude for Strategy** → **Specialized models for execution**

### Conversation Templates

Create reusable templates:

```yaml theme={null}
templates:
  - name: "Technical Review"
    system_prompt: "You are an expert code reviewer..."
    initial_message: "Please review the following code..."

  - name: "Business Analysis"
    system_prompt: "You are a strategic business consultant..."
    initial_message: "Analyze the following business scenario..."
```

***

## Security Best Practices

<Steps>
  <Step title="Secure API Keys">
    Store API keys in environment variables or secure vaults, never in code or YAML files.
  </Step>

  <Step title="Content Filtering">
    Implement content moderation for user inputs and Claude responses.
  </Step>

  <Step title="Rate Limiting">
    Set organization-level rate limits to prevent abuse and control costs.
  </Step>

  <Step title="Audit Logging">
    Enable conversation logging for compliance and security monitoring.
  </Step>

  <Step title="Data Privacy">
    Review Anthropic's data retention policy and configure accordingly.
  </Step>
</Steps>

***

## Next Steps

<CardGroup cols={2}>
  <Card title="LangChain Agents" icon="link" href="/examples/langchain-agent">
    Build agents with tools
  </Card>

  <Card title="Workflow Automation" icon="workflow" href="/examples/n8n-workflow">
    Automate with n8n
  </Card>

  <Card title="Compare Models" icon="chart-mixed" href="/agents/choosing-ai-models">
    Model selection guide
  </Card>

  <Card title="Analytics" icon="chart-bar" href="/analytics/usage-metrics">
    Track performance
  </Card>
</CardGroup>
