# Python LLM libraries

Python LLM libraries wrap calls to large language models (LLMs) and organize the work around them, such as tool calls, retrieval, and multi-step workflows. These libraries are how developers build AI agents and chat features on top of a model provider's API.

## Popularity

| Library | Monthly downloads | Stars | Last release | License |
| --- | --- | --- | --- | --- |
| [LangChain](#langchain) | 156.9M | 149.6K | Nov 2026 | MIT |
| [LangGraph](#langgraph) | 60.4M | 45.1K | Nov 2026 | MIT |
| [Pydantic AI](#pydantic-ai-slim) | 36.2M | 21.3K | Nov 2026 | MIT |
| [Google ADK](#google-adk) | 10.9M | 22.3K | Nov 2026 | Apache-2.0 |
| [Instructor](#instructor) | 10.1M | 14.1K | Sep 2026 | MIT |
| [DSPy](#dspy) | 5.8M | 39.1K | Nov 2026 | MIT |
| [LlamaIndex Core](#llamaindex-core) | 5.7M | 53.0K | Nov 2026 | MIT |
| [CrewAI](#crewai) | 2.6M | 61.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 156.9M.

## Capabilities

| Library | Agent tool-execution workflows | Native human input or approval |
| --- | --- | --- |
| [LangChain](#langchain) | Yes | Yes |
| [LangGraph](#langgraph) | Yes | Yes |
| [Pydantic AI](#pydantic-ai-slim) | Yes | Yes |
| [Google ADK](#google-adk) | Yes | Yes |
| [Instructor](#instructor) | No | No |
| [DSPy](#dspy) | Yes | Undocumented |
| [LlamaIndex Core](#llamaindex-core) | Yes | Yes |
| [CrewAI](#crewai) | Yes | Yes |

## Libraries

### LangChain

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

LangChain is a framework for building agents and other applications on large language models. `init_chat_model` opens a chat model from any supported provider by name, and `create_agent` combines a model, a list of tools, and middleware into an agent that calls tools until it reaches an answer. A declared schema returns the final answer as validated data. Each provider, vector store, and tool comes from a separate integration package, and the agent itself runs on LangGraph.

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

**Strengths**

- **Creates customizable tool agents.** Compose a model, tools, and middleware with create_agent.
- **Validates structured agent responses.** Declare a schema and receive validated data in structured_response.

**Watch out for**

- **Provider integrations install separately.** Install the package for the chosen model provider.
- **JSON schemas need explicit strategies.** Wrap schema dictionaries in ProviderStrategy or ToolStrategy.

```sh
pip install -U "langchain[openai]"
```

**langchain-ai/open_deep_research** (12.7K stars)

[langchain-ai/open_deep_research](https://github.com/langchain-ai/open_deep_research) 

```python
async def write_research_brief(state: AgentState, config: RunnableConfig) -> Command[Literal["research_supervisor"]]:
    """Transform user messages into a structured research brief and initialize supervisor.

    This function analyzes the user's messages and generates a focused research brief
    that will guide the research supervisor. It also sets up the initial supervisor
    context with appropriate prompts and instructions.

    Args:
        state: Current agent state containing user messages
        config: Runtime configuration with model settings

    Returns:
        Command to proceed to research supervisor with initialized context
    """
    # Step 1: Set up the research model for structured output
    configurable = Configuration.from_runnable_config(config)
    research_model_config = {
        "model": configurable.research_model,
        "max_tokens": configurable.research_model_max_tokens,
        "api_key": get_api_key_for_model(configurable.research_model, config),
        "tags": ["langsmith:nostream"]
    }

    # Configure model for structured research question generation
    research_model = (
        configurable_model
        .with_structured_output(ResearchQuestion)
        .with_retry(stop_after_attempt=configurable.max_structured_output_retries)
        .with_config(research_model_config)
    )

    # Step 2: Generate structured research brief from user messages
    prompt_content = transform_messages_into_research_topic_prompt.format(
        messages=get_buffer_string(state.get("messages", [])),
        date=get_today_str()
    )
    response = await research_model.ainvoke([HumanMessage(content=prompt_content)])

    # Step 3: Initialize supervisor with research brief and instructions
    supervisor_system_prompt = lead_researcher_prompt.format(
        date=get_today_str(),
        max_concurrent_research_units=configurable.max_concurrent_research_units,
        max_researcher_iterations=configurable.max_researcher_iterations
    )

    return Command(
        goto="research_supervisor", 
        update={
            "research_brief": response.research_brief,
            "supervisor_messages": {
                "type": "override",
                "value": [
                    SystemMessage(content=supervisor_system_prompt),
                    HumanMessage(content=response.research_brief)
                ]
            }
        }
    )
```

[src/open_deep_research/deep_researcher.py](https://github.com/langchain-ai/open_deep_research/blob/1b7d2e80db9faa586165c60e09096dbbfd483a64/src/open_deep_research/deep_researcher.py#L118-L175) · [More projects using LangChain →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20langchain%20for%20research%20dialogue%2C%20retrieval-pipeline%20initialization%20and%20streamed%20document%20querying&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 langchain.chat_models import init_chat_model

model = init_chat_model("gpt-6.1-sol")
response = model.invoke("Why do parrots have colorful feathers?")
print(response)

```

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

### LangGraph

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

LangGraph is a low-level framework and runtime for long-running, stateful agents. A workflow is a graph: nodes are Python functions that read and update a shared state, and edges decide which node runs next, including loops and branches. The graph compiles before it runs, and compilation is where a checkpointer attaches. With a checkpointer, a run survives failures and resumes where it stopped, and an interrupt pauses the graph to wait for human input.

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

**Strengths**

- **Pauses for human input.** An interrupt saves the graph state and waits for external input before the run continues.

```sh
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=langgraph%20GitHub%20projects)

**Quickstart**

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

class State(TypedDict):
    message: str

builder = StateGraph(State)
builder.add_node('echo', lambda state: {'message': state['message']})
builder.add_edge(START, 'echo')
builder.add_edge('echo', END)
print(builder.compile().invoke({'message': 'hello'}))

```

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

### Pydantic AI

[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)

Pydantic AI is an agent framework from the Pydantic team. An `Agent` has a model name, instructions, tools, and an output type, and `run` executes the agent loop and returns output validated against that type. Switching providers means changing the model string, and a fallback model can take over when a provider fails. Tools can require human approval before they run, and agents can run under durable execution engines such as Temporal. The `pydantic-ai-slim` package installs the core, with each provider added as an extra.

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

**Strengths**

- **Swaps models by name.** The same agent runs on another provider by changing the model string.
- **Tool approval built in.** A tool marked requires_approval waits for a person to approve the call.

```sh
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 →](https://dashboard.exa.ai/playground/search?q=pydantic-ai-slim%20GitHub%20projects)

**Quickstart**

```python
from pydantic_ai import Agent, AgentRunResultEvent, AgentStreamEvent

agent = Agent('openai:gpt-6.1-sol')

result_sync = agent.run_sync('What is the capital of Italy?')
print(result_sync.output)
#> The capital of Italy is Rome.

```

From [agents.md](https://ai.pydantic.dev/agents/)

### Google ADK

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

Google ADK, the Agent Development Kit, is a framework for defining, evaluating, and deploying agents in Python code. An agent combines a model, instructions, and tools, which can be Python functions, OpenAPI specs, or MCP tools, and several agents can be composed into a hierarchy. A graph-based workflow runtime adds routing, loops, retries, and human input to a run. The kit is optimized for Gemini but works with other models, and agents deploy to Cloud Run or Google's managed agent runtime.

- Downloads / mo: 10.9M
- Stars: 22.3K
- Last release: 2.14.1
- License: Apache-2.0
- Capabilities: [From the Google ADK docs](https://google.github.io/adk-docs/)

**Strengths**

- **Model-agnostic, Gemini-first.** Agents run on Gemini or on other models, and work with other frameworks.

```sh
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
import os
from google.adk.agents import Agent
from google.adk.runners import InMemoryRunner

async def main():
    agent = Agent(name='assistant', model=os.environ['GEMINI_MODEL'], instruction='Answer briefly.')
    runner = InMemoryRunner(agent=agent)
    await runner.run_debug('Hello')

asyncio.run(main())

```

From [runners.py](https://raw.githubusercontent.com/google/adk-python/v2.14.1/src/google/adk/runners.py)

### Instructor

[GitHub](https://github.com/567-labs/instructor) · [PyPI](https://pypi.org/project/instructor) · [Docs](https://pypi.org/project/instructor/)

Instructor returns structured data from a language model as a validated Pydantic object. A Pydantic class declares the fields, `instructor.from_provider` opens a client for a named provider and model, and a call with `response_model` returns an instance of that class instead of raw text. When validation fails, Instructor sends the errors back to the model and retries. The library handles single extraction calls, and its README points to Pydantic AI for full agents.

- Downloads / mo: 10.1M
- Stars: 14.1K
- Last release: 1.17.0
- License: MIT
- Capabilities: [From the Instructor docs](https://pypi.org/project/instructor/)

**Strengths**

- **Same code across providers.** `instructor.from_provider` takes a provider and model name, such as OpenAI, Anthropic, Google, or Ollama, and returns the same client.
- **Retries on failed validation.** When a reply fails Pydantic validation, Instructor sends the request again.

**Watch out for**

- **Extraction only.** The Instructor README points agent workflows to Pydantic AI.

```sh
pip install instructor
```

**cocoindex-io/cocoindex** (11.9K stars)

[cocoindex-io/cocoindex](https://github.com/cocoindex-io/cocoindex) 

```python
@coco.fn(memo=True)
async def extract_relationships(content: str) -> list[Triple]:
    client = cast(
        instructor.AsyncInstructor,
        instructor.from_litellm(litellm.acompletion, mode=instructor.Mode.JSON),
    )
    result = await client.chat.completions.create(
        model=coco.use_context(LLM_MODEL),
        response_model=RelationshipList,
        messages=[
            {"role": "system", "content": RELATIONSHIP_PROMPT},
            {"role": "user", "content": content},
        ],
    )
    validated = RelationshipList.model_validate(result.model_dump())
    return [Triple(r.subject, r.predicate, r.object) for r in validated.relationships]
```

[examples/docs_to_knowledge_graph/main.py](https://github.com/cocoindex-io/cocoindex/blob/42770c97d6ae6e38f80d640b404dae06a6ffec11/examples/docs_to_knowledge_graph/main.py) · [More projects using Instructor →](https://dashboard.exa.ai/playground/search?q=instructor%20GitHub%20projects)

**Quickstart**

```python
import instructor
from pydantic import BaseModel


# Define what you want
class User(BaseModel):
 name: str
 age: int


# Extract it from natural language
client = instructor.from_provider("openai/gpt-4o-mini")
user = client.chat.completions.create(
 response_model=User,
 messages=[{"role": "user", "content": "John is 25 years old"}],
)

print(user) # User(name='John', age=25)

```

From [README.md](https://pypi.org/pypi/instructor/1.17.0/json#info.description)

### DSPy

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

DSPy builds language model programs from Python code instead of hand-written prompts. A signature declares a task's typed inputs and outputs, such as a question in and an answer out, and modules such as `Predict` and `ChainOfThought` turn a signature into model calls. Modules compose into larger programs, including retrieval pipelines and agent loops. Optimizers such as `GEPA` then tune the prompts, and optionally the weights, using example data and a scoring function.

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

**Strengths**

- **Defines tasks with typed signatures.** Declare input and output fields instead of assembling prompts manually.
- **Optimizes prompts against a metric.** Use examples and a scoring function to tune the program.

**Watch out for**

- **Optimization needs examples and metrics.** Provide evaluation data and a scoring function before optimizing the program.
- **Cached streams skip token chunks.** Cached results yield the final prediction rather than individual streamed tokens.

```sh
pip install dspy
```

**stanford-oval/storm** (31.9K stars)

[stanford-oval/storm](https://github.com/stanford-oval/storm) 

```python
def forward(
    self,
    topic: str,
    persona: str,
    dialogue_turns: List[DialogueTurn],
    draft_page=None,
):
    conv = []
    for turn in dialogue_turns[:-4]:
        conv.append(
            f"You: {turn.user_utterance}\nExpert: Omit the answer here due to space limit."
        )
    for turn in dialogue_turns[-4:]:
        conv.append(
            f"You: {turn.user_utterance}\nExpert: {ArticleTextProcessing.remove_citations(turn.agent_utterance)}"
        )
    conv = "\n".join(conv)
    conv = conv.strip() or "N/A"
    conv = ArticleTextProcessing.limit_word_count_preserve_newline(conv, 2500)

    with dspy.settings.context(lm=self.engine):
        if persona is not None and len(persona.strip()) > 0:
            question = self.ask_question_with_persona(
                topic=topic, persona=persona, conv=conv
            ).question
        else:
            question = self.ask_question(
                topic=topic, persona=persona, conv=conv
            ).question

    return dspy.Prediction(question=question)
```

[knowledge_storm/storm_wiki/modules/knowledge_curation.py](https://github.com/stanford-oval/storm/blob/fb951af7744dab086e34962e9bc6fe878e145f83/knowledge_storm/storm_wiki/modules/knowledge_curation.py#L95-L125) · [More projects using DSPy →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20dspy%20for%20research%20dialogue%2C%20retrieval-pipeline%20initialization%20and%20streamed%20document%20querying&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
import os
import dspy

dspy.configure(lm=dspy.LM(os.environ['DSPY_MODEL']))
answer = dspy.Predict('question -> answer')
print(answer(question='What is a hash table?').answer)

```

From [index.md](https://dspy.ai/current/getting-started/first-program/)

### LlamaIndex Core

[GitHub](https://github.com/run-llama/llama_index) · [PyPI](https://pypi.org/project/llama-index-core) · [Docs](https://docs.llamaindex.ai/en/stable/)

LlamaIndex is a framework for applications that answer from a body of documents. The `llama-index-core` package contains the core classes, and models, embeddings, and vector stores come from separate integration packages. `SimpleDirectoryReader` loads files, `VectorStoreIndex` splits them into chunks and embeds them, and `as_query_engine` answers questions from the retrieved chunks. Indexes start in memory and persist to disk on request. Agents and event-driven workflows build on the same parts.

- Downloads / mo: 5.7M
- Stars: 53.0K
- Last release: 0.14.26
- License: MIT
- Capabilities: [From the LlamaIndex Core docs](https://docs.llamaindex.ai/en/stable/)

**Strengths**

- **Indexes documents for model queries.** Build an index and retrieve relevant context through a query engine.
- **Wraps functions as agent tools.** Convert existing functions into tools with inferred schemas.

**Watch out for**

- **Streaming waits for earlier calls.** Earlier model calls finish before the final answer starts streaming.
- **Indexes start in memory.** Persist index storage to retain it after the process exits.

```sh
pip install llama-index-core llama-index-llms-openai
```

**open-webui/pipelines** (2.4K stars)

[open-webui/pipelines](https://github.com/open-webui/pipelines) 

```python
def pipe(
    self, user_message: str, model_id: str, messages: List[dict], body: dict
) -> Union[str, Generator, Iterator]:
    # This is where you can add your custom RAG pipeline.
    # Typically, you would retrieve relevant information from your knowledge base and synthesize it to generate a response.

    print(messages)
    print(user_message)

    query_engine = self.index.as_query_engine(streaming=True)
    response = query_engine.query(user_message)

    return response.response_gen
```

[examples/pipelines/rag/llamaindex_ollama_pipeline.py](https://github.com/open-webui/pipelines/blob/c7121bd904c15954b458eb2184ba77c379936284/examples/pipelines/rag/llamaindex_ollama_pipeline.py#L62-L74) · [More projects using LlamaIndex Core →](https://dashboard.exa.ai/playground/search?q=Python%20projects%20using%20llama-index-core%20for%20research%20dialogue%2C%20retrieval-pipeline%20initialization%20and%20streamed%20document%20querying&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
import asyncio
from llama_index.core.agent.workflow import FunctionAgent
from llama_index.llms.openai import OpenAI
# Define a simple calculator tool
def multiply(a: float, b: float) -> float:
 """Useful for multiplying two numbers."""
 return a * b
# Create an agent workflow with our calculator tool
agent = FunctionAgent(
 tools= [multiply],
 llm= OpenAI(model="gpt-4o-mini"),
 system_prompt="You are a helpful assistant that can multiply two numbers.",
)
async def main():
 # Run the agent
 response = await agent.run("What is 1234 * 4567?")
 print(str(response))
# Run the agent
if __name__ == "__main__":
 asyncio.run(main())

```

From [README.md](https://developers.llamaindex.ai/python/framework/getting_started/starter_example/)

### CrewAI

[GitHub](https://github.com/crewAIInc/crewAI) · [PyPI](https://pypi.org/project/crewai) · [Docs](https://docs.crewai.com)

CrewAI is a framework for multi-agent workflows in two forms. A crew groups agents, each with a role, a goal, and tools, and assigns them a list of tasks that run in a sequential or hierarchical process. Flows are event-driven sequences of steps that combine single model calls, plain code, and crews. The `crewai` command creates a project in which agents and tasks are defined in YAML files, and `kickoff` starts a run.

- Downloads / mo: 2.6M
- Stars: 61.1K
- Last release: 1.15.41
- License: MIT
- Capabilities: [From the CrewAI docs](https://docs.crewai.com)

**Strengths**

- **Role-based crews.** Each crew assigns tasks to agents with their own roles and runs them in a set process.

```sh
pip install crewai
```

**Arindam200/awesome-ai-apps** (16.8K stars)

[Arindam200/awesome-ai-apps](https://github.com/Arindam200/awesome-ai-apps) 

```python
def build_crew(model_id: str, contract_text: str, party_perspective: str) -> Crew:
    llm = build_llm(model_id)

    extractor = Agent(
        role="Contract Clause Extractor",
        goal=(
            "Identify, label, and quote every material clause from the "
            "provided contract with precise references."
        ),
        backstory=(
            "You are a meticulous paralegal who has read thousands of "
            "commercial contracts. You never paraphrase clauses when a "
            "direct quote will do, and you never invent text that is not "
            "in the document."
        ),
        llm=llm,
        verbose=True,
        allow_delegation=False,
    )

    risk_analyst = Agent(
        role="Legal Risk Analyst",
        goal=(
            f"Score each extracted clause for risk from the perspective "
            f"of {party_perspective}, using Low / Medium / High with a "
            f"short rationale."
        ),
        backstory=(
            "You are a senior contracts attorney who specializes in "
            "protecting your client from one-sided terms, unbounded "
            "liability, and hidden operational obligations."
        ),
        llm=llm,
        verbose=True,
        allow_delegation=False,
    )

    reviewer = Agent(
        role="Senior Paralegal Reviewer",
        goal=(
            "Produce a final contract review memo summarizing clauses, "
            "risks, and redline recommendations."
        ),
        backstory=(
            "You consolidate the work of the extractor and risk analyst "
            "into a clean, executive-ready memo with clear next steps."
        ),
        llm=llm,
        verbose=True,
        allow_delegation=False,
    )

    extract_task = Task(
        description=(
            "You will receive the full text of a contract below. Extract "
            "every material clause and map it to one of these categories:\n"
            f"{chr(10).join('- ' + c for c in CLAUSE_TYPES)}\n\n"
            "For EACH clause produce:\n"
            "1. Category (from the list above, or 'Other')\n"
            "2. Section / heading reference as it appears in the contract\n"
            "3. A verbatim quote (<= 400 chars; truncate with ... if longer)\n"
            "4. A one-sentence plain-English summary\n\n"
            "Return the result as a Markdown table with columns: "
            "Category | Section | Quote | Summary.\n\n"
            "CONTRACT TEXT:\n"
            f"\"\"\"\n{contract_text}\n\"\"\""
        ),
        expected_output=(
            "A Markdown table with one row per material clause."
        ),
        agent=extractor,
    )

    risk_task = Task(
        description=(
            "Using the extracted clauses from the previous task, score "
            f"each one for risk from the perspective of {party_perspective}. "
            "Output a Markdown table with columns: "
            "Category | Risk (Low/Medium/High) | Why it matters | "
            "Suggested redline.\n\n"
            "Scoring guidance:\n"
            "- High: uncapped/broad liability, one-sided indemnity, "
            "auto-renewal without notice, IP assignment giveaways, "
            "unilateral termination rights against our client, "
            "unfavorable governing law, broad non-competes.\n"
            "- Medium: vague SLAs, ambiguous payment terms, "
            "confidentiality carve-outs, assignment without consent.\n"
            "- Low: standard boilerplate with balanced terms.\n"
            "Finish with a single 'Overall Contract Risk' line: "
            "Low / Medium / High, plus a 2-sentence justification."
        ),
        expected_output=(
            "A Markdown risk table followed by an overall risk rating."
        ),
        agent=risk_analyst,
        context=[extract_task],
    )

    review_task = Task(
        description=(
            "Write the final Contract Review Memo in Markdown with these "
            "sections:\n"
            "1. **Executive Summary** (3-5 bullets: what this contract is, "
            "key commercial terms, overall risk verdict).\n"
            "2. **Key Clauses** (table from the extractor, trimmed to the "
            "most material rows).\n"
            "3. **Risk Assessment** (table from the risk analyst).\n"
            "4. **Recommended Redlines** (numbered list of the top 5-8 "
            "changes to request, each with a one-line rationale).\n"
            "5. **Open Questions for Counsel** (bullets: anything you "
            "cannot determine from the document alone).\n\n"
            f"Client perspective: {party_perspective}.\n"
            "Never invent clauses that were not identified by the "
            "extractor. Close the memo with a disclaimer that this is "
            "an AI-generated review and not legal advice."
        ),
        expected_output="A complete Markdown review memo.",
        agent=reviewer,
        context=[extract_task, risk_task],
    )

    return Crew(
        agents=[extractor, risk_analyst, reviewer],
        tasks=[extract_task, risk_task, review_task],
        process=Process.sequential,
        verbose=True,
    )
```

[advance_ai_agents/paralegal_crew/crew.py](https://github.com/Arindam200/awesome-ai-apps/blob/147939c6022029d2ea3caf425f46539df034e372/advance_ai_agents/paralegal_crew/crew.py#L31-L157) · [More projects using CrewAI →](https://dashboard.exa.ai/playground/search?q=crewai%20GitHub%20projects)

**Quickstart**

```python
import os
from crewai import Agent, Task, Crew, Process

agent = Agent(role='Explainer', goal='Explain programming concepts', backstory='You teach concise technical lessons.', llm=os.environ['CREWAI_MODEL'])
task = Task(description='Explain a hash table.', expected_output='A short explanation.', agent=agent)
result = Crew(agents=[agent], tasks=[task], process=Process.sequential).kickoff()
print(result.raw)

```

From [crews.md](https://docs.crewai.com/en/concepts/crews)

## FAQ

### Which Python LLM library should I use?

[Instructor](#instructor) returns typed data from a single model call. [LangChain](#langchain), [Pydantic AI](#pydantic-ai-slim), [Google ADK](#google-adk), and [CrewAI](#crewai) build tool-calling agents, [LangGraph](#langgraph) runs long, stateful workflows, [LlamaIndex](#llamaindex-core) queries indexed documents, and [DSPy](#dspy) optimizes prompts against examples.

### LangChain vs LangGraph: which should I use?

LangChain builds an agent from a model, tools, and middleware with `create_agent`. LangGraph is the lower-level runtime underneath, where a workflow is a graph of nodes over shared state, with checkpoints that let a run pause for human input and resume.

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

LangChain centers on agents and a standard interface to models, tools, and vector stores. LlamaIndex centers on loading documents into indexes and querying them through retrievers and query engines, and it also builds agents and workflows.

### Pydantic AI vs LangChain: which should I use?

Pydantic AI, from the Pydantic team, runs a typed agent loop in which tools and outputs are Pydantic models and a model change is a string swap. LangChain composes agents from a model, tools, and middleware, with a separate integration package for each provider.

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

CrewAI groups agents with roles and goals into a crew that works through a list of tasks, and adds event-driven Flows for fixed steps. LangChain builds a single agent from a model and tools, and leaves multi-agent orchestration to LangGraph.

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

DSPy declares each model task as a signature of typed inputs and outputs, and its optimizers tune the prompts against examples and a scoring function. LangChain prompts and agent instructions are written by hand.

## How this page was built

Data checked Nov 19, 2026.

Reproduce it with the Exa API:

```json
{
  "endpoint": "/search",
  "body": {
    "query": "Best Python LLM libraries LangChain LlamaIndex Haystack DSPy examples",
    "numResults": 5
  }
}
```

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