# API Reference

Complete API reference for Logos ADK.

## Agent

### `Agent`

Main agent class for building AI assistants.

```python
from logos_adk import Agent
```

#### Constructor

```python
Agent(name: str, *, model: Any | None = None, system: str | None = None)
```

**Parameters:**
- `name` — Agent identifier
- `model` — Model name string or Provider instance
- `system` — System prompt

#### Methods

##### `model(model: Any) -> Agent`

Set the model for this agent.

```python
agent.model("gpt-4o")
agent.model(anthropic_client)
```

##### `system(prompt: str) -> Agent`

Set system prompt.

```python
agent.system("You are a helpful assistant.")
```

##### `tools(tools: list[Tool] | Toolkit) -> Agent`

Attach tools to the agent.

```python
agent.tools([search_tool, calculator_tool])
agent.tools(my_toolkit)
```

##### `mcp(source: str | MCPClient) -> Agent`

Connect to MCP server.

```python
agent.mcp("http://localhost:3000/sse")
agent.mcp("npx @server-github")
agent.mcp(mcp_client)
```

##### `memory(*memories: Memory) -> Agent`

Attach memory strategies.

```python
agent.memory(session_memory, long_term_memory)
```

##### `observe(*exporters: Exporter) -> Agent`

Attach observability exporters.

```python
agent.memory(console_exporter, otel_exporter)
```

##### `output_schema(schema: type) -> Agent`

Set Pydantic model for structured output.

```python
class Response(BaseModel):
    answer: str
    confidence: float

agent.output_schema(Response)
```

##### `cache(backend, ttl, semantic, embed_fn, similarity_threshold) -> Agent`

Enable response caching.

```python
agent.cache(
    backend=InMemoryCacheBackend(),
    ttl=3600,
    semantic=True,
    embed_fn=embed_fn,
    similarity_threshold=0.95
)
```

##### `knowledge(kb, mode, limit) -> Agent`

Attach knowledge base for RAG.

```python
agent.knowledge(kb, mode="memory", limit=5)
```

##### `guardrail(guard) -> Agent`

Add guardrail for both input and output.

```python
agent.guardrail(content_filter)
```

##### `input_guardrail(guard) -> Agent`

Add input-only guardrail.

```python
agent.input_guardrail(regex_guard)
```

##### `output_guardrail(guard) -> Agent`

Add output-only guardrail.

```python
agent.output_guardrail(max_length_guard)
```

##### `on_event(event: str, handler: Any) -> Agent`

Register event handler.

```python
agent.on_event("start", my_handler)
```

##### `reload(path: str | None = None) -> None`

Reload agent config from YAML.

```python
agent.reload()  # Uses original path
agent.reload("new_config.yaml")
```

##### `serve(**kwargs) -> None`

Start web server for this agent.

```python
agent.serve(host="0.0.0.0", port=8000)
```

##### `send_to(to_agent: str, message: Any) -> None`

Send message to another agent in team.

```python
await agent.send_to("writer", "Here are the facts")
```

##### `broadcast_msg(message: Any) -> None`

Broadcast to all allowed agents.

```python
await agent.broadcast_msg("Task complete")
```

##### `run(prompt: str, *, session_id, **kwargs) -> Response`

Run agent with prompt.

```python
response = await agent.run("Hello!")
response = await agent.run("Continue", session_id="session-123")
```

**Kwargs:**
- `session_id` — Session identifier for context
- `on_text` — Callback for text chunks
- `on_tool_start` — Callback for tool calls
- `on_tool_end` — Callback for tool results
- `on_done` — Callback when complete
- `output_schema` — Override output schema

##### `stream(prompt: str, *, session_id, **kwargs) -> AsyncIterator[StreamChunk]`

Stream agent response.

```python
async for chunk in agent.stream("Tell me a story"):
    if isinstance(chunk, TextChunk):
        print(chunk.text, end="")
```

#### Class Methods

##### `from_definition(config: AgentConfig) -> Agent`

Build agent from typed config.

```python
config = AgentConfig(name="bot", model="gpt-4o")
agent = Agent.from_definition(config)
```

##### `from_config(path: str) -> Agent`

Load agent from YAML file.

```python
agent = Agent.from_config("agent.yaml")
```

#### Properties

- `name` — Agent name (read-only)
- `state_class` — State class type (default: `AgentState`)

---

## Team

### `Team`

Multi-agent orchestration.

```python
from logos_adk import Team
```

#### Constructor

```python
Team(
    name: str,
    *,
    agents: list[Agent] | None = None,
    orchestrator: str | None = None,
    topology: str | dict[str, list[str]] | None = None,
    max_rounds: int = 10,
    supervisor: Supervisor | None = None
)
```

**Parameters:**
- `name` — Team identifier
- `agents` — List of agent instances
- `orchestrator` — Name of orchestrator agent
- `topology` — Communication topology
- `max_rounds` — Maximum execution rounds
- `supervisor` — Optional supervisor

#### Methods

##### `get_agent(name: str) -> Agent | None`

Get agent by name.

```python
agent = team.get_agent("researcher")
```

##### `send(from_agent, to_agent, message) -> None`

Send message between agents.

```python
await team.send("researcher", "writer", "Facts collected")
```

##### `broadcast(from_agent, message) -> None`

Broadcast from agent.

```python
await team.broadcast("researcher", "Starting research")
```

##### `run(prompt: str, *, session_id, **kwargs) -> Response`

Run team with prompt.

```python
response = await team.run("Write an article")
```

##### `run_rounds() -> Response`

Process mailbox messages in rounds.

```python
response = await team.run_rounds()
```

##### `stream(prompt: str, *, session_id, **kwargs) -> AsyncIterator[StreamChunk]`

Stream team execution.

```python
async for chunk in team.stream("Task"):
    ...
```

##### `as_tool(name, description) -> Tool`

Convert team to tool.

```python
team_tool = team.as_tool(name="research_team", description="Research topics")
```

#### Properties

- `name` — Team name (read-only)

---

## Tools

### `tool` Decorator

Create tools from async functions.

```python
from logos_adk import tool
```

#### Usage

```python
@tool
async def search(query: str) -> str:
    """Search for information."""
    ...

@tool(name="custom_name", description="Custom description")
async def my_func(x: int) -> str:
    ...
```

### `Tool` Class

Tool representation.

```python
from logos_adk import Tool
```

#### Constructor

```python
Tool(fn: Callable, name: str, description: str)
```

#### Properties

- `name` — Tool name
- `description` — Tool description
- `schema` — JSON schema dict

#### Methods

##### `execute(call: ToolCall) -> ToolResult`

Execute tool call.

```python
result = await tool.execute(tool_call)
```

### `Toolkit`

Tool collection.

```python
from logos_adk import Toolkit
```

#### Methods

##### `get_tools() -> list[Tool]`

Get all tools.

##### `add(tool: Tool) -> None`

Add tool to kit.

### Tool Registry

```python
from logos_adk import registry

# Get tool
tool = registry.get("search")

# List all
tools = registry.list()

# Register
registry.register("my_tool", tool_instance)
```

### Built-in Tool Factories

```python
from logos_adk import cli_tool, claude_code_tool, codex_tool, gemini_tool
from logos_adk import acpx_tool, acpx_agent_tools

# CLI execution tool
cli = cli_tool()

# Claude Code
cc = claude_code_tool()

# Codex
codex = codex_tool()

# Gemini
gemini = gemini_tool()

# ACPX
acpx = acpx_tool()
tools = acpx_agent_tools()
```

---

## Memory

### `MemoryEntry`

Stored memory unit.

```python
from logos_adk import MemoryEntry
```

#### Fields

- `content` — Memory content
- `id` — Unique identifier
- `embedding` — Vector embedding
- `metadata` — Additional data
- `created_at` — Creation timestamp
- `session_id` — Session identifier

### `MemoryBackend`

Abstract storage backend.

```python
from logos_adk import MemoryBackend
```

#### Methods

##### `store(entry: MemoryEntry) -> None`

Store entry.

##### `search(query, limit, session_id) -> list[MemoryEntry]`

Search entries.

##### `delete(entry_id) -> None`

Delete entry.

### `Memory`

Abstract memory strategy.

```python
from logos_adk import Memory
```

#### Methods

##### `remember(messages, state, session_id) -> list[MemoryEntry]`

Retrieve relevant memories.

##### `commit(messages, response, state, session_id) -> None`

Commit new memories.

### `SessionMemory`

Short-term memory.

```python
from logos_adk import SessionMemory
```

#### Constructor

```python
SessionMemory(
    strategy="sliding_window",
    max_messages=20,
    max_tokens=None
)
```

**Strategies:**
- `sliding_window` — Keep last N messages
- `summarize` — Summarize old messages
- `token_limit` — Keep under token limit

### `LongTermMemory`

Persistent memory.

```python
from logos_adk import LongTermMemory
```

#### Constructor

```python
LongTermMemory(
    backend: MemoryBackend,
    retrieval="keyword",
    limit=5,
    embed_model=None
)
```

**Retrieval modes:**
- `keyword` — BM25 matching
- `semantic` — Vector search
- `hybrid` — Combined

### `SharedMemory`

Cross-session memory.

```python
from logos_adk import SharedMemory
```

Same API as `LongTermMemory`, but session_id is ignored.

### Backends

#### `InMemoryBackend`

```python
from logos_adk import InMemoryBackend

backend = InMemoryBackend()
```

#### `SQLiteBackend`

```python
from logos_adk import SQLiteBackend

backend = SQLiteBackend("memory.db")
```

---

## Guardrails

### `Guardrail`

Abstract base class.

```python
from logos_adk import Guardrail
```

#### Methods

##### `check(content, role) -> GuardrailResult`

Check content.

### `GuardrailResult`

Check result.

```python
from logos_adk import GuardrailResult
```

#### Fields

- `passed` — Pass/fail status
- `message` — Explanation
- `action` — block/warn/override
- `override_content` — Replacement content

### `ContentFilter`

Block words/phrases.

```python
from logos_adk import ContentFilter

filter = ContentFilter(
    blocked=["spam", "abuse"],
    case_sensitive=False,
    action="block",
    override_with="I can't help with that."
)
```

### `RegexGuard`

Pattern-based guard.

```python
from logos_adk import RegexGuard

guard = RegexGuard(
    deny=[r"pattern"],
    allow=[r"allowed"],
    action="block",
    message="Blocked"
)
```

### `MaxLengthGuard`

Length limit.

```python
from logos_adk import MaxLengthGuard

guard = MaxLengthGuard(max_chars=1000, action="block")
```

### `KeywordGuard`

Keyword detection.

```python
from logos_adk import KeywordGuard

guard = KeywordGuard(
    keywords=["word1", "word2"],
    action="warn",
    message="Detected",
    case_sensitive=False,
    override_with=None
)
```

---

## RAG

### `Document`

Loaded document.

```python
from logos_adk import Document
```

#### Fields

- `content` — Document text
- `metadata` — Additional data
- `id` — Unique identifier

### `Chunk`

Document chunk.

```python
from logos_adk import Chunk
```

#### Fields

- `content` — Chunk text
- `metadata` — Additional data
- `document_id` — Parent document
- `embedding` — Vector embedding
- `id` — Unique identifier

### `DocumentLoader`

Abstract loader.

```python
from logos_adk import DocumentLoader
```

#### Methods

##### `load(path: str) -> list[Document]`

Load documents.

### `TextLoader`

Load text files.

```python
from logos_adk import TextLoader

loader = TextLoader("docs/")
documents = loader.load()
```

### `MarkdownLoader`

Load markdown files.

```python
from logos_adk import MarkdownLoader

loader = MarkdownLoader("docs/md/")
```

### `TextSplitter`

Abstract splitter.

```python
from logos_adk import TextSplitter
```

#### Methods

##### `split(documents) -> list[Chunk]`

Split documents.

### `RecursiveCharacterSplitter`

Character-based splitter.

```python
from logos_adk import RecursiveCharacterSplitter

splitter = RecursiveCharacterSplitter(
    chunk_size=500,
    chunk_overlap=50,
    separators=["\n\n", "\n", ". "]
)
```

### `VectorStore`

Abstract vector store.

```python
from logos_adk import VectorStore
```

#### Methods

##### `add_documents(documents, splitter) -> None`

Add documents.

##### `search(query, limit, score_threshold) -> list[Chunk]`

Search chunks.

### `InMemoryVectorStore`

In-memory store.

```python
from logos_adk import InMemoryVectorStore

store = InMemoryVectorStore(embed_fn=embed_fn)
```

### `SQLiteVectorStore`

SQLite with vectors.

```python
from logos_adk import SQLiteVectorStore

store = SQLiteVectorStore("vectors.db", embed_fn=embed_fn)
```

### `ChromaVectorStore`

ChromaDB integration.

```python
from logos_adk import ChromaVectorStore

store = ChromaVectorStore(collection="docs", embed_fn=embed_fn)
```

### `KnowledgeBase`

RAG knowledge base.

```python
from logos_adk import KnowledgeBase

kb = KnowledgeBase(vector_store)
```

#### Methods

##### `search(query, limit) -> list[Chunk]`

Search knowledge base.

### `RAGMemory`

RAG as memory.

```python
from logos_adk import RAGMemory

memory = RAGMemory(kb, limit=5)
```

### `rag_tool`

RAG as tool.

```python
from logos_adk import rag_tool

tool = rag_tool(kb, limit=5)
```

---

## MCP

### `MCPClient`

MCP client.

```python
from logos_adk import MCPClient
```

#### Constructor

```python
MCPClient.from_string(source: str)
```

#### Methods

##### `connect() -> None`

Connect to server.

##### `get_tools() -> list[Tool]`

Get server tools.

##### `disconnect() -> None`

Disconnect.

#### Properties

- `connected` — Connection status

### `serve_as_mcp`

Serve agent via MCP.

```python
from logos_adk import serve_as_mcp

@serve_as_mcp
async def create_agent():
    return Agent("mcp_bot", model="...")
```

### `serve_as_mcp_async`

Async MCP server.

```python
from logos_adk import serve_as_mcp_async

await serve_as_mcp_async(agent)
```

---

## Observability

### `Span`

Trace span.

```python
from logos_adk import Span
```

#### Fields

- `name` — Span name
- `trace_id` — Trace identifier
- `span_id` — Span identifier
- `parent_span_id` — Parent span
- `started_at` — Start time
- `ended_at` — End time
- `duration_ms` — Duration
- `agent_name` — Agent name
- `session_id` — Session ID
- `status` — ok/error/warning
- `attributes` — Metadata

### `Metric`

Metric data.

```python
from logos_adk import Metric
```

#### Fields

- `name` — Metric name
- `value` — Metric value
- `unit` — Unit string
- `attributes` — Metadata

### `Exporter`

Abstract exporter.

```python
from logos_adk import Exporter
```

#### Methods

##### `on_span(span) -> None`

Handle span.

##### `on_metric(metric) -> None`

Handle metric.

##### `flush() -> None`

Flush data.

### `ConsoleExporter`

Console output.

```python
from logos_adk import ConsoleExporter

exporter = ConsoleExporter()
```

### `InMemoryExporter`

In-memory storage.

```python
from logos_adk import InMemoryExporter

exporter = InMemoryExporter()
# Access: exporter.spans, exporter.metrics
```

### `OpenTelemetryExporter`

OTLP HTTP exporter.

```python
from logos_adk import OpenTelemetryExporter

exporter = OpenTelemetryExporter(
    endpoint="http://localhost:4318/v1/traces",
    timeout=5.0,
    batch_size=100,
    max_retries=3,
    headers={"x-api-key": "..."},
    bearer_token="token",
    compression="gzip"
)
```

---

## Cache

### `CacheEntry`

Cache entry.

```python
from logos_adk import CacheEntry
```

#### Fields

- `content` — Cached content
- `tool_calls` — Tool calls
- `usage` — Token usage
- `vector` — Embedding
- `scope` — Scope hash
- `created_at` — Creation time

### `CacheConfig`

Cache configuration.

```python
from logos_adk import CacheConfig

config = CacheConfig(
    ttl=3600,
    semantic=True,
    embed_fn=embed_fn,
    similarity_threshold=0.95
)
```

### `CacheBackend`

Abstract backend.

```python
from logos_adk import CacheBackend
```

#### Methods

##### `get(key) -> CacheEntry | None`

Get entry.

##### `put(key, entry, ttl) -> None`

Store entry.

##### `search_similar(vector, threshold, limit, scope) -> list[CacheEntry]`

Semantic search.

### `InMemoryCacheBackend`

In-memory cache.

```python
from logos_adk import InMemoryCacheBackend

backend = InMemoryCacheBackend()
```

### `SQLiteCacheBackend`

SQLite cache.

```python
from logos_adk import SQLiteCacheBackend

backend = SQLiteCacheBackend("cache.db")
```

### `RedisCacheBackend`

Redis cache (optional).

```python
from logos_adk import RedisCacheBackend

backend = RedisCacheBackend("redis://localhost")
```

---

## Types

### `Message`

Conversation message.

```python
from logos_adk import Message
```

#### Fields

- `role` — user/assistant/system/tool
- `content` — Text content
- `tool_calls` — Tool calls
- `tool_result` — Tool result

### `Response`

Agent response.

```python
from logos_adk import Response
```

#### Fields

- `content` — Response text
- `tool_calls` — Tool calls
- `usage` — Token usage
- `raw` — Raw provider data
- `parsed` — Parsed structured response

### `StructuredResponse`

Structured response.

```python
from logos_adk import StructuredResponse
```

Extends `Response` with `parsed` field containing Pydantic model.

### `StreamChunk`

Streaming chunk base class.

### `TextChunk`

Text stream chunk.

```python
from logos_adk import TextChunk
```

#### Fields

- `text` — Text content
- `reasoning` — Reasoning text

### `ToolStart`

Tool call start.

```python
from logos_adk import ToolStart
```

#### Fields

- `name` — Tool name
- `arguments` — Tool arguments

### `ToolEnd`

Tool call end.

```python
from logos_adk import ToolEnd
```

#### Fields

- `name` — Tool name
- `result` — Tool result

### `StreamDone`

Stream completion.

```python
from logos_adk import StreamDone
```

#### Fields

- `response` — Final response

### `ToolCall`

Tool call request.

```python
from logos_adk import ToolCall
```

#### Fields

- `id` — Call ID
- `name` — Tool name
- `arguments` — Arguments dict

### `ToolResult`

Tool call result.

```python
from logos_adk import ToolResult
```

#### Fields

- `call_id` — Call ID
- `content` — Result content
- `error` — Error message
- `duration_ms` — Execution time

### `Usage`

Token usage.

```python
from logos_adk import Usage
```

#### Fields

- `input_tokens` — Input token count
- `output_tokens` — Output token count

### `AgentDelegation`

Agent delegation info.

---

## Config

### `AgentConfig`

Agent configuration.

```python
from logos_adk import AgentConfig
```

#### Fields

- `name` — Agent name
- `model` — Model config
- `provider` — Provider config
- `system_prompt` — System prompt
- `tools` — Tool list
- `memories` — Memory list
- `mcp_servers` — MCP servers
- `observers` — Observers
- `output_schema` — Output schema
- `input_guardrails` — Input guards
- `output_guardrails` — Output guards
- `cache_backend` — Cache backend
- `cache_config` — Cache config
- `knowledge_base` — Knowledge base

### `ProviderConfig`

Provider configuration.

```python
from logos_adk import ProviderConfig

config = ProviderConfig(
    type="openai-compatible",
    model="llama3",
    base_url="http://localhost:11434/v1",
    api_key="key"
)
```

#### Fields

- `type` — Provider type
- `model` — Model name
- `base_url` — API URL
- `api_key` — API key
- `api_key_env` — Env var for key
- `extra` — Extra config

### `TeamConfig`

Team configuration.

```python
from logos_adk import TeamConfig
```

#### Fields

- `name` — Team name
- `agents` — Agent list
- `orchestrator` — Orchestrator name
- `topology` — Topology config
- `max_rounds` — Max rounds

---

## Errors

### `LogosError`

Base error class.

### `ConfigError`

Configuration error.

```python
from logos_adk.errors import ConfigError
```

### `GuardrailError`

Guardrail violation.

```python
from logos_adk.errors import GuardrailError

try:
    ...
except GuardrailError as e:
    print(e.result.message)
```

### `MaxRoundsExceeded`

Team max rounds exceeded.

```python
from logos_adk.errors import MaxRoundsExceeded
```

### `RoutingError`

Invalid agent routing.

```python
from logos_adk.errors import RoutingError
```

### `DocumentLoadError`

Document load failure.

```python
from logos_adk.rag import DocumentLoadError
```

---

## Testing

### `mock_agent`

Mock agent for testing.

```python
from logos_adk import mock_agent

mock = mock_agent(responses=["Hello", "World"])
```

### `assert_response`

Assert response content.

```python
from logos_adk import assert_response

assert_response(response, contains="hello")
```

### `assert_tool_called`

Assert tool was called.

```python
from logos_adk import assert_tool_called

assert_tool_called(mock, "search")
```

### `assert_tool_not_called`

Assert tool not called.

```python
from logos_adk import assert_tool_not_called

assert_tool_not_called(mock, "delete")
```

### `assert_guardrail_blocked`

Assert guardrail blocked.

```python
from logos_adk import assert_guardrail_blocked

assert_guardrail_blocked(agent, "blocked content")
```

### `run_yaml_tests`

Run YAML test suite.

```python
from logos_adk import run_yaml_tests

results = run_yaml_tests("tests.yaml")
```

---

## Cost

### `CostTracker`

Track costs.

```python
from logos_adk import CostTracker

tracker = CostTracker()
```

#### Methods

##### `track(agent, response) -> None`

Track response.

##### `get_report(agent) -> CostReport`

Get cost report.

##### `reset() -> None`

Reset tracking.

### `CostReport`

Cost report.

```python
from logos_adk import CostReport
```

#### Fields

- `input_tokens` — Input count
- `output_tokens` — Output count
- `estimated_cost` — Cost estimate

---

## Runtime

### `Runtime`

Agent runtime.

```python
from logos_adk import Runtime
```

#### Methods

##### `spawn(agent) -> None`

Spawn agent.

##### `get_agent(name) -> Agent | None`

Get agent.

### `Supervisor`

Agent supervisor.

```python
from logos_adk import Supervisor
```

---

## State

### `AgentState`

Agent state.

```python
from logos_adk import AgentState
```

#### Fields

- `session_id` — Session ID
- `messages` — Message history
- `metadata` — State metadata

#### Methods

##### `add_message(message) -> None`

Add message.

##### `clear() -> None`

Clear state.

---

## Handler

### `handler` Decorator

Register message handler.

```python
from logos_adk import handler

class MyAgent:
    @handler
    def handle_request(self, msg: RequestType):
        return f"Handled: {msg}"
```

---

## Hot Reload

### `ConfigWatcher`

Watch config changes.

```python
from logos_adk import ConfigWatcher

async def on_reload(config):
    print(f"Reloaded: {config.name}")

watcher = ConfigWatcher("agent.yaml", on_reload=on_reload)
await watcher.start()
```

#### Methods

##### `start() -> None`

Start watching.

##### `stop() -> None`

Stop watching.

---

## Providers

### `Provider`

Abstract provider.

### `AnthropicProvider`

Anthropic provider.

```python
from logos_adk.providers import AnthropicProvider

provider = AnthropicProvider(
    model="claude-sonnet-4-20250514",
    api_key="key"
)
```

### `OpenAIProvider`

OpenAI provider.

```python
from logos_adk.providers import OpenAIProvider

provider = OpenAIProvider(
    model="gpt-4o",
    api_key="key"
)
```

### `OpenAICompatibleProvider`

OpenAI-compatible provider.

```python
from logos_adk.providers import OpenAICompatibleProvider

provider = OpenAICompatibleProvider(
    model="llama3",
    base_url="http://localhost:11434/v1",
    api_key="key"
)
```

### `OllamaProvider`

Ollama provider (via OpenAICompatibleProvider).

```python
from logos_adk.providers import OpenAICompatibleProvider

provider = OpenAICompatibleProvider(
    model="llama3",
    base_url="http://localhost:11434/v1",
    api_key="not-needed"
)
```

---

## Serve

### `serve`

Start HTTP server.

```python
from logos_adk import serve

serve(agents=[agent1, agent2], host="0.0.0.0", port=8000)
```

### `create_app`

Create FastAPI app.

```python
from logos_adk import create_app

app = create_app(agents=[agent], api_key="key")
```

#### Endpoints

- `POST /{agent}/run` — Run agent
- `POST /{agent}/stream` — Stream agent
- `GET /health` — Health check
- `GET /metrics` — Metrics
