# Python AI agent libraries

Python AI agent libraries run a language model in a loop that calls tools, reads the results, and decides the next step. A framework manages the conversation state, tool definitions, and handoffs between agents across each run. These libraries let developers build agents that research, write code, and operate software for a user.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [LangChain](#langchain) | 157.1M | 149.9K | Nov 2026 | MIT |
| [LangGraph](#langgraph) | 58.7M | 45.0K | Nov 2026 | MIT |
| [Strands Agents](#strands-agents) | 38.6M | 9.2K | Nov 2026 | Apache-2.0 |
| [Pydantic AI Slim](#pydantic-ai-slim) | 36.8M | 21.2K | Nov 2026 | MIT |
| [OpenAI Agents SDK](#openai-agents) | 20.2M | 30.8K | Nov 2026 | MIT |
| [google-adk](#google-adk) | 11.0M | 22.3K | Nov 2026 | Apache-2.0 |
| [Browser Use](#browser-use) | 7.3M | 121.5K | Nov 2026 | MIT |
| [DSPy](#dspy) | 5.9M | 39.1K | Nov 2026 | MIT |

Downloads: PyPI, last thirty days. Stars and releases: GitHub. Amber: no release in over a year.

[LangChain](#langchain) has the most monthly downloads in this comparison, at 157.1M.

## Capabilities

| Library | Python three ten installation | MCP client tools |
| --- | --- | --- |
| [LangChain](#langchain) | No | Via plugin |
| [LangGraph](#langgraph) | Yes | Via plugin |
| [Strands Agents](#strands-agents) | Yes | Yes |
| [Pydantic AI Slim](#pydantic-ai-slim) | No | Via plugin |
| [OpenAI Agents SDK](#openai-agents) | Yes | Yes |
| [google-adk](#google-adk) | No | Via plugin |
| [Browser Use](#browser-use) | No | No |
| [DSPy](#dspy) | Yes | Via plugin |

## Libraries

### LangChain

[GitHub](https://github.com/langchain-ai/langchain) · [PyPI](https://pypi.org/project/langchain) · [Docs](https://reference.langchain.com/python/langchain/langchain/)

Builds LLM applications from composable components.

- Downloads / mo: 157.1M
- Stars: 149.9K
- Last release: 1.5.2
- License: MIT
- Capabilities: [From the LangChain docs](https://reference.langchain.com/python/langchain/langchain/)

```sh
python -m pip install langchain langchain-openai
```

**microsoft/langchain-for-beginners** (689 stars)

[microsoft/langchain-for-beginners](https://github.com/microsoft/langchain-for-beginners) 

```python
def main():
    print("🤖 Agent with create_agent() Example\n")

    # Create the model
    model = ChatOpenAI(
        model=os.getenv("AI_MODEL"),
        base_url=os.getenv("AI_ENDPOINT"),
        api_key=os.getenv("AI_API_KEY"),
    )

    # Create agent using create_agent() - that's it!
    agent = create_agent(model, tools=[calculator])

    # Use the agent
    query = "What is 125 * 8?"
    print(f"👤 User: {query}\n")

    # create_agent() returns a LangChain agent that expects messages array
    response = agent.invoke({"messages": [HumanMessage(content=query)]})

    # The response contains the full state, including all messages
    # Get the last message which is the agent's final answer
    last_message = response["messages"][-1]
    print(f"🤖 Agent: {last_message.content}\n")

    print("💡 Key Differences from Manual Loop:")
    print("   • create_agent() handles the ReAct loop automatically")
    print("   • Less code to write")
    print("   • Production-ready error handling built-in")
    print("   • Same result, simpler API\n")

    print("✅ Under the hood:")
    print(
        "   create_agent() implements the ReAct pattern (Thought → Action → Observation)"
    )
    print("   and handles all the boilerplate for you.")
```

[05-agents/code/01_create_agent_basic.py](https://github.com/microsoft/langchain-for-beginners/blob/978a81f8d02f837ea23d2e8f5e1b9303f16f3914/05-agents/code/01_create_agent_basic.py#L57-L92) · [More projects using LangChain →](https://dashboard.exa.ai/playground/search?q=langchain%20GitHub%20projects)

**Quickstart**

```python
from langchain.agents import create_agent
agent = create_agent(model='openai:gpt-6.1-sol', tools=[])
result = agent.invoke({'messages': [{'role': 'user', 'content': 'Hello'}]})
print(result['messages'][-1].content)

```

From [README.md](https://docs.langchain.com/oss/python/langchain/agents)

### LangGraph

[GitHub](https://github.com/langchain-ai/langgraph) · [PyPI](https://pypi.org/project/langgraph) · [Docs](https://reference.langchain.com/python/langgraph/)

Orchestrates long-running agents through stateful graphs and a runtime.

- Downloads / mo: 58.7M
- Stars: 45.0K
- Last release: 1.2.22
- License: MIT
- Capabilities: [From the LangGraph docs](https://reference.langchain.com/python/langgraph/)

**Strengths**

- **Retains graph state in checkpoints.** Use a checkpointer to retain thread-scoped state across graph runs.
- **Pauses for application approval.** Interrupt graph execution and resume it with an application-supplied response.

**Watch out for**

- **Persistence needs a checkpointer.** Configure a checkpointer before relying on retained thread state.
- **Resuming restarts the interrupted node.** Keep code before an interrupt safe to repeat.

```sh
python -m pip install langgraph
```

**assafelovic/gpt-researcher** (30.7K stars)

[assafelovic/gpt-researcher](https://github.com/assafelovic/gpt-researcher) 

```python
def _create_workflow(self, agents):
    workflow = StateGraph(ResearchState)

    # Add nodes for each agent
    workflow.add_node("browser", agents["research"].run_initial_research)
    workflow.add_node("planner", agents["editor"].plan_research)
    workflow.add_node("researcher", agents["editor"].run_parallel_research)
    workflow.add_node("writer", agents["writer"].run)
    workflow.add_node("fact_checker", agents["fact_checker"].run)
    workflow.add_node("visualizer", agents["visualizer"].run)
    workflow.add_node("publisher", agents["publisher"].run)
    workflow.add_node("human", agents["human"].review_plan)

    # Add edges
    self._add_workflow_edges(workflow)

    return workflow
```

[multi_agents/agents/orchestrator.py](https://github.com/assafelovic/gpt-researcher/blob/ddd4db36208d9c8e49f3b2436efda97baecb5433/multi_agents/agents/orchestrator.py#L65-L81) · [More projects using LangGraph →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20langgraph%20for%20agent%20orchestration%20tool%20workflows%20state%20and%20delegation&filters=%7B%22type%22%3A%20%22auto%22%2C%20%22numResults%22%3A%2010%2C%20%22includeDomains%22%3A%20%5B%22github.com%22%5D%7D)

**Quickstart**

```python
from typing_extensions import TypedDict
from langgraph.graph import END, START, StateGraph

class State(TypedDict):
    text: str

def node_a(state: State):
    return {'text': state['text'] + 'a'}

graph = (StateGraph(State)
    .add_node('node_a', node_a)
    .add_edge(START, 'node_a')
    .add_edge('node_a', END)
    .compile())
print(graph.invoke({'text': ''}))

```

From [graph-api.md](https://docs.langchain.com/oss/python/langgraph/graph-api)

### Strands Agents

[GitHub](https://github.com/strands-agents/harness-sdk) · [PyPI](https://pypi.org/project/strands-agents) · [Docs](https://strandsagents.com)

Builds AI agents with a model-driven approach.

- Downloads / mo: 38.6M
- Stars: 9.2K
- Last release: 1.65.0
- License: Apache-2.0
- Capabilities: [From the Strands Agents docs](https://strandsagents.com)

```sh
python -m pip install strands-agents
```

**headroomlabs-ai/headroom** (80.2K stars)

[headroomlabs-ai/headroom](https://github.com/headroomlabs-ai/headroom) 

```python
def run_hook_provider_demo(region: str = "us-west-2") -> dict[str, Any]:
    """Demonstrate HeadroomHookProvider for tool output compression.

    Returns metrics from the demo run.
    """
    from strands import Agent, tool
    from strands.models import BedrockModel

    from headroom.integrations.strands import HeadroomHookProvider

    print_box(
        "Demo 1: HeadroomHookProvider",
        [
            "The HeadroomHookProvider intercepts tool outputs and compresses",
            "them BEFORE they're added to the conversation context.",
            "",
            "This reduces token usage for subsequent LLM calls by eliminating",
            "redundant data from verbose tool outputs.",
            "",
            "Using: Claude 3 Haiku (anthropic.claude-3-haiku-20240307-v1:0)",
        ],
    )

    # Define tools with @tool decorator
    @tool
    def search_docs_tool(query: str) -> str:
        """Search documentation for articles matching the query.

        Args:
            query: The search query to find relevant documentation

        Returns:
            JSON array of search results with titles, snippets, and URLs
        """
        return search_documentation(query, limit=25)

    @tool
    def get_logs_tool(server: str, lines: int = 100) -> str:
        """Fetch server logs for analysis and troubleshooting.

        Args:
            server: Name of the server to fetch logs from
            lines: Number of log lines to retrieve (default: 100)

        Returns:
            JSON array of log entries with timestamps and messages
        """
        return get_server_logs(server, lines=lines)

    @tool
    def query_db_tool(sql: str) -> str:
        """Execute a database query and return results.

        Args:
            sql: SQL query to execute (e.g., SELECT * FROM users)

        Returns:
            JSON array of database rows
        """
        return query_database(sql, limit=50)

    @tool
    def get_metrics_tool(timerange: str = "1h") -> str:
        """Get system metrics for the specified time range.

        Args:
            timerange: Time range for metrics (5m, 15m, 1h, 6h, 24h)

        Returns:
            JSON object with time-series metrics data
        """
        return get_system_metrics(timerange)

    # Create BedrockModel
    model = BedrockModel(
        model_id="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
        region_name=region,
        temperature=0.1,
    )

    # Create HeadroomHookProvider
    hook_provider = HeadroomHookProvider(
        compress_tool_outputs=True,
        min_tokens_to_compress=100,  # Compress outputs with 100+ tokens
        preserve_errors=True,
    )

    # Create agent with hook
    agent = Agent(
        model=model,
        tools=[search_docs_tool, get_logs_tool, query_db_tool, get_metrics_tool],
        hooks=[hook_provider],
    )

    print("\n  Running agent queries that trigger tools with verbose output...")
    print("  " + "-" * 60)

    # Query 1: Search documentation
    print("\n  Query 1: Searching documentation...")
    result1 = agent(
        "Search the documentation for 'authentication setup' and summarize "
        "the top 3 most relevant articles you find."
    )
    print(f"  Response: {str(result1)[:200]}...")

    # Query 2: Get server logs
    print("\n  Query 2: Fetching server logs...")
    result2 = agent(
        "Get the logs from server 'api-gateway' (100 lines) and tell me "
        "how many ERROR and WARN level entries there are."
    )
    print(f"  Response: {str(result2)[:200]}...")

    # Query 3: Query database
    print("\n  Query 3: Running database query...")
    result3 = agent(
        "Query the orders table and tell me how many orders have status 'completed' "
        "and what the average order total is."
    )
    print(f"  Response: {str(result3)[:200]}...")

    # Query 4: Get metrics
    print("\n  Query 4: Fetching system metrics...")
    result4 = agent(
        "Get the system metrics for the last hour and identify if there are "
        "any services with high CPU usage (>70%) or memory issues."
    )
    print(f"  Response: {str(result4)[:200]}...")

    # Get metrics
    metrics = hook_provider.get_savings_summary()

    # Display results
    print_box(
        "HeadroomHookProvider Results",
        [
            f"Tool calls processed:    {metrics['total_requests']}",
            f"Compressions applied:    {metrics['compressed_requests']}",
            "",
            f"Tokens BEFORE compression: {metrics['total_tokens_before']:,}",
            f"Tokens AFTER compression:  {metrics['total_tokens_after']:,}",
            f"Tokens SAVED:              {metrics['total_tokens_saved']:,}",
            "",
            f"Average savings:           {metrics['average_savings_percent']:.1f}%",
        ],
        style="success",
    )

    # Show per-tool breakdown
    if hook_provider.metrics_history:
        tool_metrics = []
        for m in hook_provider.metrics_history:
            tool_metrics.append(
                {
                    "tool": m.tool_name[:20],
                    "before": f"{m.tokens_before:,}",
                    "after": f"{m.tokens_after:,}",
                    "saved": f"{m.tokens_saved:,}",
                    "pct": f"{m.savings_percent:.1f}%",
                }
            )

        print_metrics_table(
            tool_metrics,
            headers=["Tool", "Before", "After", "Saved", "%"],
            keys=["tool", "before", "after", "saved", "pct"],
            title="Per-Tool Compression Breakdown",
        )

    print_comparison(
        metrics["total_tokens_before"],
        metrics["total_tokens_after"],
        "Tool Output Tokens",
    )

    return metrics

```

[examples/strands_bedrock_demo.py](https://github.com/headroomlabs-ai/headroom/blob/e27f0d96cc3032d5f2c510ac97545553b867a697/examples/strands_bedrock_demo.py#L514-L689) · [More projects using Strands Agents →](https://dashboard.exa.ai/playground/search?q=strands-agents%20GitHub%20projects)

**Quickstart**

```python
from strands import Agent
agent = Agent()
print(agent('Hello'))

```

From [README.md](https://pypi.org/pypi/strands-agents/1.65.0/json#info.description)

### Pydantic AI Slim

[GitHub](https://github.com/pydantic/pydantic-ai) · [PyPI](https://pypi.org/project/pydantic-ai-slim) · [Docs](https://pydantic.dev/docs/ai/overview/install/#slim-install)

Provides the slim package of the Pydantic AI agent framework.

- Downloads / mo: 36.8M
- Stars: 21.2K
- Last release: 2.69.0
- License: MIT
- Capabilities: [From the Pydantic AI Slim docs](https://pydantic.dev/docs/ai/overview/install/#slim-install)

```sh
python -m pip install "pydantic-ai-slim[openai]"
```

**UKGovernmentBEIS/inspect_ai** (3.3K stars)

[UKGovernmentBEIS/inspect_ai](https://github.com/UKGovernmentBEIS/inspect_ai) 

```python
@agent
def web_research_agent() -> Agent:
    """Pydantic AI Web Research Agent."""

    async def execute(state: AgentState) -> AgentState:
        async with agent_bridge(state) as bridge:
            agent = PydanticAgent(
                _pydantic_bridge_model(),
                capabilities=[WebSearch()],
                system_prompt="You help users find information by searching the web.",
                output_type=AnswerToQueryOutput,
                retries={"output": 3},
            )

            result = await agent.run(user_prompt(state.messages).text)

            # capture the typed result as the completion (as the final
            # assistant message includes on the `final_answer()` tool
            # call that PydanticAI uses to report its answer
            bridge.state.output.completion = result.output.model_dump_json()

            return bridge.state

    return execute
```

[examples/bridge/pydantic-ai/agent.py](https://github.com/UKGovernmentBEIS/inspect_ai/blob/b1816681f4f4b7e6fb492c555befe1bb724706f0/examples/bridge/pydantic-ai/agent.py#L34-L57) · [More projects using Pydantic AI Slim →](https://dashboard.exa.ai/playground/search?q=pydantic-ai-slim%20GitHub%20projects)

**Quickstart**

```python
from pydantic_ai import Agent
agent = Agent('openai:gpt-5.2')
result = agent.run_sync('What is the capital of France?')
print(result.output)

```

From [README.md](https://pydantic.dev/docs/ai/api/agent/)

### OpenAI Agents SDK

[GitHub](https://github.com/openai/openai-agents-python) · [PyPI](https://pypi.org/project/openai-agents) · [Docs](https://pypi.org/project/openai-agents/)

Provides the OpenAI SDK for building agents.

- Downloads / mo: 20.2M
- Stars: 30.8K
- Last release: 0.25.0
- License: MIT
- Capabilities: [From the OpenAI Agents SDK docs](https://pypi.org/project/openai-agents/)

```sh
python -m pip install openai-agents
```

**openai/openai-cs-agents-demo** (6.6K stars)

[openai/openai-cs-agents-demo](https://github.com/openai/openai-cs-agents-demo) 

```python
@input_guardrail(name="Relevance Guardrail")
async def relevance_guardrail(
    context: RunContextWrapper[None], agent: Agent, input: str | list[TResponseInputItem]
) -> GuardrailFunctionOutput:
    """Guardrail to check if input is relevant to airline topics."""
    result = await Runner.run(
        guardrail_agent,
        input,
        context=context.context.state if hasattr(context.context, "state") else context.context,
    )
    final = result.final_output_as(RelevanceOutput)
    return GuardrailFunctionOutput(output_info=final, tripwire_triggered=not final.is_relevant)

```

[python-backend/airline/guardrails.py](https://github.com/openai/openai-cs-agents-demo/blob/bd7bfca0f5abf50529370814c3e7c88542011925/python-backend/airline/guardrails.py#L39-L50) · [More projects using OpenAI Agents SDK →](https://dashboard.exa.ai/playground/search?q=openai-agents%20GitHub%20projects)

**Quickstart**

```python
from agents import Agent, Runner
agent = Agent(name='Assistant', instructions='You are a helpful assistant')
result = Runner.run_sync(agent, 'Write a haiku about recursion in programming.')
print(result.final_output)

```

From [README.md](https://github.com/openai/openai-agents-python/blob/91fb508a8931016efa793b033147d08cd20308cf/README.md)

### google-adk

[GitHub](https://github.com/google/adk-python) · [PyPI](https://pypi.org/project/google-adk) · [Docs](https://pypi.org/project/google-adk/)

Provides the Google Agent Development Kit.

- Downloads / mo: 11.0M
- Stars: 22.3K
- Last release: 2.14.1
- License: Apache-2.0
- Capabilities: [From the google-adk docs](https://pypi.org/project/google-adk/)

```sh
python -m pip install google-adk
```

**google/adk-docs** (1.5K stars)

[google/adk-docs](https://github.com/google/adk-docs) 

```python
async def call_agent_async(query):
    content = types.Content(role='user', parts=[types.Part(text=query)])
    session, runner = await setup_session_and_runner()
    events = runner.run_async(user_id=USER_ID, session_id=SESSION_ID, new_message=content)

    async for event in events:
        if event.is_final_response() and event.content and event.content.parts:
            final_response = event.content.parts[0].text
            print("Agent Response: ", final_response)
```

[examples/python/snippets/tools/overview/customer_support_agent.py](https://github.com/google/adk-docs/blob/ff7a5f56469a81f3e43a8fc54668d8dc84300192/examples/python/snippets/tools/overview/customer_support_agent.py#L65-L73) · [More projects using google-adk →](https://dashboard.exa.ai/playground/search?q=google-adk%20GitHub%20projects)

**Quickstart**

```python
import asyncio
from google.adk import Agent
from google.adk.runners import InMemoryRunner
agent = Agent(name='greeting_agent', model='gemini-3.5-flash', instruction='Greet the user warmly.')
runner = InMemoryRunner(agent=agent)
asyncio.run(runner.run_debug('Hello'))

```

From [runners.py](https://github.com/google/adk-python/blob/e2a21ac23260d043bf9d217b573af1bef48f0f70/src/google/adk/runners.py)

### Browser Use

[GitHub](https://github.com/browser-use/browser-use) · [PyPI](https://pypi.org/project/browser-use) · [Docs](https://docs.browser-use.com)

Runs a browser agent on Pydantic AI against cloud or local Chrome.

- Downloads / mo: 7.3M
- Stars: 121.5K
- Last release: 1.0.6
- License: MIT
- Capabilities: [From the Browser Use docs](https://docs.browser-use.com)

```sh
python -m pip install browser-use==1.0.6
```

**Quickstart**

```python
from browser_use import Agent
result = Agent('Find the number of stars of the browser-use repo').run_sync()
print(result.final_result())

```

From [README.md](https://github.com/browser-use/browser-use/blob/ccbdb8095fbaf903c748880a600054a34c7b6191/README.md) · [Find projects using Browser Use →](https://dashboard.exa.ai/playground/search?q=browser-use%20GitHub%20projects)

### DSPy

[GitHub](https://github.com/stanfordnlp/dspy) · [PyPI](https://pypi.org/project/dspy) · [Docs](https://pypi.org/project/dspy/)

Programs language models with code rather than prompts.

- Downloads / mo: 5.9M
- Stars: 39.1K
- Last release: 3.5.0
- License: MIT
- Capabilities: [From the DSPy docs](https://pypi.org/project/dspy/)

```sh
python -m pip install dspy
```

**Quickstart**

```python
import dspy
dspy.configure(lm=dspy.LM('openai/gpt-4.1-mini'))
agent = dspy.ReAct('question -> answer', tools=[])
result = agent(question='What is the capital of France?')
print(result.answer)

```

From [mcp.md](https://github.com/stanfordnlp/dspy/blob/9d3a8eb04618907854256e5b0fa88ea29e53e10b/docs/docs/learn/programming/mcp.md) · [Find projects using DSPy →](https://dashboard.exa.ai/playground/search?q=dspy%20GitHub%20projects)

## FAQ

### Which Python AI agent library should I use?

[LangGraph](#langgraph) suits long-running agents that need explicit state and control flow. [OpenAI Agents SDK](#openai-agents) and [Pydantic AI Slim](#pydantic-ai-slim) suit smaller agents with typed tools and handoffs. [Browser Use](#browser-use) suits agents that operate a web browser.

### What is LangGraph?

[LangGraph](#langgraph) orchestrates long-running agents as stateful graphs of steps. Its runtime persists state between steps, letting a run pause for human input and resume.

### What is LangChain?

[LangChain](#langchain) is a framework for building LLM applications from composable parts such as models, prompts, tools, and retrievers. Its agents run on LangGraph.

### LangChain vs LangGraph: what is the difference?

[LangChain](#langchain) provides model integrations and a high-level agent API. [LangGraph](#langgraph) is the lower-level runtime for agents that need custom control flow and durable state.

### What is DSPy?

[DSPy](#dspy) is a framework for programming language models with declarative modules instead of hand-written prompts. Its optimizers tune prompts and weights against a metric.

### What is Google ADK?

[google-adk](#google-adk) is the Agent Development Kit, an open-source Google framework for building and deploying agents. It works with Gemini and other models.

## How this page was built

Data checked Nov 20, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python AI agent libraries LangGraph CrewAI Pydantic AI smolagents code examples",
    "numResults": 5
  }
}
```

Docs: https://exa.ai/docs/reference/search
