# LangChain & DeepAgents

DeepAgents is a framework for building autonomous AI agents that can perform deep research and complex tasks. Built on LangChain, DeepAgents provides tools for creating agents that can plan, research, critique, and iterate on their outputs.

InteractiveAI integrates with LangChain DeepAgents using the built-in CallbackHandler. The SDK automatically captures detailed traces of your DeepAgents executions, including planning steps, research iterations, tool calls, and sub-agent interactions.

### Prerequisites

* InteractiveAI account with API credentials
* Anthropic API key
* Web search API (e.g.: Tavily)
* Python 3.11 or higher

***

### Installation

```bash
pip install interactiveai deepagents tavily-python
```

***

### Configuration

Initialize the client and the CallbackHandler:

```python
import os
from dotenv import load_dotenv

load_dotenv()

from interactiveai import Interactive
from interactiveai.langchain import CallbackHandler

interactiveai = Interactive(
    public_key=os.getenv("INTERACTIVEAI_PUBLIC_KEY"),
    secret_key=os.getenv("INTERACTIVEAI_SECRET_KEY"),
)

handler = CallbackHandler()

if interactiveai.auth_check():
    print("Connection established")
else:
    print("Authentication failed - verify credentials")
```

***

### Example 1: Research Agent with Web Search

Create a research agent that can search the web and synthesize information:

```python
from typing import Literal
from tavily import TavilyClient
from deepagents import create_deep_agent

tavily = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])


def web_search(
    query: str,
    max_results: int = 5,
    topic: Literal["general", "news", "finance"] = "general",
) -> dict:
    """Search the web for information."""
    return tavily.search(query, max_results=max_results, topic=topic)


system_prompt = """You are an expert analyst. Your job is to research topics thoroughly and provide clear, actionable insights.

You have access to a web search tool. Use it to gather current information before forming your analysis.

Structure your responses with:
1. Key findings
2. Supporting evidence
3. Recommendations
"""

agent = create_deep_agent(
    tools=[web_search],
    system_prompt=system_prompt,
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "What are the latest trends in AI agent frameworks?"}]},
    config={"callbacks": [handler]}
)

print(result)
client.flush()
```

### Example 2: Multi-Agent Research Pipeline

Create a sophisticated agent with specialized sub-agents for research and review:

```python
from typing import Literal
from tavily import TavilyClient
from deepagents import create_deep_agent

tavily = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])


def web_search(
    query: str,
    max_results: int = 5,
    topic: Literal["general", "news", "finance"] = "general",
) -> dict:
    """Search the web for information."""
    return tavily.search(query, max_results=max_results, topic=topic)


# Sub-agent for focused research
research_agent = {
    "name": "researcher",
    "description": "Conducts deep research on a specific topic. Give this agent one focused question at a time.",
    "system_prompt": """You are a dedicated researcher. Conduct thorough research using the search tool and provide detailed findings.
    
Your final message should contain all relevant information - the user will only see your final response.""",
    "tools": [web_search],
}

# Sub-agent for quality review
review_agent = {
    "name": "reviewer", 
    "description": "Reviews and critiques research reports for completeness and accuracy.",
    "system_prompt": """You are a quality reviewer. Evaluate reports for:
- Completeness of coverage
- Accuracy of claims
- Clarity of presentation
- Missing perspectives

Provide specific, actionable feedback.""",
}

# Main orchestrator agent
orchestrator_prompt = """You are a research director coordinating a team of specialists.

Your workflow:
1. Break down complex questions into focused research tasks
2. Delegate to the researcher agent for each topic
3. Compile findings into a comprehensive report
4. Send to the reviewer agent for quality check
5. Iterate based on feedback until satisfied

Write your final report in clear markdown with proper citations.
"""

agent = create_deep_agent(
    tools=[web_search],
    system_prompt=orchestrator_prompt,
    subagents=[research_agent, review_agent],
)

result = agent.invoke(
    {"messages": [{"role": "user", "content": "Compare the architectural approaches of CrewAI, AutoGen, and LangGraph for building multi-agent systems."}]},
    config={"callbacks": [handler]}
)

print(result)
client.flush()
```

***

### Enriching Traces with Context

Add user tracking and metadata to your DeepAgents traces:

```python
import os
from dotenv import load_dotenv
from typing import Literal

load_dotenv()

from interactiveai import Interactive
from interactiveai.langchain import CallbackHandler
from tavily import TavilyClient
from deepagents import create_deep_agent

client = Interactive(
    public_key=os.getenv("INTERACTIVEAI_PUBLIC_KEY"),
    secret_key=os.getenv("INTERACTIVEAI_SECRET_KEY"),
    host=os.getenv("INTERACTIVEAI_HOST", "https://app.interactive.ai"),
)

handler = CallbackHandler()
tavily = TavilyClient(api_key=os.environ["TAVILY_API_KEY"])


def web_search(
    query: str,
    max_results: int = 5,
    topic: Literal["general", "news", "finance"] = "general",
) -> dict:
    """Search the web for information."""
    return tavily.search(query, max_results=max_results, topic=topic)


agent = create_deep_agent(
    tools=[web_search],
    system_prompt="You are a helpful research assistant with web search capabilities.",
)

with client.start_as_current_span(name="deepagents-research") as span:
    
    client.update_current_trace(
        user_id="user_456",
        session_id="session_xyz",
        tags=["deepagents", "research"],
        metadata={"use_case": "competitive-analysis", "environment": "production"}
    )
    
    query = "What are the key differences between vector databases Pinecone, Weaviate, and Chroma?"
    
    result = agent.invoke(
        {"messages": [{"role": "user", "content": query}]},
        config={"callbacks": [handler]}
    )
    
    span.update(
        input={"query": query},
        output={"result": str(result)}
    )

client.flush()
```

***

### Trace Visibility

After execution, the InteractiveAI dashboard displays:

* Complete agent execution flow including planning steps
* Sub-agent interactions and handoffs
* Tool invocations (web searches) with results
* Token usage across all agent calls
* Full reasoning chain for debugging
* Cost and latency metrics per step


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://docs.interactive.ai/integrations/ai-frameworks/langchain-and-deepagents.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
