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.
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:
1# Install provider adapters2pip install "evidor[openai]"3pip install "evidor[anthropic]"4pip install "evidor[gemini]"56# Install MCP and telemetry extras7pip install "evidor[mcp]"8pip install "evidor[otel]"9pip install "evidor[langfuse]"10pip install "evidor[phoenix]"11pip install "evidor[prometheus]"1213# Install all adapters, tools, and telemetry dependencies14pip install "evidor[all]"
Quickstart
Create an Agent with any provider and send a message:
1from evidor import Agent, OpenAIProvider23agent = 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: Two Execution Paradigms
Evidor cleanly separates AI execution into two distinct paradigms:
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.
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:
1from evidor import Agent, OpenAIProvider23# Stateful conversations maintain context across turns automatically4agent = Agent(OpenAIProvider(model="gpt-6-astra"))56agent.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:
1from evidor import Agent, GeminiProvider23agent = 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)78response = 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:
| Provider | Strategy | Architecture | Compaction |
|---|---|---|---|
| OpenAIProvider | "response_chain" | Responses API previous_response_id | Server-side at compact_threshold |
| GeminiProvider | "interaction_chain" | Interactions API previous_interaction_id | Managed 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:
1from evidor import Agent, OpenAIProvider, AnthropicProvider23# 1. OpenAI: Automatic server-side compaction4openai_agent = Agent(5 OpenAIProvider(model="gpt-6-astra", compact_threshold=100000)6)78# 2. Anthropic Claude: Threshold compaction with optional custom instructions9claude_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)1617# Compaction threshold can also be set directly on the Agent facade18agent = Agent(OpenAIProvider(model="gpt-6-astra"), compact_threshold=100000)
response_chain mode, passing previous_response_id carries this compaction forward seamlessly.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:
1from evidor import Agent, OpenAIProvider23agent = Agent(OpenAIProvider(model="gpt-6-astra"))4agent.send("Hello!")56# Inspect provider context strategy ('response_chain', 'interaction_chain', 'stateless_replay')7print(agent.strategy) # "response_chain"89# Inspect the latest provider response/interaction ID10print(agent.last_response_id) # e.g. "resp_12345"1112# Inspect message history captured during this session13for msg in agent.messages:14 print(f"{msg.role}: {msg.content}")1516# Reset conversation state and provider response chain17agent.reset() # or agent.clear_history()18print(agent.last_response_id) # None
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:
1from evidor import GenerationRequest, Message, OpenAIProvider23provider = OpenAIProvider(model="gpt-6-astra")45# Single-prompt shortcut6response = provider.generate(GenerationRequest(prompt="Explain Raft consensus in one paragraph."))7print(response.text)89# Multi-message request10request = 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():
1from evidor import GenerationRequest, Message, OpenAIProvider23# In stateless mode, the user maintains history and passes it explicitly4provider = OpenAIProvider(model="gpt-6-astra")5chat_history: list[Message] = [6 Message(role="system", content="You are a concise coding assistant."),7]89# Turn 110chat_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))1314# Turn 215chat_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:
1from evidor import GenerationRequest, Message, OpenAIProvider, Tool23tool_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)1314request = GenerationRequest(15 messages=[Message(role="user", content="What is the price of AAPL?")],16 tools=(tool_def,),17)18response = provider.generate(request)1920if response.tool_calls:21 for call in response.tool_calls:22 print(f"Tool call requested: {call.name} with args {call.arguments}")
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.
Chunks stringify directly to their text (str(chunk) returns chunk.text), so standard printing works out of the box: print(chunk, end="", flush=True).
Tool arguments stream silently behind the scenes without polluting chunk.text. When tool execution finishes, the final synthesized response streams to the caller.
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:
1from evidor import Agent, OpenAIProvider23agent = Agent(OpenAIProvider(model="gpt-6-astra"))45# Stream responses token-by-token6stream = agent.send("Write a short haiku about debugging code.", stream=True)7for chunk in stream:8 print(chunk, end="", flush=True)910# Access final accumulated response, token usage, and latency11print(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.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::
1import asyncio2from evidor import Agent, GeminiProvider34async 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)910 print(f"\nFinished with {stream.time_to_first_token_ms:.1f}ms TTFT")1112asyncio.run(main())
Streaming with Tools: Seamless Background Execution
When an agent needs to execute tools during a streaming turn:
chunk.text remains empty string (""), ensuring raw JSON arguments never pollute the client stream.asyncio.gather() if multiple tools were invoked) and updates the conversation history with the tool result.chunk.tool_calls:1from evidor import Agent, GeminiProvider, tool23@tool4def check_order_status(order_id: str) -> str:5 """Look up order shipping status."""6 return f"Order {order_id} is out for delivery."78agent = Agent(GeminiProvider(model="gemini-3.8-flash"), tools=[check_order_status])9stream = agent.send("Where is my order ORD-992?", stream=True)1011for chunk in stream:12 # chunk.tool_calls contains fully validated ToolCall instances when a tool is invoked13 if chunk.tool_calls:14 for call in chunk.tool_calls:15 print(f"\n[⚡ Executing tool: {call.name} with args {call.arguments}]")1617 # 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:
1from evidor import Agent, AnthropicProvider23agent = Agent(AnthropicProvider(model="claude-3-7-sonnet-20250219", thinking=2048))4stream = agent.send("Solve: Which is greater, 9.11 or 9.9?", stream=True)56for chunk in stream:7 if chunk.thinking:8 print(f"\033[90m{chunk.thinking}\033[0m", end="", flush=True) # Dim thinking text9 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():
1from evidor import GenerationRequest, OpenAIProvider23provider = OpenAIProvider(model="gpt-6-astra")45request = GenerationRequest(6 prompt="Explain consensus in distributed systems.",7 stream=True,8)910# Synchronous streaming11stream = provider.generate(request)12for chunk in stream:13 print(chunk, end="", flush=True)1415# Asynchronous streaming16# 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:
1from evidor import Agent, OpenAIProvider23agent = Agent(OpenAIProvider(model="gpt-6-astra"))45# Sync context manager ensures deterministic cleanup even on early break6with agent.send("List 5 facts about space.", stream=True) as stream:7 for chunk in stream:8 print(chunk, end="", flush=True)910# Async context manager11# 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)1415# Final accumulated response can also be retrieved via helper:16# final_response = stream.get_final_response()
stream.time_to_first_token_ms and recorded on LLMCallEndEvent.True on LLMCallStartEvent and LLMCallEndEvent.GenerationResponse without consuming remaining chunks manually.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:
1from evidor import (2 Agent,3 AnthropicProvider,4 AnthropicThinkingConfig,5 GeminiProvider,6 GeminiThinkingConfig,7 OpenAIProvider,8 OpenAIThinkingConfig,9)1011# 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"))1516# 2. Anthropic: Token budget or adaptive effort17# 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)2425# 3. Gemini: Thinking level ('minimal', 'low', 'medium', 'high') or budget26provider = 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:
1from evidor import Agent, AnthropicProvider23agent = Agent(AnthropicProvider(model="claude-3-7-sonnet-20250219", thinking=2048))4response = agent.send("Solve this logic riddle step-by-step...")56# Visible text response7print(response.text)89# Model's internal reasoning scratchpad (if available)10if response.thinking:11 print(f"Reasoning Steps:\n{response.thinking}")1213# Reasoning tokens recorded in usage metadata14if 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.
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:
1import asyncio2from evidor import Agent, OpenAIProvider, tool34@tool5async def lookup_account(account_id: str) -> dict:6 return {"id": account_id, "status": "active"}78async def main() -> None:9 # Async-first execution engine: runs natively on caller event loop10 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)1314asyncio.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:
1import asyncio2from evidor import Agent, OpenAIProvider, tool34@tool5async def fetch_user(user_id: str) -> dict:6 await asyncio.sleep(0.1)7 return {"id": user_id, "name": "Alice"}89@tool10async def fetch_orders(user_id: str) -> list[str]:11 await asyncio.sleep(0.1)12 return ["order-101", "order-102"]1314# 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)2021asyncio.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:
1import time2from evidor import Agent, OpenAIProvider34# Persistent connection pooling: internal daemon event loop reuses HTTP/2 connections5agent = Agent(OpenAIProvider(model="gpt-6-astra"))67# Turn 1: Establishes HTTP/2 TLS session8agent.send("Hello, initialize session.")910# Turn 2: Sockets and TLS state are preserved; 0ms handshake overhead11agent.send("Tell me a quick tip.")1213# Clean shutdown14agent.close()
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.
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:
1from evidor import tool23# Automatic JSON schema derivation from types & docstrings4@tool5def get_weather(location: str, unit: str = "celsius") -> str:6 """Get the current weather forecast for a given location.78 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."1314# Explicit name and description overrides15@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:
1from evidor import Agent, GeminiProvider, tool23@tool4def search_database(query: str) -> list[str]:5 """Search internal records by keyword."""6 return [f"Record 1 matching '{query}'", f"Record 2 matching '{query}'"]78agent = 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)1314response = agent.send("Can you check our records for 'alpha project'?")15print(response.text)
Async Tools & Timeouts
Evidor seamlessly supports asynchronous functions and execution timeouts:
1import asyncio2from evidor import Agent, GeminiProvider, tool34# Async functions are automatically executed without blocking5@tool(timeout=5.0) # Timeout in seconds6async def fetch_webpage(url: str) -> str:7 """Fetch content from a URL."""8 await asyncio.sleep(0.1)9 return f"Contents of {url}"1011# Configure an agent with a default timeout for all its tools12agent = Agent(13 GeminiProvider(model="gemini-3.8-flash"),14 tools=[fetch_webpage],15 tool_timeout=10.0, # Default tool timeout in seconds16 max_tool_iterations=10, # Max tool turns before forcing final synthesis17)
Manual Tool Definition
For dynamic or programmatic tools without a standard Python function signature, instantiate Tool directly:
1from evidor import Tool23# Programmatic tool creation without standard Python function inspection4custom_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 Utility Tools (Calculator & Time)
Evidor includes dependency-free tools you can opt into:
1from evidor import Agent, OpenAIProvider, calculator, get_current_time23# Built-in zero-dependency utility tools4agent = 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:
1from evidor import Agent, OpenAIProvider, calculator, filesystem_tools, get_current_time23# 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)
Provider-Neutral Web Search
Pluggable search using Tavily, Exa, or Brave adapters built exclusively with Python standard library:
1from evidor import Agent, OpenAIProvider, TavilySearchProvider, web_search23# Provider-neutral web search using Python standard library4search = web_search(TavilySearchProvider(), max_results=5)5agent = Agent(OpenAIProvider(model="gpt-4.1-mini"), tools=[search])67response = agent.send("Find the current Python release notes and cite the sources.")8print(response.text)
Webpage Reader (read_webpage)
Let agents fetch and read clean, token-bounded text from web pages, stripping HTML boilerplate automatically:
1from evidor import Agent, OpenAIProvider, read_webpage, read_webpage_tool23# Ready-to-use default tool (strips HTML boilerplate, bounded to 15,000 chars)4agent = Agent(OpenAIProvider(model="gpt-4.1-mini"), tools=[read_webpage])56# Or customized with explicit character and timeout limits7custom_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:
1from evidor import Agent, EvidenceStore, GeminiProvider23store = EvidenceStore()45# store.tools provides record_evidence, list_evidence, and compare_evidence6agent = Agent(GeminiProvider(model="gemini-3.8-flash"), tools=[*store.tools])7agent.send("Analyze trade-offs between PostgreSQL and SQLite and record your findings.")89# Inspect structured findings in Python or format as Markdown10print(store.to_markdown())11for item in store.items:12 print(f"[{item.id}] {item.topic}: {item.finding}")
MCP Overview & Local Stdio Servers
Connect agents to external MCP servers (e.g. AWS Bedrock, Amazon search) over local stdio subprocesses:
1from evidor import Agent, OpenAIProvider23# 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)1415# Tools exposed by MCP server are automatically discovered and executed16response = 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:
1from evidor import Agent, GeminiProvider, MCPServerConfig23# 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 subprocess8 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 server16 MCPServerConfig.sse(name="weather", url="http://localhost:8080/sse"),17 ],18)1920response = agent.send("Check warehouse stock and recommend hiking boots.")21print(response.text)22agent.close()
Standalone MCPClient & Tool Composition
Use MCPClient standalone to inspect tools, retrieve resources, or mix MCP tools with standard Python tools:
1import asyncio2from evidor import Agent, MCPClient, OpenAIProvider, tool34@tool5def internal_calculator(x: int, y: int) -> int:6 return x * y78async def main():9 async with MCPClient({"amazon": {"command": "uvx", "args": ["amazon-mcp-server"]}}) as mcp:10 # Retrieve all Evidor Tool objects from the MCP server11 mcp_tools = await mcp.get_tools_async()1213 # Combine MCP tools with local tools14 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)1718asyncio.run(main())
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:
1from opentelemetry import trace2from opentelemetry.sdk.trace import TracerProvider3from opentelemetry.sdk.trace.export import BatchSpanProcessor, ConsoleSpanExporter4from evidor import Agent, OpenAIProvider, OpenTelemetrySink56provider = TracerProvider()7provider.add_span_processor(BatchSpanProcessor(ConsoleSpanExporter()))8trace.set_tracer_provider(provider)910# Non-blocking telemetry (<1µs latency on agent thread) via dedicated worker11otel_sink = OpenTelemetrySink(tracer_provider=provider)12agent = Agent(OpenAIProvider("gpt-4.1-mini"), telemetry=otel_sink)1314response = 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:
1from evidor import Agent, OpenAIProvider, LangfuseSink23# Traces agent execution, latency, and tokens to Langfuse4langfuse_sink = LangfuseSink() # Reads credentials from environment5agent = Agent(OpenAIProvider("gpt-4.1-mini"), telemetry=langfuse_sink)67response = 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:
1from evidor import Agent, AnthropicProvider2from evidor.telemetry import ConsoleSink, OpenTelemetrySink, PhoenixSink, LangfuseSink34# 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)910agent = 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:
1from evidor import Agent, OpenAIProvider2from evidor.telemetry import OpenTelemetrySink, LangfuseSink34# 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)89agent = 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()
Supported Providers & Modern APIs
Evidor exclusively uses modern provider APIs with zero legacy fallbacks:
client.responses.create) with previous_response_id chaining. Requires openai>=1.0.0.client.interactions.create) with previous_interaction_id chaining. Requires google-genai>=1.0.0.cache_control) and native threshold compaction.Custom ModelProvider Protocol
Implement either synchronous generate(request), native asynchronous generate_async(request), or both:
1from evidor import GenerationRequest, GenerationResponse, ModelProvider23class CustomAsyncProvider(ModelProvider):4 """Implements the Evidor ModelProvider protocol with async-first support."""5 def __init__(self, model: str = "custom-model") -> None:6 self.model = model78 def with_model(self, model: str) -> "CustomAsyncProvider":9 return CustomAsyncProvider(model=model)1011 async def generate_async(self, request: GenerationRequest) -> GenerationResponse:12 # Asynchronously call custom model backend13 prompt_text = request.prompt14 return GenerationResponse(text="Custom async response", model=self.model)
Optional Package Extras Summary
| Extra | Purpose | Included 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 servers | mcp |
| evidor[otel] | OpenTelemetry distributed tracing | opentelemetry-api, opentelemetry-sdk |
| evidor[langfuse] | Langfuse tracing & evaluation | langfuse |
| evidor[phoenix] | Arize Phoenix OpenInference UI | arize-phoenix-otel, openinference-semantic-conventions |
| evidor[prometheus] | Prometheus metrics exposition | prometheus-client |
| evidor[all] | All providers, MCP, and telemetry adapters | All optional extras |
PyPI Release Model
Releases are automated via GitHub Actions and use Conventional Commits to calculate the next semantic version:
fix: ... creates a patch releasefeat: ... creates a minor releaseBREAKING CHANGE: ... creates a major releaseLocal Build & Testing
Build and test the package locally:
1python -m pip install -e ".[dev]"2python -m pytest3python -m build4python -m twine check dist/*