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

# LangChain Agent Integration

> Execute hosted LangChain agents for complex AI workflows with tool usage

## Overview

Integrate LangChain agents with AgentFlow to build sophisticated AI systems that can use tools, access external data, and execute multi-step reasoning workflows.

***

## Prerequisites

<CardGroup cols={2}>
  <Card title="LangChain Account" icon="link">
    Sign up at [smith.langchain.com](https://smith.langchain.com)
  </Card>

  <Card title="API Key" icon="key">
    Generate API key from LangChain settings
  </Card>

  <Card title="Agent Created" icon="robot">
    Build and deploy a LangChain agent
  </Card>

  <Card title="AgentFlow Access" icon="shield">
    Admin rights in AgentFlow
  </Card>
</CardGroup>

***

## Step 1: Create LangChain Agent

### Setup LangChain Project

<Steps>
  <Step title="Install LangChain">
    ```bash theme={null}
    pip install langchain langchain-openai langsmith
    ```
  </Step>

  <Step title="Configure Environment">
    ```bash theme={null}
    export LANGCHAIN_API_KEY="your_api_key"
    export LANGCHAIN_TRACING_V2="true"
    export OPENAI_API_KEY="your_openai_key"
    ```
  </Step>

  <Step title="Create Agent">
    ```python theme={null}
    from langchain.agents import create_openai_functions_agent
    from langchain_openai import ChatOpenAI
    from langchain.tools import Tool
    from langchain.prompts import ChatPromptTemplate

    # Define tools
    tools = [
        Tool(
            name="web_search",
            func=web_search_function,
            description="Search the web for current information"
        ),
        Tool(
            name="calculator",
            func=calculator_function,
            description="Perform mathematical calculations"
        )
    ]

    # Create agent
    llm = ChatOpenAI(model="gpt-4", temperature=0.7)
    agent = create_openai_functions_agent(
        llm=llm,
        tools=tools,
        prompt=ChatPromptTemplate.from_messages([
            ("system", "You are a helpful AI assistant with access to tools."),
            ("human", "{input}"),
            ("placeholder", "{agent_scratchpad}")
        ])
    )
    ```
  </Step>

  <Step title="Deploy Agent">
    ```python theme={null}
    from langchain.agents import AgentExecutor

    agent_executor = AgentExecutor(
        agent=agent,
        tools=tools,
        verbose=True,
        max_iterations=10
    )

    # Create API endpoint
    from langserve import add_routes
    from fastapi import FastAPI

    app = FastAPI()
    add_routes(app, agent_executor, path="/agent")
    ```
  </Step>
</Steps>

### Deploy to LangChain Hub

<Steps>
  <Step title="Push to Hub">
    ```python theme={null}
    from langchain.hub import push

    push(
        "your-username/research-agent",
        agent_executor,
        description="Research agent with web search and calculation tools"
    )
    ```
  </Step>

  <Step title="Get Agent ID">
    Copy the agent ID from LangSmith dashboard

    ```
    agent_id: "abc123xyz789"
    ```
  </Step>
</Steps>

***

## Step 2: Create AI Connection in AgentFlow

### Manual Configuration

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

2. Basic Info:
   * **Name**: `LangChain Research Agent`
   * **Model ID**: `langchain-agent-executor`
   * **Description**: `Research agent with web search and calculation`

3. API Settings:
   * **Endpoint**: `https://api.langchain.com/v1/agents/{{agent_id}}/invoke`
   * **Method**: POST

4. Headers:
   ```json theme={null}
   {
     "Authorization": "Bearer {{langchain_api_key}}",
     "Content-Type": "application/json",
     "X-LangChain-Version": "0.1.0"
   }
   ```

5. Request Schema:
   ```json theme={null}
   {
     "agent_id": "{{agent_id}}",
     "input": {
       "message": "{{message}}",
       "user_id": "{{user_id}}",
       "session_id": "{{session_id}}",
       "timestamp": "{{timestamp}}"
     },
     "config": {
       "callbacks": [],
       "tags": ["chat-platform"],
       "metadata": {
         "user_id": "{{user_id}}",
         "session_id": "{{session_id}}"
       }
     },
     "tools": [
       {
         "name": "web_search",
         "description": "Search the web for current information"
       },
       {
         "name": "calculator",
         "description": "Perform mathematical calculations"
       },
       {
         "name": "code_executor",
         "description": "Execute code snippets"
       }
     ],
     "memory": {
       "type": "conversation_buffer",
       "max_token_limit": 2000
     }
   }
   ```

6. Response Path: `data.output`

7. **Save**

***

## Step 3: Import via YAML

### Complete YAML Configuration

Create `langchain-agent-config.yaml`:

```yaml theme={null}
name: "Hosted LangChain Agent"
model_id: "langchain-agent-executor"
description: "Execute hosted LangChain agents for complex AI workflows and tool usage"
endpoint: "https://api.langchain.com/v1/agents/{{agent_id}}/invoke"
method: "POST"

headers:
  Authorization: "Bearer {{langchain_api_key}}"
  Content-Type: "application/json"
  X-LangChain-Version: "0.1.0"

request_schema:
  agent_id: "{{agent_id}}"
  input:
    message: "{{message}}"
    user_id: "{{user_id}}"
    session_id: "{{session_id}}"
    timestamp: "{{timestamp}}"
  config:
    callbacks: []
    tags: ["chat-platform"]
    metadata:
      user_id: "{{user_id}}"
      session_id: "{{session_id}}"
  tools:
    - name: "web_search"
      description: "Search the web for current information"
    - name: "calculator"
      description: "Perform mathematical calculations"
    - name: "code_executor"
      description: "Execute code snippets"
  memory:
    type: "conversation_buffer"
    max_token_limit: 2000

response_path: "data.output"

message_format:
  preset: "langchain_agent"
  mapping:
    role:
      source: "role"
      target: "input.role"
      transform: "lowercase"
    content:
      source: "content"
      target: "input.message"
      transform: "none"
    timestamp:
      source: "timestamp"
      target: "input.timestamp"
      transform: "iso8601"
    session_id:
      source: "session_id"
      target: "input.session_id"
      transform: "none"
  customFields:
    - name: "langchain_configuration"
      value:
        platform: "langchain"
        version: "0.1.0"
        agent_type: "conversational"
        capabilities: ["tool_usage", "memory", "reasoning"]
      type: "object"
    - name: "agent_settings"
      value:
        max_iterations: 10
        timeout: 300
        memory_type: "conversation_buffer"
        max_token_limit: 2000
      type: "object"

suggestion_prompts:
  - "Create an agent that can research topics and provide comprehensive summaries"
  - "Build an agent for automated data analysis and visualization"
  - "Set up an agent for code review and optimization suggestions"
  - "Create an agent for customer support with access to knowledge base"
  - "Build an agent for automated report generation from multiple data sources"
```

### Import Steps

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

***

## Step 4: Assign to Group

1. **Admin Dashboard** → **Groups**
2. Select/Create group (e.g., "Research Team")
3. **Manage Models** → Enable **LangChain Agent**
4. Configure access:
   * **Tool Access**: All tools enabled
   * **Max Iterations**: 10
   * **Timeout**: 5 minutes
   * **Memory**: Enabled
5. **Save**

***

## Step 5: Use in Chat

### Agent Interactions

1. **Chat** → **New Conversation**
2. Select **LangChain Research Agent**
3. Ask questions that require tool usage

### Example Prompts

<CodeGroup>
  ```text Research theme={null}
  Research the latest developments in quantum computing from 2024 and summarize the key breakthroughs.
  ```

  ```text Calculation theme={null}
  Calculate the ROI of investing $100,000 in a SaaS startup with 15% monthly growth over 2 years. Account for a 30% churn rate.
  ```

  ```text Data Analysis theme={null}
  Analyze the sales data from Q4 2023: Total revenue $2.5M, 1,500 customers, 25% from enterprise, 50% from mid-market, 25% from SMB. Provide insights and recommendations.
  ```

  ```text Code Execution theme={null}
  Write and execute a Python script to analyze this CSV data and generate a correlation matrix between features.
  ```
</CodeGroup>

### Understanding Agent Responses

Agent shows its reasoning process:

```
Thought: I need to search for recent quantum computing developments.
Action: web_search
Action Input: "quantum computing breakthroughs 2024"
Observation: [Search results...]

Thought: I now have enough information to summarize.
Final Answer: [Comprehensive summary...]
```

***

## Building Custom Tools

### Tool Definition Pattern

```python theme={null}
from langchain.tools import BaseTool
from pydantic import BaseModel, Field

class SearchInput(BaseModel):
    query: str = Field(description="The search query")
    num_results: int = Field(default=5, description="Number of results")

class WebSearchTool(BaseTool):
    name = "web_search"
    description = "Search the web for current information"
    args_schema = SearchInput

    def _run(self, query: str, num_results: int = 5) -> str:
        # Implement search logic
        results = search_api(query, limit=num_results)
        return format_results(results)

    async def _arun(self, query: str, num_results: int = 5) -> str:
        # Async implementation
        results = await async_search_api(query, limit=num_results)
        return format_results(results)
```

### Common Tool Types

<CardGroup cols={2}>
  <Card title="Search Tools" icon="magnifying-glass">
    * Web search (Google, Bing)
    * Knowledge base search
    * Document search
  </Card>

  <Card title="Data Tools" icon="database">
    * SQL queries
    * API calls
    * CSV/Excel parsing
  </Card>

  <Card title="Computation Tools" icon="calculator">
    * Math calculations
    * Statistical analysis
    * Code execution
  </Card>

  <Card title="Integration Tools" icon="plug">
    * CRM access
    * Email sending
    * File operations
  </Card>
</CardGroup>

### Tool Implementation Examples

<CodeGroup>
  ```python Database Tool theme={null}
  from langchain.tools import Tool

  def query_database(query: str) -> str:
      """Execute SQL query and return results"""
      import psycopg2
      conn = psycopg2.connect(DATABASE_URL)
      cursor = conn.cursor()
      cursor.execute(query)
      results = cursor.fetchall()
      return str(results)

  database_tool = Tool(
      name="database_query",
      func=query_database,
      description="Execute SQL queries on the customer database"
  )
  ```

  ```python API Tool theme={null}
  def call_api(endpoint: str, params: dict) -> str:
      """Call external API"""
      import requests
      response = requests.get(endpoint, params=params)
      return response.json()

  api_tool = Tool(
      name="api_call",
      func=call_api,
      description="Call external APIs for data retrieval"
  )
  ```

  ```python Email Tool theme={null}
  def send_email(to: str, subject: str, body: str) -> str:
      """Send email via SendGrid"""
      import sendgrid
      sg = sendgrid.SendGridAPIClient(api_key=SENDGRID_KEY)
      # Send email logic
      return "Email sent successfully"

  email_tool = Tool(
      name="send_email",
      func=send_email,
      description="Send emails to users or team members"
  )
  ```
</CodeGroup>

***

## Advanced Agent Patterns

### Multi-Agent Systems

Create specialized agents for different tasks:

```python theme={null}
# Research Agent
research_agent = create_agent(
    llm=ChatOpenAI(model="gpt-4"),
    tools=[web_search_tool, summarizer_tool]
)

# Analysis Agent
analysis_agent = create_agent(
    llm=ChatOpenAI(model="gpt-4"),
    tools=[calculator_tool, data_viz_tool]
)

# Coordinator Agent
coordinator = create_agent(
    llm=ChatOpenAI(model="gpt-4"),
    tools=[research_agent, analysis_agent]
)
```

### Memory Management

Configure different memory types:

<CodeGroup>
  ```python Buffer Memory theme={null}
  from langchain.memory import ConversationBufferMemory

  memory = ConversationBufferMemory(
      memory_key="chat_history",
      return_messages=True
  )
  ```

  ```python Summary Memory theme={null}
  from langchain.memory import ConversationSummaryMemory

  memory = ConversationSummaryMemory(
      llm=ChatOpenAI(model="gpt-3.5-turbo"),
      memory_key="chat_history"
  )
  ```

  ```python Window Memory theme={null}
  from langchain.memory import ConversationBufferWindowMemory

  memory = ConversationBufferWindowMemory(
      k=5,  # Remember last 5 exchanges
      memory_key="chat_history"
  )
  ```
</CodeGroup>

### Custom Prompts

Optimize agent behavior with custom prompts:

```python theme={null}
from langchain.prompts import ChatPromptTemplate

prompt = ChatPromptTemplate.from_messages([
    ("system", """You are an expert data analyst with access to various tools.
    When analyzing data:
    1. First, understand the question
    2. Gather necessary data using tools
    3. Perform calculations/analysis
    4. Provide clear insights
    5. Suggest actionable recommendations

    Be concise but thorough."""),
    ("human", "{input}"),
    ("placeholder", "{agent_scratchpad}")
])
```

***

## Monitoring & Debugging

### LangSmith Tracing

View detailed execution traces:

1. Go to [smith.langchain.com](https://smith.langchain.com)
2. Navigate to **Traces**
3. Filter by your agent
4. View:
   * Input/Output
   * Tool calls
   * Token usage
   * Latency
   * Errors

### Error Handling

Implement robust error handling:

```python theme={null}
from langchain.agents import AgentExecutor

agent_executor = AgentExecutor(
    agent=agent,
    tools=tools,
    verbose=True,
    max_iterations=10,
    max_execution_time=300,
    handle_parsing_errors=True,
    return_intermediate_steps=True
)
```

### Performance Optimization

<Steps>
  <Step title="Cache Responses">
    ```python theme={null}
    from langchain.cache import InMemoryCache
    import langchain
    langchain.llm_cache = InMemoryCache()
    ```
  </Step>

  <Step title="Parallel Tool Execution">
    ```python theme={null}
    agent_executor = AgentExecutor(
        agent=agent,
        tools=tools,
        max_iterations=10,
        early_stopping_method="generate"
    )
    ```
  </Step>

  <Step title="Optimize Token Usage">
    * Use GPT-3.5 for simple tasks
    * Implement conversation summarization
    * Trim unnecessary context
  </Step>
</Steps>

***

## Troubleshooting

<AccordionGroup>
  <Accordion title="Agent Exceeds Max Iterations">
    **Cause**: Complex query requires many steps

    **Solutions**:

    * Increase `max_iterations` to 15-20
    * Simplify the prompt
    * Break into multiple queries
    * Optimize tool descriptions
  </Accordion>

  <Accordion title="Tool Execution Fails">
    **Check**:

    * Tool function implementation
    * API credentials for external services
    * Network connectivity
    * Input parameter format

    **Debug**: Check LangSmith trace logs
  </Accordion>

  <Accordion title="Memory Issues">
    **Symptoms**: Agent forgets previous context

    **Fix**:

    * Verify memory configuration
    * Increase token limit
    * Use ConversationSummaryMemory for long conversations
  </Accordion>

  <Accordion title="Timeout Errors">
    **Cause**: Agent takes too long to respond

    **Solutions**:

    * Increase timeout in AgentFlow config
    * Optimize tool performance
    * Use faster LLM (GPT-3.5)
    * Implement async execution
  </Accordion>
</AccordionGroup>

***

## Security Best Practices

<CardGroup cols={2}>
  <Card title="API Keys" icon="key">
    Store securely, rotate regularly, use environment variables
  </Card>

  <Card title="Tool Access" icon="shield">
    Limit tools to necessary operations, implement access control
  </Card>

  <Card title="Input Validation" icon="check">
    Validate all inputs before tool execution
  </Card>

  <Card title="Output Sanitization" icon="broom">
    Filter sensitive information from responses
  </Card>

  <Card title="Rate Limiting" icon="gauge">
    Implement limits to prevent abuse
  </Card>

  <Card title="Audit Logging" icon="file-text">
    Log all agent actions for compliance
  </Card>
</CardGroup>

***

## Cost Optimization

### Token Usage Strategies

1. **Model Selection**:
   * GPT-4: Complex reasoning (\$0.03/1K tokens)
   * GPT-3.5-Turbo: Simple tasks (\$0.002/1K tokens)

2. **Prompt Engineering**:
   * Concise system prompts
   * Efficient tool descriptions
   * Clear, specific queries

3. **Memory Management**:
   * Use ConversationSummaryMemory
   * Implement conversation trimming
   * Set appropriate token limits

4. **Caching**:
   * Cache identical queries
   * Store tool results
   * Reuse computations

***

## Next Steps

<CardGroup cols={2}>
  <Card title="OpenAI Assistants" icon="robot" href="/examples/openai-agent-builder">
    Alternative agent framework
  </Card>

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

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

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