Polski

Article · AI in Python · RAG

AI in Python: Anthropic SDK, Pydantic, LangChain, LlamaIndex and FastAPI in practice

A map of the richest AI ecosystem – when the provider SDK with Pydantic is enough and when LangChain or LlamaIndex pay off – plus streaming, tools, RAG with sentence-transformers and Qdrant, an MCP server and a FastAPI endpoint with tests.

By · · 18 min read

Python is the home of machine learning, so it is no surprise that most AI libraries are born there: official provider SDKs, LangChain and LangGraph, LlamaIndex, PydanticAI, sentence-transformers, clients for every vector database. That abundance has a price – it is easy to build a prototype out of six layers of abstraction that nobody can debug. This guide shows how to take only what you need from the ecosystem and how to move code from a notebook into a production service.

1
Pydantic model – describes the response structure, tool arguments and the API contract
3
levels of abstraction – provider SDK, frameworks (LangChain, LlamaIndex), agents (LangGraph)
0
blocking calls in async endpoints – use AsyncAnthropic in FastAPI

The problem: a notebook that went to production

The data team at Halina's Pierogi built an assistant in Jupyter that answers questions about the menu and orders. The demo impressed the board, so the code was moved into a FastAPI service almost unchanged. A week later:

  • an async endpoint called the synchronous client, so one long question blocked the event loop and every other request waited,
  • pip install without pinned versions upgraded an integration library and the application stopped starting,
  • a chain of six framework calls returned text that was parsed with regular expressions,
  • there was not a single test – every run called the real model and cost money.

None of these problems comes from Python. They come from not deciding which layer of the ecosystem to use and how to wrap it in production code.

Ecosystem map

LayerLibrariesWhat for
Provider SDKsanthropic, openaithe full API: streaming, messages.parse, tool runner, prompt caching, batch, files
Data structurespydanticresponse and tool schemas, validation, FastAPI contracts
LLM application frameworkslangchain + langchain-anthropic, llama-indexagents, integrations (loaders, vector stores), ready-made RAG pipelines
Agents and flowslanggraph, pydantic-aiflows as stateful graphs, checkpoints, human-in-the-loop
Embeddings and vectorssentence-transformers, qdrant-client, pgvector, chromadblocal embeddings, vector search – see embeddings and vector databases
Local modelsollama, vllm, transformersopen models on your own hardware – see local LLMs
ProtocolmcpMCP servers and clients
Evaluation and observabilitypytest, promptfoo, Langfuse, OpenTelemetrytests, evals, tracking cost and latency

pypi: anthropic

pypi: pydantic

Before you reach for a framework, answer a few questions:

Diagram: Provider SDK or framework? Start with the simplest layer that solves the problem

How this ecosystem grew

Most libraries on the map appeared within a few years and still change quickly. That is good news – the problems of 2023 (parsing responses, hand-written tool loops) have ready-made solutions in the SDKs today. And bad news – tutorials from a year ago often show APIs that no longer exist.

That is why the code in this article targets the versions current in November 2026: anthropic 2.x, langchain 1.x, llama-index-core 0.14, mcp 2.x, sentence-transformers 6.x. Before you copy an example from the internet, check which version it was written for.

  1. 2019 Transformers and Sentence-BERT – Hugging Face organizes models in the transformers library; the Sentence-BERT paper starts sentence-transformers.
  2. 2022 LangChain and GPT Index – Harrison Chase releases LangChain, Jerry Liu releases GPT Index, later LlamaIndex.
  3. 2023 Provider SDKs – official Python SDKs become the default way to call models.
  4. 2024 LangGraph, MCP, PydanticAI – agent flows as graphs, the MCP protocol with a Python SDK and Pydantic-style agents.
  5. 2025 LangChain 1.0 – a stable API with create_agent built on LangGraph.
  6. 2026 mcp 2.0 and anthropic 2.0 – July and October: new major SDK versions – and integrations that have to keep up.

The provider SDK: streaming and structured responses

The official SDK gives you two things almost every feature needs: streaming (messages.stream) and structured responses (messages.parse). The latter takes a Pydantic class, sends its schema as the response format and returns the result as a validated object in parsed_output. No more regular expressions over "2x ruskie and one cabbage".

Streaming and order extraction with Pydantic

stream_chat.py
import anthropic

client = anthropic.Anthropic()  # reads ANTHROPIC_API_KEY from the environment

SYSTEM = "You are the support assistant of Halina's Pierogi. Answer briefly and politely."


def ask(question: str) -> str:
    with client.messages.stream(
        model="claude-opus-5-5",
        max_tokens=64000,
        output_config={"effort": "low"},  # FAQ answers need little reasoning
        system=SYSTEM,
        messages=[{"role": "user", "content": question}],
    ) as stream:
        for text in stream.text_stream:  # print tokens as they arrive
            print(text, end="", flush=True)
        final = stream.get_final_message()

    print(f"\n[{final.stop_reason}] in={final.usage.input_tokens} out={final.usage.output_tokens}")
    return "".join(b.text for b in final.content if b.type == "text")


if __name__ == "__main__":
    ask("How long do you cook frozen pierogi?")
extract_order.py
from typing import Literal

import anthropic
from pydantic import BaseModel, Field

client = anthropic.Anthropic()


class OrderLine(BaseModel):
    dish: Literal["ruskie", "cabbage", "meat", "spinach"]
    quantity: int = Field(ge=1, le=20)


class OrderDraft(BaseModel):
    lines: list[OrderLine]
    pickup_time: str | None = Field(description="HH:MM, or null when not given")
    notes: str | None


def extract(text: str) -> OrderDraft:
    # parse() sends the Pydantic schema as a structured-output format
    # and validates the JSON the model returns.
    response = client.messages.parse(
        model="claude-opus-5-5",
        max_tokens=16000,
        system="Turn the customer's message into an order draft. Do not invent dishes.",
        messages=[{"role": "user", "content": text}],
        output_format=OrderDraft,
    )
    if response.stop_reason != "end_turn":
        raise RuntimeError(f"Unexpected stop reason: {response.stop_reason}")
    return response.parsed_output


if __name__ == "__main__":
    draft = extract("2x ruskie and one cabbage for 18:30, no onion please")
    print(draft.model_dump_json(indent=2))

A few details that are easy to miss:

  • Not every Pydantic constraint reaches the model. Structured outputs support a subset of JSON Schema; the SDK moves unsupported constraints (such as ge/le on numbers) into the field description and checks them client-side during validation. Handle validation errors like any other error.
  • Describe optional fields as str | None without a default when the model should always return them (even as null) – the schema is then unambiguous.
  • Check stop_reason. A response cut off by max_tokens will not validate; it is better to react explicitly than to catch a parser exception.
  • effort instead of temperature. Current Claude models do not accept sampling parameters; you set reasoning depth in output_config. Explained in LLM fundamentals.

Tools: the tool runner with a decorator

You can write the tool use loop by hand, but the Python SDK has a tool runner (in beta): the @beta_tool decorator builds the tool schema from the function signature and docstring, and the runner calls the tools and sends results back to the model until it is done. The docstring is part of the contract here – it is how the model learns when to use the tool.

The rest of this article is for members

Create a free account or sign in to read it all. Still ahead:

  • RAG: sentence-transformers, Qdrant and Claude
  • Frameworks: LangChain and LlamaIndex
  • MCP: share your tools with other applications
  • Production: FastAPI, an SSE stream and tests without the API
  • SDK or framework?
  • Checklist
  • Test yourself
  • What's next

Create a free account · Sign in