Documentation for evidor v1.10.1. Published on PyPI.
GETTING STARTED

Evidor Documentation

Evidor is an open-source, provider-agnostic runtime for building AI agents. It provides a clean, modern interface for conversational agents across multiple model providers, with first-class support for stateful and stateless conversations, native context compaction, thinking flags, async-first concurrent execution, MCP, and decoupled telemetry.

Runtime Harness ArchitectureUnlike simple SDK wrappers that merely standardize request formats, Evidor acts as an operational runtime: coordinating conversational session state, delegating native context compaction to provider engines, executing concurrent async tool loops via asyncio.gather(), bridging external MCP servers, managing retry budgets, and dispatching non-blocking telemetry trace trees.

Installation

Install Evidor from PyPI with the provider adapter(s) and extras needed for your stack:

terminal
bash
1# Install provider adapters
2pip install "evidor[openai]"
3pip install "evidor[anthropic]"
4pip install "evidor[gemini]"
5
6# Install MCP and telemetry extras
7pip install "evidor[mcp]"
8pip install "evidor[otel]"
9pip install "evidor[langfuse]"
10pip install "evidor[phoenix]"
11pip install "evidor[prometheus]"
12
13# Install all adapters, tools, and telemetry dependencies
14pip install "evidor[all]"
Published on PyPI: Package is published at pypi.org/project/evidor/. Compatible with Python 3.10 through Python 3.14.

Quickstart

Create an Agent with any provider and send a message:

quickstart.py
python
1from evidor import Agent, OpenAIProvider
2
3agent = Agent(OpenAIProvider(model="gpt-4.1-mini"))
4response = agent.send("Give a one-sentence explanation of dependency inversion.")
5print(response.text)

Response objects expose response.text (assistant response string) and response.model (model identifier).

CORE ARCHITECTURE

Core Architecture: Two Execution Paradigms

Evidor cleanly separates AI execution into two distinct paradigms:

1. Stateful Conversations (Agent) — Recommended

Conversations maintain state automatically across turns—you do not have to pass the entire message history each time. Evidor manages session state, context continuation, and tool execution loops cleanly behind the scenes.

2. Stateless LLM Calls (provider.generate)

Direct single-turn or user-managed requests with tools, structured outputs, and raw message histories. Available when your application manages its own database storage and persistence.

Stateful Multi-Turn Conversations (Agent)

Use send() (or send_async()) to advance the conversation. Previous turns are remembered without re-passing the conversation history:

stateful_agent.py
python
1from evidor import Agent, OpenAIProvider
2
3# Stateful conversations maintain context across turns automatically
4agent = Agent(OpenAIProvider(model="gpt-6-astra"))
5
6agent.send("My favorite color is navy blue.")
7response = agent.send("What color did I say I like?")
8print(response.text) # "You said your favorite color is navy blue."

System Prompts

Configure an initial system prompt when creating an Agent. Evidor delivers the instructions natively across subsequent turns:

system_prompt.py
python
1from evidor import Agent, GeminiProvider
2
3agent = Agent(
4 GeminiProvider(model="gemini-3.8-flash"),
5 system_prompt="You are a concise technical writer. Avoid buzzwords and respond in bullet points.",
6)
7
8response = agent.send("How does a TCP handshake work?")
9print(response.text)

How State and Context Are Handled Under the Hood

Under the hood, Evidor transparently maps stateful conversations to each model provider's optimal context mechanism, ensuring efficient token usage without requiring you to manually re-send past messages:

ProviderStrategyArchitectureCompaction
OpenAIProvider"response_chain"Responses API previous_response_idServer-side at compact_threshold
GeminiProvider"interaction_chain"Interactions API previous_interaction_idManaged in Interactions API
AnthropicProvider"stateless_replay"Ephemeral Prompt Caching (KV-cache)Native compaction summary blocks

Native Provider Compaction (compact_threshold)

For long-running agents and multi-turn workflows, both OpenAI and Anthropic provide native compaction to summarize older context at a token threshold rather than hitting context window limits:

native_compaction.py
python
1from evidor import Agent, OpenAIProvider, AnthropicProvider
2
3# 1. OpenAI: Automatic server-side compaction
4openai_agent = Agent(
5 OpenAIProvider(model="gpt-6-astra", compact_threshold=100000)
6)
7
8# 2. Anthropic Claude: Threshold compaction with optional custom instructions
9claude_agent = Agent(
10 AnthropicProvider(
11 model="claude-3-7-sonnet-20250219",
12 compact_threshold=150000,
13 compact_instructions="Focus on preserving key architecture decisions and code snippets.",
14 )
15)
16
17# Compaction threshold can also be set directly on the Agent facade
18agent = Agent(OpenAIProvider(model="gpt-6-astra"), compact_threshold=100000)
Compaction Lifecycle:
• OpenAI: Server-side compaction creates an opaque compaction item in the response stream. In response_chain mode, passing previous_response_id carries this compaction forward seamlessly.
• Anthropic: Claude produces a native compaction block. Evidor preserves this compaction block and formats it into subsequent turns so Claude automatically drops older history.

Inspecting and Resetting State

Inspect provider identifiers, strategy, message history, or reset the conversation at any time:

inspect_state.py
python
1from evidor import Agent, OpenAIProvider
2
3agent = Agent(OpenAIProvider(model="gpt-6-astra"))
4agent.send("Hello!")
5
6# Inspect provider context strategy ('response_chain', 'interaction_chain', 'stateless_replay')
7print(agent.strategy) # "response_chain"
8
9# Inspect the latest provider response/interaction ID
10print(agent.last_response_id) # e.g. "resp_12345"
11
12# Inspect message history captured during this session
13for msg in agent.messages:
14 print(f"{msg.role}: {msg.content}")
15
16# Reset conversation state and provider response chain
17agent.reset() # or agent.clear_history()
18print(agent.last_response_id) # None
STATELESS PARADIGM

Stateless LLM Calls (provider.generate)

In the stateless paradigm, you interact directly with the underlying ModelProvider using GenerationRequest. Evidor executes the call directly against modern provider endpoints without maintaining or mutating any hidden conversation state:

stateless_calls.py
python
1from evidor import GenerationRequest, Message, OpenAIProvider
2
3provider = OpenAIProvider(model="gpt-6-astra")
4
5# Single-prompt shortcut
6response = provider.generate(GenerationRequest(prompt="Explain Raft consensus in one paragraph."))
7print(response.text)
8
9# Multi-message request
10request = GenerationRequest(
11 messages=[
12 Message(role="system", content="You are a distributed systems expert."),
13 Message(role="user", content="What is quorum?"),
14 ]
15)
16response = provider.generate(request)
17print(response.text)

User-Managed Message History

When your application handles its own persistence (e.g. database, chat storage, or custom state machine), you maintain the message list and pass it directly to provider.generate():

user_managed_history.py
python
1from evidor import GenerationRequest, Message, OpenAIProvider
2
3# In stateless mode, the user maintains history and passes it explicitly
4provider = OpenAIProvider(model="gpt-6-astra")
5chat_history: list[Message] = [
6 Message(role="system", content="You are a concise coding assistant."),
7]
8
9# Turn 1
10chat_history.append(Message(role="user", content="Recommend a fast key-value store in Go."))
11response = provider.generate(GenerationRequest(messages=chat_history))
12chat_history.append(Message(role="assistant", content=response.text))
13
14# Turn 2
15chat_history.append(Message(role="user", content="Does it support persistence?"))
16response = provider.generate(GenerationRequest(messages=chat_history))
17chat_history.append(Message(role="assistant", content=response.text))
18print(f"Assistant: {response.text}")

Stateless Tool Calling

Supply tool definitions directly in a GenerationRequest. The model emits tool calls if needed, which you can execute statelessly in your own application loop:

stateless_tools.py
python
1from evidor import GenerationRequest, Message, OpenAIProvider, Tool
2
3tool_def = Tool(
4 name="get_stock_price",
5 description="Get current price for a stock ticker.",
6 parameters={
7 "type": "object",
8 "properties": {"ticker": {"type": "string"}},
9 "required": ["ticker"],
10 },
11 func=lambda ticker: f"${ticker.upper()} is $150.00",
12)
13
14request = GenerationRequest(
15 messages=[Message(role="user", content="What is the price of AAPL?")],
16 tools=(tool_def,),
17)
18response = provider.generate(request)
19
20if response.tool_calls:
21 for call in response.tool_calls:
22 print(f"Tool call requested: {call.name} with args {call.arguments}")
STREAMING ENGINE

Streaming Responses: Unified Architecture

Evidor provides a provider-agnostic streaming interface across all supported model providers (OpenAI, Google Gemini, and Anthropic Claude). By passing stream=True, you receive an iterable stream of lightweight chunks that emit tokens in real time while maintaining 100% compatibility with conversation memory, tool execution loops, and observability.

Clean Stringification

Chunks stringify directly to their text (str(chunk) returns chunk.text), so standard printing works out of the box: print(chunk, end="", flush=True).

Silent Argument Buffering

Tool arguments stream silently behind the scenes without polluting chunk.text. When tool execution finishes, the final synthesized response streams to the caller.

Automatic State Commit

At stream completion, message history, compaction summaries, and server-side state (last_response_id) are automatically updated and persisted.

Synchronous Streaming (agent.send)

Call agent.send(prompt, stream=True) to receive an iterable stream. After consuming tokens, inspect the final accumulated response, token usage, and latency metrics:

streaming_sync.py
python
1from evidor import Agent, OpenAIProvider
2
3agent = Agent(OpenAIProvider(model="gpt-6-astra"))
4
5# Stream responses token-by-token
6stream = agent.send("Write a short haiku about debugging code.", stream=True)
7for chunk in stream:
8 print(chunk, end="", flush=True)
9
10# Access final accumulated response, token usage, and latency
11print(f"\nModel: {stream.response.model}")
12print(f"Total tokens: {stream.response.usage.total_tokens}")
13print(f"Time to first token: {stream.time_to_first_token_ms:.1f}ms")
Stream Inspection:stream.response provides the fully accumulated GenerationResponse object, including total tokens, finish reason, and model metadata.

Asynchronous Streaming (agent.send_async)

In async environments (FastAPI, Starlette, Tornado, async background workers), use await agent.send_async(..., stream=True) and iterate with async for chunk in stream::

streaming_async.py
python
1import asyncio
2from evidor import Agent, GeminiProvider
3
4async def main():
5 agent = Agent(GeminiProvider(model="gemini-3.8-flash"))
6 stream = await agent.send_async("Explain how event loops work.", stream=True)
7 async for chunk in stream:
8 print(chunk, end="", flush=True)
9
10 print(f"\nFinished with {stream.time_to_first_token_ms:.1f}ms TTFT")
11
12asyncio.run(main())

Streaming with Tools: Seamless Background Execution

When an agent needs to execute tools during a streaming turn:

1. Clean Text Output: Tool arguments stream and accumulate silently behind the scenes. chunk.text remains empty string (""), ensuring raw JSON arguments never pollute the client stream.
2. Automatic Execution: The agent detects and executes the tool function (concurrently via asyncio.gather() if multiple tools were invoked) and updates the conversation history with the tool result.
3. Follow-Up Stream: The model automatically streams its final synthesized answer as text chunks to the caller.
4. Optional UI Indicators: If you are building a user interface and want to show a loading badge or status indicator when a tool is called, inspect chunk.tool_calls:
streaming_tools.py
python
1from evidor import Agent, GeminiProvider, tool
2
3@tool
4def check_order_status(order_id: str) -> str:
5 """Look up order shipping status."""
6 return f"Order {order_id} is out for delivery."
7
8agent = Agent(GeminiProvider(model="gemini-3.8-flash"), tools=[check_order_status])
9stream = agent.send("Where is my order ORD-992?", stream=True)
10
11for chunk in stream:
12 # chunk.tool_calls contains fully validated ToolCall instances when a tool is invoked
13 if chunk.tool_calls:
14 for call in chunk.tool_calls:
15 print(f"\n[⚡ Executing tool: {call.name} with args {call.arguments}]")
16
17 # Regular text tokens (arguments accumulate silently without polluting chunk.text)
18 print(chunk, end="", flush=True)

Streaming Thinking & Reasoning Tokens

For reasoning models (OpenAI gpt-6-astra, Anthropic claude-3-7-sonnet-20250219, or Gemini gemini-3.8-flash with thinking enabled), intermediate thought tokens stream via chunk.thinking:

streaming_thinking.py
python
1from evidor import Agent, AnthropicProvider
2
3agent = Agent(AnthropicProvider(model="claude-3-7-sonnet-20250219", thinking=2048))
4stream = agent.send("Solve: Which is greater, 9.11 or 9.9?", stream=True)
5
6for chunk in stream:
7 if chunk.thinking:
8 print(f"\033[90m{chunk.thinking}\033[0m", end="", flush=True) # Dim thinking text
9 if chunk.text:
10 print(chunk.text, end="", flush=True)

Stateless Provider Streaming

Stream direct single-turn LLM calls without agent wrappers using provider.generate() or provider.generate_async():

streaming_stateless.py
python
1from evidor import GenerationRequest, OpenAIProvider
2
3provider = OpenAIProvider(model="gpt-6-astra")
4
5request = GenerationRequest(
6 prompt="Explain consensus in distributed systems.",
7 stream=True,
8)
9
10# Synchronous streaming
11stream = provider.generate(request)
12for chunk in stream:
13 print(chunk, end="", flush=True)
14
15# Asynchronous streaming
16# stream = await provider.generate_async(request)
17# async for chunk in stream:
18# print(chunk, end="", flush=True)

Context Managers & TTFT Telemetry

Streams implement context manager protocols (with / async with) for deterministic cleanup if you break out of iteration early:

streaming_cleanup.py
python
1from evidor import Agent, OpenAIProvider
2
3agent = Agent(OpenAIProvider(model="gpt-6-astra"))
4
5# Sync context manager ensures deterministic cleanup even on early break
6with agent.send("List 5 facts about space.", stream=True) as stream:
7 for chunk in stream:
8 print(chunk, end="", flush=True)
9
10# Async context manager
11# async with await agent.send_async("List 5 facts about space.", stream=True) as stream:
12# async for chunk in stream:
13# print(chunk, end="", flush=True)
14
15# Final accumulated response can also be retrieved via helper:
16# final_response = stream.get_final_response()
Time to First Token (TTFT) & Zero-Flooding Telemetry:
• time_to_first_token_ms: Measured precisely from the moment the HTTP stream request starts until the first content or thinking token arrives. Accessible on stream.time_to_first_token_ms and recorded on LLMCallEndEvent.
• is_streaming: Boolean flag set to True on LLMCallStartEvent and LLMCallEndEvent.
• Zero-Flooding Architecture: Evidor does not emit telemetry events per token. Lifecycle events are recorded at the call boundaries, preserving maximum streaming throughput without queue saturation.
• stream.get_final_response(): Retrieve the final accumulated GenerationResponse without consuming remaining chunks manually.
REASONING CAPABILITIES

Configurable Thinking & Reasoning Mode

Evidor provides first-class support for reasoning models across OpenAI (gpt-6-astra, gpt-6.1-sol), Anthropic (claude-3-7-sonnet-20250219), and Gemini (gemini-3.8-flash). Configure thinking using provider-specific typed configuration classes or intuitive shorthands:

thinking_configs.py
python
1from evidor import (
2 Agent,
3 AnthropicProvider,
4 AnthropicThinkingConfig,
5 GeminiProvider,
6 GeminiThinkingConfig,
7 OpenAIProvider,
8 OpenAIThinkingConfig,
9)
10
11# 1. OpenAI: Reasoning effort ('low', 'medium', 'high', 'xhigh', 'max')
12provider = OpenAIProvider(model="gpt-6-astra", thinking="high")
13# Or via typed config:
14provider = OpenAIProvider(model="gpt-6-astra", thinking=OpenAIThinkingConfig(effort="high"))
15
16# 2. Anthropic: Token budget or adaptive effort
17# Shorthand int (budget_tokens >= 1024; auto-bumps max_tokens if needed):
18provider = AnthropicProvider(model="claude-3-7-sonnet-20250219", thinking=4096)
19# Or via typed config:
20provider = AnthropicProvider(
21 model="claude-3-7-sonnet-20250219",
22 thinking=AnthropicThinkingConfig(budget_tokens=4096),
23)
24
25# 3. Gemini: Thinking level ('minimal', 'low', 'medium', 'high') or budget
26provider = GeminiProvider(model="gemini-3.8-flash", thinking="high")
27# Or via typed config:
28provider = GeminiProvider(
29 model="gemini-3.8-flash",
30 thinking=GeminiThinkingConfig(thinking_level="high", include_thoughts=True),
31)

Inspecting Reasoning Steps & Tokens

When thinking is enabled and the provider outputs thought tokens, the response provides both the visible text and the internal reasoning scratchpad:

inspect_thinking.py
python
1from evidor import Agent, AnthropicProvider
2
3agent = Agent(AnthropicProvider(model="claude-3-7-sonnet-20250219", thinking=2048))
4response = agent.send("Solve this logic riddle step-by-step...")
5
6# Visible text response
7print(response.text)
8
9# Model's internal reasoning scratchpad (if available)
10if response.thinking:
11 print(f"Reasoning Steps:\n{response.thinking}")
12
13# Reasoning tokens recorded in usage metadata
14if response.usage and response.usage.reasoning_tokens:
15 print(f"Reasoning tokens consumed: {response.usage.reasoning_tokens}")

Multi-Turn Tool Calling & Cryptographic Signatures

Reasoning models from Anthropic and Gemini output thought blocks alongside cryptographic signatures (such as Anthropic's signature field or Gemini's thought parts). In multi-turn tool loops, these signatures must be preserved and replayed in subsequent conversation turns to avoid API verification errors. Evidor automatically captures and replays them in agent.messages and thought_blocks without requiring any manual handling.

ASYNC EXECUTION ENGINE

Native Asynchronous Conversations (send_async)

Evidor is built on an async-first execution engine. In async environments (like FastAPI, Starlette, Tornado), use await agent.send_async(...). All async tools execute natively on the caller's event loop without thread transitions, cleanly preserving shared connection pools, locks, and contextvars:

async_agent.py
python
1import asyncio
2from evidor import Agent, OpenAIProvider, tool
3
4@tool
5async def lookup_account(account_id: str) -> dict:
6 return {"id": account_id, "status": "active"}
7
8async def main() -> None:
9 # Async-first execution engine: runs natively on caller event loop
10 async with Agent(OpenAIProvider(model="gpt-4.1-mini"), tools=[lookup_account]) as agent:
11 response = await agent.send_async("Check status for account 1234")
12 print(response.text)
13
14asyncio.run(main())

Concurrent Multi-Tool Execution (asyncio.gather)

When an LLM emits multiple tool calls in a single turn, Evidor executes them concurrently via asyncio.gather(). This significantly reduces turn latency for complex agent workflows:

concurrent_tools.py
python
1import asyncio
2from evidor import Agent, OpenAIProvider, tool
3
4@tool
5async def fetch_user(user_id: str) -> dict:
6 await asyncio.sleep(0.1)
7 return {"id": user_id, "name": "Alice"}
8
9@tool
10async def fetch_orders(user_id: str) -> list[str]:
11 await asyncio.sleep(0.1)
12 return ["order-101", "order-102"]
13
14# When the LLM emits multiple tool calls in a single turn,
15# Evidor executes them concurrently via asyncio.gather()
16async def main():
17 async with Agent(OpenAIProvider("gpt-4.1-mini"), tools=[fetch_user, fetch_orders]) as agent:
18 response = await agent.send_async("Look up user 42 and their recent orders.")
19 print(response.text)
20
21asyncio.run(main())

Persistent Connection Pooling & Daemon Loop

Synchronous agent.send() transparently bridges calls through an encapsulated background daemon event loop. This preserves underlying HTTP/2 keep-alive connection pools across conversation turns, eliminating TCP/TLS handshake latency on subsequent turns without tearing down sockets between calls:

connection_pooling.py
python
1import time
2from evidor import Agent, OpenAIProvider
3
4# Persistent connection pooling: internal daemon event loop reuses HTTP/2 connections
5agent = Agent(OpenAIProvider(model="gpt-6-astra"))
6
7# Turn 1: Establishes HTTP/2 TLS session
8agent.send("Hello, initialize session.")
9
10# Turn 2: Sockets and TLS state are preserved; 0ms handshake overhead
11agent.send("Tell me a quick tip.")
12
13# Clean shutdown
14agent.close()
Zero Handshake Overhead:Subsequent requests within an active agent session reuse active TLS sessions. When finished, call agent.close() (or use with Agent(...) as agent:) to cleanly drain connection pools and terminate the background daemon thread.

Event Loop Guards & Clean Teardown

Synchronous methods (agent.send(), agent.close(), tool.execute(), mcp.get_tools()) are protected with event loop guards. Calling them from inside an active event loop raises an explicit RuntimeError immediately rather than hanging the event loop, directing you to use await agent.send_async(), await agent.close_async(), etc.

Clean up agents and background MCP sessions asynchronously using await agent.close_async() or the async with agent: context manager.

TOOLS & FUNCTION CALLING

Defining Tools with @tool

Transform any Python function into a provider-neutral tool using the @tool decorator. Evidor automatically derives the JSON Schema for parameters from type annotations and extracts descriptions from docstrings:

define_tools.py
python
1from evidor import tool
2
3# Automatic JSON schema derivation from types & docstrings
4@tool
5def get_weather(location: str, unit: str = "celsius") -> str:
6 """Get the current weather forecast for a given location.
7
8 Args:
9 location: City and country or state, e.g. 'San Francisco, CA'.
10 unit: Temperature scale ('celsius' or 'fahrenheit').
11 """
12 return f"Weather in {location}: 22° {unit}, clear skies."
13
14# Explicit name and description overrides
15@tool(name="calc_add", description="Add two numbers together.")
16def add(a: float, b: float) -> float:
17 return a + b

Equipping Agents with Tools

Pass your tools directly into Agent(..., tools=[...]). The agent automatically executes tool calls, feeds results back as role="tool", and loops until the model generates a final response:

agent_tools.py
python
1from evidor import Agent, GeminiProvider, tool
2
3@tool
4def search_database(query: str) -> list[str]:
5 """Search internal records by keyword."""
6 return [f"Record 1 matching '{query}'", f"Record 2 matching '{query}'"]
7
8agent = Agent(
9 GeminiProvider(model="gemini-3.8-flash"),
10 tools=[search_database],
11 max_tool_iterations=10, # Maximum tool execution turns per send() (default: 10)
12)
13
14response = agent.send("Can you check our records for 'alpha project'?")
15print(response.text)

Async Tools & Timeouts

Evidor seamlessly supports asynchronous functions and execution timeouts:

async_tools.py
python
1import asyncio
2from evidor import Agent, GeminiProvider, tool
3
4# Async functions are automatically executed without blocking
5@tool(timeout=5.0) # Timeout in seconds
6async def fetch_webpage(url: str) -> str:
7 """Fetch content from a URL."""
8 await asyncio.sleep(0.1)
9 return f"Contents of {url}"
10
11# Configure an agent with a default timeout for all its tools
12agent = Agent(
13 GeminiProvider(model="gemini-3.8-flash"),
14 tools=[fetch_webpage],
15 tool_timeout=10.0, # Default tool timeout in seconds
16 max_tool_iterations=10, # Max tool turns before forcing final synthesis
17)

Manual Tool Definition

For dynamic or programmatic tools without a standard Python function signature, instantiate Tool directly:

manual_tool.py
python
1from evidor import Tool
2
3# Programmatic tool creation without standard Python function inspection
4custom_tool = Tool(
5 name="query_sql",
6 description="Run a read-only SQL query.",
7 parameters={
8 "type": "object",
9 "properties": {
10 "query": {"type": "string", "description": "SQL statement"}
11 },
12 "required": ["query"],
13 },
14 func=lambda query: f"Results for: {query}",
15 timeout=5.0,
16)
BUILT-IN TOOLKITS

Built-in Utility Tools (Calculator & Time)

Evidor includes dependency-free tools you can opt into:

builtin_tools.py
python
1from evidor import Agent, OpenAIProvider, calculator, get_current_time
2
3# Built-in zero-dependency utility tools
4agent = Agent(
5 OpenAIProvider(model="gpt-4.1-mini"),
6 tools=[calculator, get_current_time],
7)

Scoped Filesystem Tools

Create filesystem tools scoped to an existing directory for listing, searching, reading, creating, updating, and deleting files with strict boundary checks:

filesystem_tools.py
python
1from evidor import Agent, OpenAIProvider, calculator, filesystem_tools, get_current_time
2
3# Scoped filesystem tools (list, read, search, create, write, delete)
4agent = Agent(
5 OpenAIProvider(model="gpt-4.1-mini"),
6 tools=[
7 calculator,
8 get_current_time,
9 *filesystem_tools("./project", max_file_bytes=100_000, max_results=100),
10 ],
11)

Webpage Reader (read_webpage)

Let agents fetch and read clean, token-bounded text from web pages, stripping HTML boilerplate automatically:

read_webpage.py
python
1from evidor import Agent, OpenAIProvider, read_webpage, read_webpage_tool
2
3# Ready-to-use default tool (strips HTML boilerplate, bounded to 15,000 chars)
4agent = Agent(OpenAIProvider(model="gpt-4.1-mini"), tools=[read_webpage])
5
6# Or customized with explicit character and timeout limits
7custom_reader = read_webpage_tool(max_chars=8_000, timeout=10.0)

Structured Evidence Store (EvidenceStore)

Prevent context pollution and hallucinations across multi-step research or analysis tasks by equipping agents with an in-memory structured evidence store:

evidence_store.py
python
1from evidor import Agent, EvidenceStore, GeminiProvider
2
3store = EvidenceStore()
4
5# store.tools provides record_evidence, list_evidence, and compare_evidence
6agent = Agent(GeminiProvider(model="gemini-3.8-flash"), tools=[*store.tools])
7agent.send("Analyze trade-offs between PostgreSQL and SQLite and record your findings.")
8
9# Inspect structured findings in Python or format as Markdown
10print(store.to_markdown())
11for item in store.items:
12 print(f"[{item.id}] {item.topic}: {item.finding}")
MODEL CONTEXT PROTOCOL (MCP)

MCP Overview & Local Stdio Servers

Connect agents to external MCP servers (e.g. AWS Bedrock, Amazon search) over local stdio subprocesses:

mcp_quickstart.py
python
1from evidor import Agent, OpenAIProvider
2
3# Connect to external MCP server (e.g. AWS Bedrock, Amazon search)
4agent = Agent(
5 OpenAIProvider(model="gpt-4.1-mini"),
6 mcp_servers={
7 "amazon": {
8 "command": "uvx",
9 "args": ["amazon-mcp-server"],
10 "env": {"AWS_PROFILE": "default"},
11 }
12 },
13)
14
15# Tools exposed by MCP server are automatically discovered and executed
16response = agent.send("Search for Kindle Paperwhite on Amazon and summarize reviews.")
17print(response.text)
18agent.close()

Streamable HTTP & SSE Remote MCP Transports

Connect to remote hosted MCP servers using modern Streamable HTTP (streamable-http or http) or legacy SSE:

mcp_remote.py
python
1from evidor import Agent, GeminiProvider, MCPServerConfig
2
3# Connect multiple MCP servers (local stdio, Streamable HTTP, and legacy SSE)
4agent = Agent(
5 GeminiProvider(model="gemini-3.8-flash"),
6 mcp_servers=[
7 # Stdio subprocess
8 MCPServerConfig.stdio(name="amazon", command="uvx", args=["amazon-mcp-server"]),
9 # Remote Streamable HTTP server (recommended standard for hosted MCP)
10 MCPServerConfig.http(
11 name="inventory",
12 url="https://inventory.internal/mcp",
13 headers={"Authorization": "Bearer secret-token"},
14 ),
15 # Legacy SSE server
16 MCPServerConfig.sse(name="weather", url="http://localhost:8080/sse"),
17 ],
18)
19
20response = agent.send("Check warehouse stock and recommend hiking boots.")
21print(response.text)
22agent.close()

Shared MCPClient Across Agents

In FastAPI or multi-agent backends, share a single open MCPClient across agents to avoid spawning duplicate server subprocesses:

shared_mcp.py
python
1from evidor import Agent, MCPClient, OpenAIProvider
2
3# Boot a single shared MCP client across multiple agents (e.g. FastAPI backends)
4shared_mcp = MCPClient.from_file("claude_desktop_config.json")
5shared_mcp.connect()
6
7# Both agents reuse the exact same client without duplicating subprocesses:
8researcher = Agent(OpenAIProvider("gpt-4.1-mini"), mcp_client=shared_mcp)
9assistant = Agent(OpenAIProvider("gpt-4.1-mini"), mcp_client=shared_mcp)
10
11res1 = researcher.send("Search records for client ABC.")
12res2 = assistant.send("Verify credentials for client ABC.")
13shared_mcp.close()

Standalone MCPClient & Tool Composition

Use MCPClient standalone to inspect tools, retrieve resources, or mix MCP tools with standard Python tools:

standalone_mcp.py
python
1import asyncio
2from evidor import Agent, MCPClient, OpenAIProvider, tool
3
4@tool
5def internal_calculator(x: int, y: int) -> int:
6 return x * y
7
8async def main():
9 async with MCPClient({"amazon": {"command": "uvx", "args": ["amazon-mcp-server"]}}) as mcp:
10 # Retrieve all Evidor Tool objects from the MCP server
11 mcp_tools = await mcp.get_tools_async()
12
13 # Combine MCP tools with local tools
14 agent = Agent(OpenAIProvider("gpt-4.1-mini"), tools=[*mcp_tools, internal_calculator])
15 response = await agent.send_async("Calculate total price for 3 units of item B08N5WRWNW.")
16 print(response.text)
17
18asyncio.run(main())
TELEMETRY & OBSERVABILITY

Decoupled Actor Runtime & Built-in Sinks

Built on an asynchronous producer-consumer actor runtime. Event dispatch on the agent thread takes under 1 microsecond. Network transport and formatting run on a dedicated worker thread (Evidor-Telemetry-Worker). Built-in sinks require zero extra dependencies:

telemetry_setup.py
python
1from opentelemetry import trace
2from opentelemetry.sdk.trace import TracerProvider
3from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter
4from evidor import Agent, OpenAIProvider, OpenTelemetrySink
5
6provider = TracerProvider()
7provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))
8trace.set_tracer_provider(provider)
9
10# Non-blocking telemetry (<1µs latency on agent thread) via dedicated worker
11otel_sink = OpenTelemetrySink(tracer_provider=provider)
12agent = Agent(OpenAIProvider("gpt-4.1-mini"), telemetry=otel_sink)
13
14response = agent.send("Search the documentation for vector embeddings.")
15agent.close()

Observability Adapters (OTel, Langfuse, Phoenix, Prometheus)

Official ultra-compact adapters for industry-leading observability platforms:

langfuse_setup.py
python
1from evidor import Agent, OpenAIProvider, LangfuseSink
2
3# Traces agent execution, latency, and tokens to Langfuse
4langfuse_sink = LangfuseSink() # Reads credentials from environment
5agent = Agent(OpenAIProvider("gpt-4.1-mini"), telemetry=langfuse_sink)
6
7response = agent.send("Summarize the quarterly earnings report.")
8agent.close() # Flushes queues and terminates background worker

Thinking Visibility in Telemetry (capture_thinking)

Intermediate reasoning scratchpads can contain confidential information. Sinks default to capture_thinking=False, which redacts raw thought text while recording reasoning token metrics. Enable capture_thinking=True to make reasoning steps visible in trace dashboards:

capture_thinking.py
python
1from evidor import Agent, AnthropicProvider
2from evidor.telemetry import ConsoleSink, OpenTelemetrySink, PhoenixSink, LangfuseSink
3
4# Enable intermediate thinking visibility on any sink (default: capture_thinking=False)
5console_sink = ConsoleSink(capture_content=True, capture_thinking=True)
6otel_sink = OpenTelemetrySink(capture_content=True, capture_thinking=True)
7phoenix_sink = PhoenixSink(capture_content=True, capture_thinking=True)
8langfuse_sink = LangfuseSink(capture_content=True, capture_thinking=True)
9
10agent = Agent(
11 AnthropicProvider(model="claude-3-7-sonnet-20250219", thinking=2048),
12 telemetry=[console_sink, phoenix_sink],
13)
14response = agent.send("Analyze system security risks...")
15agent.close()

Privacy & PII Protection (capture_content=False)

Setting capture_content=False redacts all raw prompt text, model outputs, and tool arguments while preserving span trees, latencies, and token counts:

pii_protection.py
python
1from evidor import Agent, OpenAIProvider
2from evidor.telemetry import OpenTelemetrySink, LangfuseSink
3
4# Metadata-only mode: preserves trace trees, latency, and tokens,
5# but omits/redacts all raw prompt text, LLM outputs, and tool arguments.
6otel_sink = OpenTelemetrySink(capture_content=False)
7langfuse_sink = LangfuseSink(capture_content=False)
8
9agent = Agent(
10 OpenAIProvider("gpt-4.1-mini"),
11 telemetry=[otel_sink, langfuse_sink],
12)
13response = agent.send("Sensitive patient record or financial data...")
14agent.close()
PROVIDERS & LOW-LEVEL API

Supported Providers & Modern APIs

Evidor exclusively uses modern provider APIs with zero legacy fallbacks:

• OpenAI (OpenAIProvider): Exclusively uses OpenAI Responses API (client.responses.create) with previous_response_id chaining. Requires openai>=1.0.0.
• Gemini (GeminiProvider): Exclusively uses Google Interactions API (client.interactions.create) with previous_interaction_id chaining. Requires google-genai>=1.0.0.
• Anthropic (AnthropicProvider): Messages API with native ephemeral prompt caching (cache_control) and native threshold compaction.

Custom ModelProvider Protocol

Implement either synchronous generate(request), native asynchronous generate_async(request), or both:

custom_async_provider.py
python
1from evidor import GenerationRequest, GenerationResponse, ModelProvider
2
3class CustomAsyncProvider(ModelProvider):
4 """Implements the Evidor ModelProvider protocol with async-first support."""
5 def __init__(self, model: str = "custom-model") -> None:
6 self.model = model
7
8 def with_model(self, model: str) -> "CustomAsyncProvider":
9 return CustomAsyncProvider(model=model)
10
11 async def generate_async(self, request: GenerationRequest) -> GenerationResponse:
12 # Asynchronously call custom model backend
13 prompt_text = request.prompt
14 return GenerationResponse(text="Custom async response", model=self.model)

Optional Package Extras Summary

ExtraPurposeIncluded Packages
evidor[openai]OpenAI models (gpt-6-astra, gpt-4.1-mini)openai
evidor[anthropic]Anthropic Claude (claude-3-7-sonnet)anthropic
evidor[gemini]Google Gemini (gemini-3.8-flash)google-genai
evidor[mcp]Model Context Protocol serversmcp
evidor[otel]OpenTelemetry distributed tracingopentelemetry-api, opentelemetry-sdk
evidor[langfuse]Langfuse tracing & evaluationlangfuse
evidor[phoenix]Arize Phoenix OpenInference UIarize-phoenix-otel, openinference-semantic-conventions
evidor[prometheus]Prometheus metrics expositionprometheus-client
evidor[all]All providers, MCP, and telemetry adaptersAll optional extras
RELEASE & BUILD

PyPI Release Model

Releases are automated via GitHub Actions and use Conventional Commits to calculate the next semantic version:

fix: ... creates a patch release
feat: ... creates a minor release
BREAKING CHANGE: ... creates a major release

Local Build & Testing

Build and test the package locally:

terminal
bash
1python -m pip install -e ".[dev]"
2python -m pytest
3python -m build
4python -m twine check dist/*