100+ AI Agents, Agent Skills and RAG Apps - Free and Open Source.
Add Pydantic AI typed agentic RAG (typed answers, citations, self-refusal)
Matt Van Horn5a141cb2284f
diff --git a/README.md b/README.mdindex 2969b872..997867b0 100644--- a/README.md+++ b/README.md@@ -205,6 +205,7 @@ streamlit run travel_agent.py* [π Autonomous RAG](rag_tutorials/autonomous_rag/) - GPT-4o answers from your PDFs, falls back to web search* [π Contextual AI RAG Agent](rag_tutorials/contextualai_rag_agent/) - Managed RAG: datastore to grounded chat in minutes* [π Corrective RAG (CRAG)](rag_tutorials/corrective_rag/) - Retrieval that grades itself and retries before answering+* [π Typed Agentic RAG with Pydantic AI](rag_tutorials/agentic_typed_rag_pydanticai/) - Validated answers with exact citations, or a refusal when evidence is weak* [π Deepseek Local RAG Agent](rag_tutorials/deepseek_local_rag_agent/) - Local DeepSeek reasoning over your own documents* [π€ Gemini Agentic RAG](rag_tutorials/gemini_agentic_rag/) - Query rewriting and web fallback with Gemini Flash Thinking* [π Hybrid Search RAG (Cloud)](rag_tutorials/hybrid_search_rag/) - Keyword plus vector search feeding Claudediff --git a/rag_tutorials/agentic_typed_rag_pydanticai/.env.example b/rag_tutorials/agentic_typed_rag_pydanticai/.env.examplenew file mode 100644index 00000000..3b9a3235--- /dev/null+++ b/rag_tutorials/agentic_typed_rag_pydanticai/.env.example@@ -0,0 +1,5 @@+OPENAI_API_KEY=+ANTHROPIC_API_KEY=++# Optional Pydantic AI model override.+# RAG_MODEL=openai:gpt-5.2diff --git a/rag_tutorials/agentic_typed_rag_pydanticai/README.md b/rag_tutorials/agentic_typed_rag_pydanticai/README.mdnew file mode 100644index 00000000..a05598fa--- /dev/null+++ b/rag_tutorials/agentic_typed_rag_pydanticai/README.md@@ -0,0 +1,106 @@+# Typed Agentic RAG with Pydantic AI++This Streamlit app answers questions from uploaded PDFs or a documentation URL.+Every response is a validated `Answer` object with exact source quotes, chunk IDs,+a confidence score, and an `answered` decision. If retrieval is too weak, the app+refuses before calling the language model.++++## Features++- Pydantic AI `Agent`, `RunContext`, and dependency injection+- A typed `retrieve` tool with source metadata and cosine scores+- Pydantic models for answers, citations, and retrieval evidence+- Exact quote checks against indexed chunks after model output validation+- A deterministic refusal gate for out-of-corpus questions+- OpenAI or Anthropic answer models+- OpenAI embeddings with a local hashing fallback for Anthropic-only setups+- A session-scoped NumPy vector store with no database service++## How it works++1. `rag.py` extracts PDF or web text, splits it into overlapping chunks, embeds+ the chunks, and stores normalized vectors in memory.+2. `agent.py` injects the vector store through `RagDependencies`. The Pydantic AI+ agent must call the typed `retrieve` tool before producing an `Answer`.+3. A preflight search compares the best cosine score with the refusal threshold.+ Low scores return `answered=False` without an LLM request.+4. For an answered response, each citation must match a stored source, chunk ID,+ and verbatim quoted span. An invalid or missing citation becomes a refusal.+5. `app.py` renders the answer, confidence, citations, or refusal state.++When `OPENAI_API_KEY` is available, Auto mode uses Pydantic AI's OpenAI+`Embedder` with `text-embedding-3-small`. With only `ANTHROPIC_API_KEY`, Auto mode+uses the local hashing backend because Anthropic has no embeddings API. The local+backend is best for keyword-oriented demos. Select OpenAI embeddings for semantic+retrieval across paraphrases.++## Prerequisites++- Python 3.12 or newer+- An OpenAI API key or an Anthropic API key++## Setup++From the repository root:++```bash+cd rag_tutorials/agentic_typed_rag_pydanticai+python3 -m venv .venv+source .venv/bin/activate+pip install -r requirements.txt+cp .env.example .env+```++Add one key to `.env`:++```text+OPENAI_API_KEY=your-key+```++or:++```text+ANTHROPIC_API_KEY=your-key+```++The default answer models are `openai:gpt-5.2` and+`anthropic:claude-sonnet-4-6`. Change the model field in the sidebar or set+`RAG_MODEL` to another Pydantic AI model string.++## Run++From `rag_tutorials/agentic_typed_rag_pydanticai`:++```bash+streamlit run app.py+```++Upload one or more PDFs, optionally add a docs URL, and select **Build knowledge+base**. Ask an in-corpus question to see a cited answer. Then ask about an+unrelated topic to see the refusal state.++## Tests++The deterministic suite uses Pydantic AI's `TestModel`, so it makes no provider+requests:++```bash+python3 test_typed_rag.py+```++## Files++```text+agentic_typed_rag_pydanticai/+βββ app.py+βββ agent.py+βββ rag.py+βββ test_typed_rag.py+βββ requirements.txt+βββ .env.example+βββ assets/screenshot-placeholder.svg+```++Licensed under Apache-2.0 as part of `awesome-llm-apps`.diff --git a/rag_tutorials/agentic_typed_rag_pydanticai/agent.py b/rag_tutorials/agentic_typed_rag_pydanticai/agent.pynew file mode 100644index 00000000..ed438d65--- /dev/null+++ b/rag_tutorials/agentic_typed_rag_pydanticai/agent.py@@ -0,0 +1,243 @@+"""Pydantic AI agent, typed retrieval tool, and grounding guardrails."""++from __future__ import annotations++import os+import re+from dataclasses import dataclass+from typing import Any++from pydantic import BaseModel, Field, field_validator, model_validator+from pydantic_ai import Agent, RunContext++from rag import InMemoryVectorStore+++DEFAULT_MIN_RELEVANCE = 0.2+REFUSAL_TEXT = (+ "I do not have enough evidence in the indexed sources to answer that question."+)+DEFAULT_MODELS = {+ "openai": "openai:gpt-5.2",+ "anthropic": "anthropic:claude-sonnet-4-6",+}+++class Citation(BaseModel):+ """An exact quote that connects an answer to one stored chunk."""++ source: str = Field(description="Source document name or URL")+ chunk_id: str = Field(description="Stable identifier returned by retrieve")+ quoted_span: str = Field(description="Short verbatim quote from the chunk")++ @field_validator("source", "chunk_id", "quoted_span")+ @classmethod+ def values_must_not_be_blank(cls, value: str) -> str:+ value = value.strip()+ if not value:+ raise ValueError("citation values must not be blank")+ return value+++class Answer(BaseModel):+ """Validated output rendered by the Streamlit app."""++ text: str+ citations: list[Citation]+ confidence: float = Field(ge=0.0, le=1.0)+ answered: bool++ @field_validator("text")+ @classmethod+ def text_must_not_be_blank(cls, value: str) -> str:+ value = value.strip()+ if not value:+ raise ValueError("text must not be blank")+ return value++ @model_validator(mode="after")+ def answer_and_citations_must_agree(self) -> "Answer":+ if self.answered and not self.citations:+ raise ValueError("answered responses require at least one citation")+ if not self.answered and self.citations:+ raise ValueError("refused responses must not contain citations")+ return self++ @classmethod+ def insufficient_evidence(cls, top_score: float = 0.0) -> "Answer":+ return cls(+ text=REFUSAL_TEXT,+ citations=[],+ confidence=round(min(max(top_score, 0.0), 1.0), 3),+ answered=False,+ )+++class RetrievedChunk(BaseModel):+ """A serializable chunk returned by the retrieve tool."""++ source: str+ chunk_id: str+ text: str+ score: float = Field(ge=0.0, le=1.0)+++class RetrievalEvidence(BaseModel):+ """The typed result of one vector search."""++ query: str+ enough_evidence: bool+ top_score: float = Field(ge=0.0, le=1.0)+ chunks: list[RetrievedChunk]+++@dataclass+class RagDependencies:+ """Per-run resources injected into tools through RunContext."""++ store: InMemoryVectorStore+ min_relevance: float = DEFAULT_MIN_RELEVANCE+ top_k: int = 4+++AGENT_INSTRUCTIONS = """+You answer questions only from evidence returned by the retrieve tool.++Rules:+1. Always call retrieve before producing the final output.+2. If retrieve returns enough_evidence=false, set answered=false, use no citations,+ and say that the indexed sources do not contain enough evidence.+3. If enough evidence exists, answer only claims supported by returned chunks.+4. Every citation must copy source and chunk_id exactly from retrieve.+5. quoted_span must be a short verbatim substring of that chunk's text.+6. confidence is a number from 0 to 1. Lower it when evidence is partial.+7. Never use background knowledge to fill a gap in the sources.+""".strip()+++rag_agent: Agent[RagDependencies, Answer] = Agent(+ deps_type=RagDependencies,+ output_type=Answer,+ instructions=AGENT_INSTRUCTIONS,+ retries=2,+)+++async def retrieve_evidence(deps: RagDependencies, query: str) -> RetrievalEvidence:+ """Search dependencies and expose the relevance decision as typed data."""+ results = await deps.store.search(query, limit=deps.top_k)+ top_score = results[0].score if results else 0.0+ return RetrievalEvidence(+ query=query,+ enough_evidence=bool(results and top_score >= deps.min_relevance),+ top_score=top_score,+ chunks=[+ RetrievedChunk(+ source=result.chunk.source,+ chunk_id=result.chunk.chunk_id,+ text=result.chunk.text,+ score=result.score,+ )+ for result in results+ ],+ )+++@rag_agent.tool+async def retrieve(ctx: RunContext[RagDependencies], query: str) -> RetrievalEvidence:+ """Retrieve source chunks relevant to the user's question."""+ return await retrieve_evidence(ctx.deps, query)+++def resolve_model_name() -> str:+ """Resolve a configured Pydantic AI model from environment variables."""+ if configured := os.getenv("RAG_MODEL", "").strip():+ return configured+ if os.getenv("OPENAI_API_KEY"):+ return DEFAULT_MODELS["openai"]+ if os.getenv("ANTHROPIC_API_KEY"):+ return DEFAULT_MODELS["anthropic"]+ raise RuntimeError(+ "Set OPENAI_API_KEY or ANTHROPIC_API_KEY before asking a question"+ )+++def model_for_provider(provider: str) -> str:+ """Return a default model name for a UI provider selection."""+ normalized = provider.strip().casefold()+ try:+ return DEFAULT_MODELS[normalized]+ except KeyError as exc:+ raise ValueError(f"Unsupported provider: {provider}") from exc+++def _normalize_quote(value: str) -> str:+ return re.sub(r"\s+", " ", value).strip().casefold()+++def _valid_citations(answer: Answer, deps: RagDependencies) -> list[Citation]:+ valid = []+ for citation in answer.citations:+ chunk = deps.store.find_chunk(citation.source, citation.chunk_id)+ quoted_span = _normalize_quote(citation.quoted_span)+ if (+ chunk+ and len(quoted_span) >= 8+ and quoted_span in _normalize_quote(chunk.text)+ ):+ valid.append(citation)+ return valid+++def _used_retrieve(messages: list[Any]) -> bool:+ return any(+ getattr(part, "tool_name", None) == "retrieve"+ and getattr(part, "part_kind", None) in {"tool-call", "tool-return"}+ for message in messages+ for part in message.parts+ )+++def validate_grounded_answer(+ answer: Answer,+ deps: RagDependencies,+ preflight: RetrievalEvidence,+ *,+ used_retrieve: bool,+) -> Answer:+ """Refuse outputs that skipped retrieval or cite text outside the store."""+ if not answer.answered:+ return Answer.insufficient_evidence(preflight.top_score)+ if not used_retrieve:+ return Answer.insufficient_evidence(preflight.top_score)++ citations = _valid_citations(answer, deps)+ if not citations:+ return Answer.insufficient_evidence(preflight.top_score)+ return answer.model_copy(update={"citations": citations})+++async def answer_question(+ question: str,+ deps: RagDependencies,+ model: str | None = None,+) -> Answer:+ """Run the typed agent only after a deterministic retrieval gate."""+ question = question.strip()+ if not question:+ raise ValueError("question must not be empty")++ preflight = await retrieve_evidence(deps, question)+ if not preflight.enough_evidence:+ return Answer.insufficient_evidence(preflight.top_score)++ run_options: dict[str, Any] = {"deps": deps}+ if model is not None:+ run_options["model"] = model+ result = await rag_agent.run(question, **run_options)+ return validate_grounded_answer(+ result.output,+ deps,+ preflight,+ used_retrieve=_used_retrieve(result.all_messages()),+ )diff --git a/rag_tutorials/agentic_typed_rag_pydanticai/app.py b/rag_tutorials/agentic_typed_rag_pydanticai/app.pynew file mode 100644index 00000000..252305b3--- /dev/null+++ b/rag_tutorials/agentic_typed_rag_pydanticai/app.py@@ -0,0 +1,227 @@+"""Streamlit interface for typed, cited, self-refusing RAG."""++from __future__ import annotations++import asyncio+import os+from pathlib import PurePath++import streamlit as st+from dotenv import load_dotenv++from agent import Answer, RagDependencies, answer_question, model_for_provider+from rag import (+ HashingEmbeddingBackend,+ InMemoryVectorStore,+ OpenAIEmbeddingBackend,+ default_embedding_backend,+ fetch_url_text,+ ingest_pdf,+)+++load_dotenv()++st.set_page_config(+ page_title="Typed Agentic RAG",+ page_icon="π",+ layout="wide",+)+++def run_async(awaitable):+ """Run one async operation from Streamlit's synchronous script."""+ return asyncio.run(awaitable)+++def selected_embedding_backend(mode: str):+ if mode == "OpenAI":+ if not os.getenv("OPENAI_API_KEY"):+ raise RuntimeError("OpenAI embeddings require OPENAI_API_KEY")+ return OpenAIEmbeddingBackend()+ if mode == "Local hashing":+ return HashingEmbeddingBackend()+ return default_embedding_backend()+++async def build_knowledge_base(files, docs_url: str, embedding_mode: str):+ """Build a fresh vector store from the current source selection."""+ store = InMemoryVectorStore(selected_embedding_backend(embedding_mode))+ indexed = []++ for uploaded_file in files:+ source = PurePath(uploaded_file.name).name+ chunk_count = await ingest_pdf(store, source, uploaded_file.getvalue())+ indexed.append((source, chunk_count))++ if docs_url:+ text = fetch_url_text(docs_url)+ chunk_count = await store.add_document(docs_url, text)+ indexed.append((docs_url, chunk_count))++ return store, indexed+++def render_answer(answer: Answer) -> None:+ """Render either a grounded answer card or a clear refusal state."""+ if answer.answered:+ st.markdown(answer.text)+ st.progress(answer.confidence)+ st.caption(f"Answer confidence: {answer.confidence:.0%}")+ st.markdown("**Citations**")+ for citation in answer.citations:+ label = f"{citation.source} | {citation.chunk_id}"+ with st.expander(label):+ st.code(citation.quoted_span, language=None)+ else:+ st.warning(answer.text, icon="π")+ st.progress(answer.confidence)+ st.caption(f"Best retrieval similarity: {answer.confidence:.0%}")+++if "rag_store" not in st.session_state:+ st.session_state.rag_store = None+if "indexed_sources" not in st.session_state:+ st.session_state.indexed_sources = []+if "answer_history" not in st.session_state:+ st.session_state.answer_history = []+++with st.sidebar:+ st.header("Model settings")+ configured_model = os.getenv("RAG_MODEL", "").strip()+ prefer_anthropic = (+ configured_model.startswith("anthropic:")+ if configured_model+ else bool(os.getenv("ANTHROPIC_API_KEY")) and not os.getenv("OPENAI_API_KEY")+ )+ provider = st.selectbox(+ "Answer provider",+ ["OpenAI", "Anthropic"],+ index=1 if prefer_anthropic else 0,+ )+ key_name = "OPENAI_API_KEY" if provider == "OpenAI" else "ANTHROPIC_API_KEY"+ if os.getenv(key_name):+ st.success(f"{key_name} loaded", icon="π")+ else:+ st.warning(f"Set {key_name} in .env before asking a question.")++ configured_matches_provider = configured_model.startswith(provider.casefold())+ model_name = st.text_input(+ "Pydantic AI model",+ value=(+ configured_model+ if configured_matches_provider+ else model_for_provider(provider)+ ),+ key=f"model-name-{provider.casefold()}",+ help="Use the provider:model format accepted by Pydantic AI.",+ )+ embedding_mode = st.selectbox(+ "Embeddings",+ ["Auto", "OpenAI", "Local hashing"],+ help="Auto uses OpenAI when its key is set, otherwise a local lexical fallback.",+ )+ min_relevance = st.slider(+ "Refusal threshold",+ min_value=0.05,+ max_value=0.60,+ value=0.20,+ step=0.01,+ help="Questions below this retrieval score are refused before an LLM call.",+ )++ st.divider()+ if st.session_state.rag_store is not None:+ store = st.session_state.rag_store+ st.metric("Indexed chunks", store.count)+ st.caption(f"Embeddings: {store.embedding_backend.name}")+ if st.button("Clear knowledge base", use_container_width=True):+ st.session_state.rag_store = None+ st.session_state.indexed_sources = []+ st.session_state.answer_history = []+ st.rerun()+++st.title("π Typed Agentic RAG")+st.write(+ "Upload evidence, ask a question, and get a validated answer with exact quotes. "+ "Weak retrieval produces a refusal instead of a guess."+)++source_column, status_column = st.columns([3, 2])+with source_column:+ st.subheader("1. Add sources")+ uploaded_files = st.file_uploader(+ "PDF documents",+ type=["pdf"],+ accept_multiple_files=True,+ )+ docs_url = st.text_input(+ "Documentation URL",+ placeholder="https://example.com/docs",+ help="Optional. HTML and plain-text pages up to 2 MB are supported.",+ ).strip()+ build_clicked = st.button(+ "Build knowledge base",+ type="primary",+ disabled=not uploaded_files and not docs_url,+ )++with status_column:+ st.subheader("Index status")+ if st.session_state.indexed_sources:+ for source, chunks in st.session_state.indexed_sources:+ st.success(f"{source}: {chunks} chunks", icon="β ")+ else:+ st.info("Add at least one PDF or docs URL to begin.")++if build_clicked:+ with st.spinner("Extracting, chunking, and embedding sources..."):+ try:+ store, indexed_sources = run_async(+ build_knowledge_base(uploaded_files or [], docs_url, embedding_mode)+ )+ except Exception as exc:+ st.error(f"Could not build the knowledge base: {exc}")+ else:+ st.session_state.rag_store = store+ st.session_state.indexed_sources = indexed_sources+ st.session_state.answer_history = []+ st.rerun()++st.divider()+st.subheader("2. Ask the indexed sources")++for item in st.session_state.answer_history:+ with st.chat_message("user"):+ st.markdown(item["question"])+ with st.chat_message("assistant"):+ render_answer(Answer.model_validate(item["answer"]))++question = st.chat_input(+ "Ask a question about the indexed sources",+ disabled=st.session_state.rag_store is None,+)+if question:+ if not os.getenv(key_name):+ st.error(f"Set {key_name} before asking a question.")+ else:+ deps = RagDependencies(+ store=st.session_state.rag_store,+ min_relevance=min_relevance,+ top_k=4,+ )+ with st.spinner("Retrieving evidence and validating the answer..."):+ try:+ selected_model = model_name.strip() or model_for_provider(provider)+ answer = run_async(+ answer_question(question, deps, model=selected_model)+ )+ except Exception as exc:+ st.error(f"The agent could not answer: {exc}")+ else:+ st.session_state.answer_history.append(+ {"question": question, "answer": answer.model_dump()}+ )+ st.rerun()diff --git a/rag_tutorials/agentic_typed_rag_pydanticai/assets/screenshot-placeholder.svg b/rag_tutorials/agentic_typed_rag_pydanticai/assets/screenshot-placeholder.svgnew file mode 100644index 00000000..3468fec1--- /dev/null+++ b/rag_tutorials/agentic_typed_rag_pydanticai/assets/screenshot-placeholder.svg@@ -0,0 +1,24 @@+<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="700" viewBox="0 0 1200 700" role="img" aria-labelledby="title description">+ <title id="title">Typed Agentic RAG screenshot placeholder</title>+ <desc id="description">Placeholder showing the planned Streamlit answer and citation layout.</desc>+ <rect width="1200" height="700" fill="#f5f7fb"/>+ <rect x="40" y="40" width="1120" height="620" rx="20" fill="#ffffff" stroke="#d7dce5" stroke-width="2"/>+ <rect x="40" y="40" width="280" height="620" rx="20" fill="#eef2f8"/>+ <text x="80" y="105" fill="#172033" font-family="Arial, sans-serif" font-size="26" font-weight="700">Model settings</text>+ <rect x="80" y="140" width="200" height="46" rx="8" fill="#ffffff" stroke="#c7cfdb"/>+ <text x="98" y="170" fill="#536078" font-family="Arial, sans-serif" font-size="17">OpenAI</text>+ <rect x="80" y="215" width="200" height="46" rx="8" fill="#ffffff" stroke="#c7cfdb"/>+ <text x="98" y="245" fill="#536078" font-family="Arial, sans-serif" font-size="17">Auto embeddings</text>+ <text x="365" y="105" fill="#172033" font-family="Arial, sans-serif" font-size="34" font-weight="700">Typed Agentic RAG</text>+ <text x="365" y="145" fill="#536078" font-family="Arial, sans-serif" font-size="18">Validated answers with exact source quotes</text>+ <rect x="365" y="190" width="740" height="92" rx="12" fill="#f7f9fc" stroke="#d7dce5"/>+ <text x="392" y="225" fill="#172033" font-family="Arial, sans-serif" font-size="18" font-weight="700">Question</text>+ <text x="392" y="258" fill="#536078" font-family="Arial, sans-serif" font-size="18">How much parental leave does the handbook grant?</text>+ <rect x="365" y="310" width="740" height="190" rx="12" fill="#effaf4" stroke="#8dcda9"/>+ <text x="392" y="350" fill="#176b43" font-family="Arial, sans-serif" font-size="18" font-weight="700">Answered Β· 91% confidence</text>+ <text x="392" y="392" fill="#172033" font-family="Arial, sans-serif" font-size="19">The handbook grants twelve weeks of paid parental leave.</text>+ <rect x="392" y="425" width="680" height="50" rx="8" fill="#ffffff" stroke="#b9ddc8"/>+ <text x="412" y="457" fill="#536078" font-family="Arial, sans-serif" font-size="16">handbook.pdf | handbook.pdf:p1:c1</text>+ <rect x="365" y="530" width="740" height="72" rx="12" fill="#fff7e8" stroke="#e9be68"/>+ <text x="392" y="574" fill="#805610" font-family="Arial, sans-serif" font-size="18">Weak evidence returns a refusal instead of a guess.</text>+</svg>diff --git a/rag_tutorials/agentic_typed_rag_pydanticai/rag.py b/rag_tutorials/agentic_typed_rag_pydanticai/rag.pynew file mode 100644index 00000000..0e78bb94--- /dev/null+++ b/rag_tutorials/agentic_typed_rag_pydanticai/rag.py@@ -0,0 +1,462 @@+"""Document ingestion and a small in-memory vector store."""++from __future__ import annotations++import hashlib+import io+import ipaddress+import math+import os+import re+import socket+from dataclasses import dataclass+from html.parser import HTMLParser+from typing import Protocol, Sequence+from urllib.parse import urlparse+from urllib.request import HTTPRedirectHandler, Request, build_opener++import numpy as np+++DEFAULT_CHUNK_SIZE = 180+DEFAULT_CHUNK_OVERLAP = 30+DEFAULT_EMBEDDING_MODEL = "openai:text-embedding-3-small"+MAX_URL_BYTES = 2_000_000++_STOP_WORDS = {+ "a",+ "about",+ "after",+ "all",+ "also",+ "am",+ "an",+ "and",+ "any",+ "are",+ "as",+ "at",+ "be",+ "because",+ "been",+ "before",+ "being",+ "but",+ "by",+ "can",+ "do",+ "does",+ "for",+ "from",+ "had",+ "has",+ "have",+ "how",+ "i",+ "if",+ "in",+ "into",+ "is",+ "it",+ "its",+ "me",+ "more",+ "most",+ "my",+ "no",+ "not",+ "of",+ "on",+ "or",+ "our",+ "so",+ "than",+ "that",+ "the",+ "their",+ "then",+ "there",+ "these",+ "they",+ "this",+ "to",+ "up",+ "was",+ "we",+ "were",+ "what",+ "when",+ "where",+ "which",+ "who",+ "why",+ "will",+ "with",+ "would",+ "you",+ "your",+}+++@dataclass(frozen=True)+class DocumentChunk:+ """A source span stored in the vector index."""++ source: str+ chunk_id: str+ text: str+++@dataclass(frozen=True)+class SearchResult:+ """A chunk paired with its cosine similarity."""++ chunk: DocumentChunk+ score: float+++class EmbeddingBackend(Protocol):+ """Interface shared by hosted and local embedding backends."""++ name: str++ async def embed_documents(self, texts: Sequence[str]) -> Sequence[Sequence[float]]:+ """Embed document chunks."""++ async def embed_query(self, text: str) -> Sequence[float]:+ """Embed a search query."""+++def chunk_text(+ text: str,+ chunk_size: int = DEFAULT_CHUNK_SIZE,+ overlap: int = DEFAULT_CHUNK_OVERLAP,+) -> list[str]:+ """Split text into word windows with deterministic overlap."""+ if chunk_size <= 0:+ raise ValueError("chunk_size must be positive")+ if overlap < 0 or overlap >= chunk_size:+ raise ValueError("overlap must be non-negative and smaller than chunk_size")++ words = text.split()+ if not words:+ return []++ chunks = []+ step = chunk_size - overlap+ for start in range(0, len(words), step):+ window = words[start : start + chunk_size]+ if not window:+ break+ chunks.append(" ".join(window))+ if start + chunk_size >= len(words):+ break+ return chunks+++def _document_chunks(+ source: str,+ text: str,+ *,+ locator: str | None,+ chunk_size: int,+ overlap: int,+) -> list[DocumentChunk]:+ texts = chunk_text(text, chunk_size=chunk_size, overlap=overlap)+ prefix = f"{source}:{locator}" if locator else source+ return [+ DocumentChunk(source=source, chunk_id=f"{prefix}:c{index}", text=value)+ for index, value in enumerate(texts, start=1)+ ]+++def _stem(token: str) -> str:+ for suffix in ("ingly", "edly", "ing", "ed", "es", "s"):+ if token.endswith(suffix) and len(token) > len(suffix) + 3:+ return token[: -len(suffix)]+ return token+++def _terms(text: str) -> list[str]:+ tokens = [+ _stem(token)+ for token in re.findall(r"[a-z0-9]+", text.casefold())+ if token not in _STOP_WORDS+ ]+ bigrams = [f"{left}:{right}" for left, right in zip(tokens, tokens[1:])]+ return tokens + bigrams+++class HashingEmbeddingBackend:+ """Offline fallback that maps normalized terms into a fixed vector."""++ def __init__(self, dimensions: int = 768):+ if dimensions < 64:+ raise ValueError("dimensions must be at least 64")+ self.dimensions = dimensions+ self.name = f"local-hashing-{dimensions}"++ def _embed(self, text: str) -> list[float]:+ vector = [0.0] * self.dimensions+ for term in _terms(text):+ digest = hashlib.blake2b(term.encode("utf-8"), digest_size=8).digest()+ position = int.from_bytes(digest, "big") % self.dimensions+ sign = 1.0 if digest[0] & 1 else -1.0+ vector[position] += sign++ norm = math.sqrt(sum(value * value for value in vector))+ if norm:+ vector = [value / norm for value in vector]+ return vector++ async def embed_documents(self, texts: Sequence[str]) -> list[list[float]]:+ return [self._embed(text) for text in texts]++ async def embed_query(self, text: str) -> list[float]:+ return self._embed(text)+++class OpenAIEmbeddingBackend:+ """OpenAI embeddings through Pydantic AI's typed Embedder client."""++ def __init__(self, model: str = DEFAULT_EMBEDDING_MODEL):+ self.name = model++ def _embedder(self):+ from pydantic_ai import Embedder++ return Embedder(self.name)++ async def embed_documents(self, texts: Sequence[str]) -> Sequence[Sequence[float]]:+ result = await self._embedder().embed_documents(list(texts))+ return result.embeddings++ async def embed_query(self, text: str) -> Sequence[float]:+ result = await self._embedder().embed_query(text)+ return result.embeddings[0]+++def default_embedding_backend() -> EmbeddingBackend:+ """Use hosted embeddings when possible, otherwise stay fully local."""+ if os.getenv("OPENAI_API_KEY"):+ return OpenAIEmbeddingBackend()+ return HashingEmbeddingBackend()+++class InMemoryVectorStore:+ """A NumPy cosine index intended for small, session-scoped corpora."""++ def __init__(self, embedding_backend: EmbeddingBackend):+ self.embedding_backend = embedding_backend+ self._chunks: list[DocumentChunk] = []+ self._vectors: np.ndarray | None = None++ @property+ def chunks(self) -> tuple[DocumentChunk, ...]:+ return tuple(self._chunks)++ @property+ def count(self) -> int:+ return len(self._chunks)++ @property+ def sources(self) -> tuple[str, ...]:+ return tuple(dict.fromkeys(chunk.source for chunk in self._chunks))++ def clear(self) -> None:+ self._chunks.clear()+ self._vectors = None++ async def add_document(+ self,+ source: str,+ text: str,+ *,+ locator: str | None = None,+ chunk_size: int = DEFAULT_CHUNK_SIZE,+ overlap: int = DEFAULT_CHUNK_OVERLAP,+ ) -> int:+ """Chunk, embed, and append one document to the index."""+ source = source.strip()+ if not source:+ raise ValueError("source must not be empty")++ chunks = _document_chunks(+ source,+ text,+ locator=locator,+ chunk_size=chunk_size,+ overlap=overlap,+ )+ return await self.add_chunks(chunks)++ async def add_chunks(self, chunks: Sequence[DocumentChunk]) -> int:+ """Embed and append prepared chunks in one provider request."""+ if not chunks:+ return 0++ texts = [chunk.text for chunk in chunks]+ vectors = np.asarray(+ await self.embedding_backend.embed_documents(texts), dtype=np.float32+ )+ if vectors.ndim != 2 or vectors.shape[0] != len(chunks):+ raise ValueError("embedding backend returned an unexpected shape")+ vectors = _normalize_rows(vectors)++ if self._vectors is not None and self._vectors.shape[1] != vectors.shape[1]:+ raise ValueError("embedding dimensions changed within one index")++ self._chunks.extend(chunks)+ self._vectors = (+ vectors if self._vectors is None else np.vstack((self._vectors, vectors))+ )+ return len(chunks)++ async def search(self, query: str, limit: int = 4) -> list[SearchResult]:+ """Return the nearest chunks ordered by cosine similarity."""+ if not query.strip() or limit <= 0 or self._vectors is None:+ return []++ query_vector = np.asarray(+ await self.embedding_backend.embed_query(query), dtype=np.float32+ )+ if query_vector.ndim != 1 or query_vector.shape[0] != self._vectors.shape[1]:+ raise ValueError("query embedding dimensions do not match the index")++ norm = float(np.linalg.norm(query_vector))+ if not norm:+ scores = np.zeros(len(self._chunks), dtype=np.float32)+ else:+ scores = self._vectors @ (query_vector / norm)+ order = np.argsort(scores)[::-1][:limit]+ return [+ SearchResult(+ chunk=self._chunks[int(index)],+ score=round(float(np.clip(scores[index], 0.0, 1.0)), 4),+ )+ for index in order+ ]++ def find_chunk(self, source: str, chunk_id: str) -> DocumentChunk | None:+ for chunk in self._chunks:+ if chunk.source == source and chunk.chunk_id == chunk_id:+ return chunk+ return None+++def _normalize_rows(vectors: np.ndarray) -> np.ndarray:+ norms = np.linalg.norm(vectors, axis=1, keepdims=True)+ return np.divide(vectors, norms, out=np.zeros_like(vectors), where=norms != 0)+++def extract_pdf_pages(data: bytes) -> list[str]:+ """Extract text page by page from a PDF byte string."""+ from pypdf import PdfReader++ reader = PdfReader(io.BytesIO(data))+ return [(page.extract_text() or "").strip() for page in reader.pages]+++async def ingest_pdf(store: InMemoryVectorStore, source: str, data: bytes) -> int:+ """Extract and index all text-bearing pages from a PDF."""+ pages = extract_pdf_pages(data)+ chunks = []+ for page_number, text in enumerate(pages, start=1):+ if text:+ chunks.extend(+ _document_chunks(+ source,+ text,+ locator=f"p{page_number}",+ chunk_size=DEFAULT_CHUNK_SIZE,+ overlap=DEFAULT_CHUNK_OVERLAP,+ )+ )+ if not chunks:+ raise ValueError(f"No extractable text found in {source}")+ return await store.add_chunks(chunks)+++class _ReadableHTMLParser(HTMLParser):+ def __init__(self):+ super().__init__(convert_charrefs=True)+ self.parts: list[str] = []+ self._ignored_depth = 0++ def handle_starttag(self, tag: str, attrs) -> None:+ if tag in {"script", "style", "noscript"}:+ self._ignored_depth += 1+ elif tag in {"br", "p", "div", "article", "section", "li", "h1", "h2", "h3"}:+ self.parts.append("\n")++ def handle_endtag(self, tag: str) -> None:+ if tag in {"script", "style", "noscript"} and self._ignored_depth:+ self._ignored_depth -= 1+ elif tag in {"p", "div", "article", "section", "li", "h1", "h2", "h3"}:+ self.parts.append("\n")++ def handle_data(self, data: str) -> None:+ if not self._ignored_depth:+ self.parts.append(data)+++def html_to_text(html: str) -> str:+ """Reduce HTML to readable text without third-party parsers."""+ parser = _ReadableHTMLParser()+ parser.feed(html)+ lines = [" ".join(line.split()) for line in "".join(parser.parts).splitlines()]+ return "\n".join(line for line in lines if line)+++def validate_public_url(url: str) -> None:+ """Reject malformed URLs and hosts that resolve outside the public internet."""+ parsed = urlparse(url)+ if parsed.scheme not in {"http", "https"} or not parsed.hostname:+ raise ValueError("URL must use http or https")+ if parsed.username or parsed.password:+ raise ValueError("URL credentials are not supported")++ hostname = parsed.hostname.rstrip(".").casefold()+ if hostname == "localhost":+ raise ValueError("Private or local URLs are not supported")++ try:+ addresses = {ipaddress.ip_address(hostname)}+ except ValueError:+ try:+ answers = socket.getaddrinfo(hostname, parsed.port, type=socket.SOCK_STREAM)+ except socket.gaierror as exc:+ raise ValueError(f"Could not resolve URL host: {hostname}") from exc+ addresses = {+ ipaddress.ip_address(answer[4][0].split("%", 1)[0]) for answer in answers+ }++ if not addresses or any(not address.is_global for address in addresses):+ raise ValueError("Private or local URLs are not supported")+++class _PublicRedirectHandler(HTTPRedirectHandler):+ def redirect_request(self, req, fp, code, msg, headers, newurl):+ validate_public_url(newurl)+ return super().redirect_request(req, fp, code, msg, headers, newurl)+++def fetch_url_text(url: str) -> str:+ """Fetch a bounded HTTP document and return readable text."""+ validate_public_url(url)+ request = Request(url, headers={"User-Agent": "typed-rag-demo/1.0"})+ opener = build_opener(_PublicRedirectHandler())+ with opener.open(request, timeout=15) as response:+ content_type = response.headers.get_content_type()+ if content_type not in {"text/html", "text/plain"}:+ raise ValueError(f"Unsupported URL content type: {content_type}")+ body = response.read(MAX_URL_BYTES + 1)+ if len(body) > MAX_URL_BYTES:+ raise ValueError("URL content is larger than 2 MB")+ charset = response.headers.get_content_charset() or "utf-8"++ decoded = body.decode(charset, errors="replace")+ text = html_to_text(decoded) if content_type == "text/html" else decoded.strip()+ if not text:+ raise ValueError("No readable text found at URL")+ return textdiff --git a/rag_tutorials/agentic_typed_rag_pydanticai/requirements.txt b/rag_tutorials/agentic_typed_rag_pydanticai/requirements.txtnew file mode 100644index 00000000..e3d45f1b--- /dev/null+++ b/rag_tutorials/agentic_typed_rag_pydanticai/requirements.txt@@ -0,0 +1,7 @@+anthropic==0.116.0+numpy==2.5.1+openai==2.45.0+pydantic-ai==2.10.0+pypdf==6.14.2+python-dotenv==1.2.2+streamlit==1.59.2diff --git a/rag_tutorials/agentic_typed_rag_pydanticai/test_typed_rag.py b/rag_tutorials/agentic_typed_rag_pydanticai/test_typed_rag.pynew file mode 100644index 00000000..20f9ff4a--- /dev/null+++ b/rag_tutorials/agentic_typed_rag_pydanticai/test_typed_rag.py@@ -0,0 +1,293 @@+#!/usr/bin/env python3+"""Deterministic tests for the typed agentic RAG example."""++import asyncio+import os+import unittest+from unittest.mock import patch++from rag import (+ HashingEmbeddingBackend,+ InMemoryVectorStore,+ chunk_text,+ html_to_text,+ ingest_pdf,+ validate_public_url,+)+from agent import (+ Answer,+ Citation,+ RagDependencies,+ answer_question,+ rag_agent,+ resolve_model_name,+ retrieve_evidence,+)+++class TypedRagTests(unittest.TestCase):+ def run_async(self, awaitable):+ return asyncio.run(awaitable)++ def make_store(self):+ return InMemoryVectorStore(HashingEmbeddingBackend(dimensions=512))++ def make_pdf(self, text):+ escaped = text.replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)")+ content = f"BT /F1 12 Tf 72 100 Td ({escaped}) Tj ET".encode("ascii")+ objects = [+ b"<< /Type /Catalog /Pages 2 0 R >>",+ b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>",+ (+ b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 300 200] "+ b"/Resources << /Font << /F1 5 0 R >> >> /Contents 4 0 R >>"+ ),+ b"<< /Length %d >>\nstream\n" % len(content) + content + b"\nendstream",+ b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>",+ ]+ payload = b"%PDF-1.4\n"+ offsets = [0]+ for number, value in enumerate(objects, start=1):+ offsets.append(len(payload))+ payload += b"%d 0 obj\n" % number + value + b"\nendobj\n"+ xref_offset = len(payload)+ payload += b"xref\n0 6\n0000000000 65535 f \n"+ payload += b"".join(b"%010d 00000 n \n" % offset for offset in offsets[1:])+ payload += b"trailer\n<< /Size 6 /Root 1 0 R >>\nstartxref\n"+ return payload + str(xref_offset).encode("ascii") + b"\n%%EOF\n"++ def test_chunk_text_uses_stable_overlap(self):+ text = " ".join(f"word{number}" for number in range(24))+ chunks = chunk_text(text, chunk_size=10, overlap=2)++ self.assertEqual(3, len(chunks))+ self.assertEqual(chunks[0].split()[-2:], chunks[1].split()[:2])+ self.assertEqual(chunks[1].split()[-2:], chunks[2].split()[:2])++ def test_local_store_ranks_relevant_evidence(self):+ store = self.make_store()+ self.run_async(+ store.add_document(+ "handbook.pdf",+ "Employees receive twelve weeks of paid parental leave after six months of service.",+ )+ )+ self.run_async(+ store.add_document(+ "astronomy.pdf",+ "Europa is an icy moon of Jupiter with a subsurface ocean.",+ )+ )++ relevant = self.run_async(+ store.search("How much parental leave do employees receive?")+ )+ unrelated = self.run_async(+ store.search("What is the production database password?")+ )++ self.assertEqual("handbook.pdf", relevant[0].chunk.source)+ self.assertGreater(relevant[0].score, 0.2)+ self.assertLess(unrelated[0].score, 0.2)++ def test_retrieve_evidence_reports_threshold_decision(self):+ store = self.make_store()+ self.run_async(+ store.add_document(+ "policy.pdf",+ "Expense reports must be submitted within thirty days of travel.",+ )+ )+ deps = RagDependencies(store=store, min_relevance=0.2, top_k=3)++ grounded = self.run_async(+ retrieve_evidence(deps, "When are expense reports due?")+ )+ missing = self.run_async(retrieve_evidence(deps, "Who won the 1978 World Cup?"))++ self.assertTrue(grounded.enough_evidence)+ self.assertFalse(missing.enough_evidence)+ self.assertEqual("policy.pdf", grounded.chunks[0].source)++ def test_pdf_text_is_extracted_and_indexed(self):+ store = self.make_store()+ added = self.run_async(+ ingest_pdf(+ store,+ "policy.pdf",+ self.make_pdf("Travel receipts are required within thirty days."),+ )+ )+ results = self.run_async(store.search("When are travel receipts required?"))++ self.assertEqual(1, added)+ self.assertEqual("policy.pdf:p1:c1", results[0].chunk.chunk_id)+ self.assertGreater(results[0].score, 0.2)++ def test_answer_model_requires_citations_when_answered(self):+ from pydantic import ValidationError++ with self.assertRaises(ValidationError):+ Answer(text="Unsupported", citations=[], confidence=0.8, answered=True)++ with self.assertRaises(ValidationError):+ Answer(+ text="Too confident",+ citations=[Citation(source="x", chunk_id="x:c1", quoted_span="quote")],+ confidence=1.2,+ answered=True,+ )++ def test_out_of_corpus_question_refuses_without_model_request(self):+ from pydantic_ai import models++ store = self.make_store()+ self.run_async(+ store.add_document(+ "benefits.pdf",+ "Dental coverage begins on the first day of employment.",+ )+ )+ deps = RagDependencies(store=store, min_relevance=0.2, top_k=3)+ previous = models.ALLOW_MODEL_REQUESTS+ models.ALLOW_MODEL_REQUESTS = False+ try:+ answer = self.run_async(+ answer_question("How do I configure a Kubernetes ingress?", deps)+ )+ finally:+ models.ALLOW_MODEL_REQUESTS = previous++ self.assertFalse(answer.answered)+ self.assertEqual([], answer.citations)+ self.assertIn("enough evidence", answer.text.lower())++ def test_agent_calls_retrieve_and_returns_typed_cited_answer(self):+ from pydantic_ai import capture_run_messages, models+ from pydantic_ai.models.test import TestModel++ store = self.make_store()+ self.run_async(+ store.add_document(+ "atlas-handbook.pdf",+ "The Atlas handbook grants twelve weeks of paid parental leave.",+ )+ )+ chunk = store.chunks[0]+ deps = RagDependencies(store=store, min_relevance=0.2, top_k=3)+ model = TestModel(+ call_tools=["retrieve"],+ custom_output_args={+ "text": "Atlas grants twelve weeks of paid parental leave.",+ "citations": [+ {+ "source": chunk.source,+ "chunk_id": chunk.chunk_id,+ "quoted_span": "twelve weeks of paid parental leave",+ }+ ],+ "confidence": 0.91,+ "answered": True,+ },+ )+ previous = models.ALLOW_MODEL_REQUESTS+ models.ALLOW_MODEL_REQUESTS = False+ try:+ with capture_run_messages() as messages:+ with rag_agent.override(model=model):+ answer = self.run_async(+ answer_question(+ "How much parental leave does Atlas grant?", deps+ )+ )+ finally:+ models.ALLOW_MODEL_REQUESTS = previous++ tool_names = [+ getattr(part, "tool_name", "")+ for message in messages+ for part in message.parts+ ]+ self.assertIsInstance(answer, Answer)+ self.assertTrue(answer.answered)+ self.assertEqual("atlas-handbook.pdf", answer.citations[0].source)+ self.assertIn("retrieve", tool_names)++ def test_forged_citation_forces_refusal(self):+ from pydantic_ai import models+ from pydantic_ai.models.test import TestModel++ store = self.make_store()+ self.run_async(+ store.add_document(+ "travel.pdf",+ "The meal allowance is seventy dollars per day.",+ )+ )+ chunk = store.chunks[0]+ deps = RagDependencies(store=store, min_relevance=0.2, top_k=3)+ model = TestModel(+ call_tools=["retrieve"],+ custom_output_args={+ "text": "The allowance is one hundred dollars.",+ "citations": [+ {+ "source": chunk.source,+ "chunk_id": chunk.chunk_id,+ "quoted_span": "one hundred dollars per day",+ }+ ],+ "confidence": 0.95,+ "answered": True,+ },+ )+ previous = models.ALLOW_MODEL_REQUESTS+ models.ALLOW_MODEL_REQUESTS = False+ try:+ with rag_agent.override(model=model):+ answer = self.run_async(+ answer_question("What is the daily meal allowance?", deps)+ )+ finally:+ models.ALLOW_MODEL_REQUESTS = previous++ self.assertFalse(answer.answered)+ self.assertEqual([], answer.citations)++ def test_model_resolution_supports_both_providers(self):+ with patch.dict(os.environ, {"OPENAI_API_KEY": "key"}, clear=True):+ self.assertEqual("openai:gpt-5.2", resolve_model_name())+ with patch.dict(os.environ, {"ANTHROPIC_API_KEY": "key"}, clear=True):+ self.assertEqual("anthropic:claude-sonnet-4-6", resolve_model_name())+ with patch.dict(os.environ, {"RAG_MODEL": "anthropic:custom"}, clear=True):+ self.assertEqual("anthropic:custom", resolve_model_name())++ def test_html_to_text_ignores_scripts_and_styles(self):+ html = """+ <html><head><style>.hidden { display: none; }</style></head>+ <body><h1>Policy</h1><p>Travel receipts are required.</p>+ <script>window.secret = 'ignore';</script></body></html>+ """+ text = html_to_text(html)++ self.assertIn("Policy", text)+ self.assertIn("Travel receipts are required.", text)+ self.assertNotIn("window.secret", text)+ self.assertNotIn("display: none", text)++ def test_private_docs_urls_are_rejected(self):+ private_urls = (+ "http://localhost/docs",+ "http://127.0.0.1/admin",+ "http://[::1]/admin",+ "http://169.254.169.254/latest/meta-data",+ "http://10.0.0.4/internal",+ )+ for url in private_urls:+ with self.subTest(url=url):+ with self.assertRaises(ValueError):+ validate_public_url(url)+++if __name__ == "__main__":+ unittest.main(verbosity=2)