# Logos ADK — Полная справка по возможностям

Этот документ содержит полное описание всех возможностей фреймворка Logos ADK.

## Оглавление

1. [Агенты](#1-агенты)
2. [Инструменты](#2-инструменты)
3. [Память](#3-память)
4. [Защитные механизмы](#4-защитные-механизмы)
5. [RAG](#5-rag)
6. [Рабочие процессы](#6-рабочие-процессы)
7. [Команды](#7-команды)
8. [Провайдеры](#8-провайдеры)
9. [Безопасность](#9-безопасность)
10. [Надёжность](#10-надёжность)
11. [Наблюдаемость](#11-наблюдаемость)
12. [Кеширование](#12-кеширование)
13. [Бюджетирование](#13-бюджетирование)
14. [Обучение](#14-обучение)
15. [События](#15-события)
16. [MCP](#16-mcp)
17. [CLI](#17-cli)
18. [YAML конфигурация](#18-yaml-конфигурация)

---

## 1. Агенты

### Создание агента

```python
from logos_adk import Agent

# Базовый агент
agent = Agent("name", model="gpt-4o", system="System prompt")

# Fluent API
agent = (
    Agent("assistant", model="gpt-4o")
    .system("Ты полезный ассистент")
    .role("Ассистент", goal="Помогать", backstory="Ты опытный")
    .tools([tool1, tool2])
    .memory(SessionMemory(...))
    .observe(ConsoleExporter())
)
```

### Все методы Agent

| Метод | Параметры | Описание |
|-------|-----------|----------|
| `.model(model)` | `model: str \| Provider` | Установить модель |
| `.system(prompt)` | `prompt: str` | Системный промпт |
| `.role(role, goal, backstory)` | `role: str, goal: str, backstory: str` | Crew-роль |
| `.goal(goal)` | `goal: str` | Цель агента |
| `.backstory(backstory)` | `backstory: str` | Предыстория |
| `.tools(tools)` | `tools: list[Tool] \| Toolkit` | Инструменты |
| `.artifact_sandbox(root)` | `root: str` | Песочница артефактов |
| `.mcp(source)` | `source: str \| MCPClient` | MCP сервер |
| `.memory(*memories)` | `memories: Memory` | Память |
| `.observe(*exporters)` | `exporters: Exporter` | Наблюдаемость |
| `.state_backend(store)` | `store: StateStore` | Хранилище состояния |
| `.session_cache(max)` | `max: int` | Кеш сессий |
| `.security(...)` | См. ниже | Безопасность |
| `.reliability(...)` | См. ниже | Надёжность |
| `.self_qa(...)` | См. ниже | Самопроверка |
| `.fallback(*models)` | `models: Any` | Fallback модели |
| `.cost_aware_routing(...)` | См. ниже | Маршрутизация по стоимости |
| `.budget(...)` | См. ниже | Бюджет |
| `.spend_ledger(ledger)` | `ledger: SpendLedger` | Учёт расходов |
| `.model_routing_learning(engine)` | `engine: Any` | Обучение маршрутизации |
| `.tool_workflow_learning(engine)` | `engine: Any` | Обучение workflow |
| `.temporal_autonomy()` | — | Временные инструменты |
| `.subscribe_topic(...)` | См. ниже | Подписка на события |
| `.on_event(event, handler)` | `event: str, handler: Any` | Обработчик событий |
| `.input_guardrail(guard)` | `guard: Guardrail` | Гард входа |
| `.output_guardrail(guard)` | `guard: Guardrail` | Гард выхода |
| `.knowledge(kb, mode, limit)` | `kb: KnowledgeBase, mode: str, limit: int` | RAG |

### Запуск агента

```python
# Синхронный запуск
response = await agent.run("prompt")
print(response.content)

# Потоковый вывод
async for chunk in agent.stream("prompt"):
    print(chunk.text)

# С сессией
response = await agent.run("prompt", session_id="user_123")

# С метаданными
response = await agent.run(
    "prompt",
    session_id="user_123",
    _trace_id="trace_456",
    _workspace_id="ws_789"
)
```

### AgentConfig поля

```python
@dataclass
class AgentConfig:
    name: str
    agent_class: str | None
    agent_module: str | None
    agent_factory: str | None
    model: Any | None
    provider: ProviderConfig | None
    system_prompt: str | None
    role: str | None
    goal: str | None
    backstory: str | None
    tools: list[Any]
    memories: list[Any]
    mcp_servers: list[Any]
    observers: list[Any]
    output_schema: Any | None
    input_guardrails: list[Any]
    output_guardrails: list[Any]
    event_handlers: dict[str, list[Any]]
    cache_backend: Any | None
    cache_config: Any | None
    knowledge_base: Any | None
    learning: LearningConfig
    scaling: ScalingConfig
    state: StateConfig
    security: SecurityConfig
    reliability: ReliabilityConfig
    routing: RoutingConfig
    self_qa: SelfQAConfig
    metadata: dict[str, Any]
    disabled_tools: list[str]
```

---

## 2. Инструменты

### Создание инструментов

```python
from logos_adk import tool, Toolkit

# Декоратор @tool
@tool
async def search(query: str, limit: int = 10) -> str:
    """Поиск информации.
    
    Args:
        query: Поисковый запрос
        limit: Максимум результатов
    """
    return f"Результаты: {query}"

# Toolkit класс
class SearchToolkit(Toolkit):
    def get_tools(self):
        return [search, analyze, summarize]

# Добавление агенту
agent.tools([search])
agent.tools(SearchToolkit())
```

### Параметры инструмента

```python
@tool(
    name="custom_name",  # Имя инструмента
    description="Описание",  # Описание для LLM
    tags=["search", "info"]  # Теги
)
async def my_tool(param: str) -> str:
    ...
```

### Встроенные инструменты

```python
from logos_adk import (
    ArtifactToolkit,  # Работа с файлами
    TemporalToolkit   # Планирование событий
)

agent.tools(ArtifactToolkit(root="/artifacts"))
agent.temporal_autonomy()  # Добавляет schedule_event, cancel_event
```

---

## 3. Память

### SessionMemory (краткосрочная)

```python
from logos_adk import SessionMemory

# Sliding window (последние N сообщений)
session = SessionMemory(
    strategy="sliding_window",
    max_messages=20
)

# Summarize (суммаризация контекста)
session = SessionMemory(
    strategy="summarize",
    max_messages=50,
    summary_interval=10
)

# Token limit (ограничение токенов)
session = SessionMemory(
    strategy="token_limit",
    max_tokens=16000
)
```

### LongTermMemory (долгосрочная)

```python
from logos_adk import LongTermMemory
from logos_adk.memory import SQLiteBackend

long_term = LongTermMemory(
    backend=SQLiteBackend("memory.db"),
    retrieval="hybrid",  # keyword, semantic, hybrid
    limit=5,
    embed_model="sentence-transformers/all-MiniLM-L6-v2"
)
```

### SharedMemory (общая)

```python
from logos_adk import SharedMemory
from logos_adk.memory import PostgreSQLBackend

shared = SharedMemory(
    backend=PostgreSQLBackend("postgresql://..."),
    scope="workspace"  # workspace, global
)
```

### Memory backends

- `InMemoryBackend` — Development
- `SQLiteBackend` — Локальное хранилище
- `PostgreSQLBackend` — Production
- `ShardedMemoryBackend` — Распределённое

---

## 4. Защитные механизмы

### Типы гардов

```python
from logos_adk.guardrails import (
    ContentFilter,      # Блокировка слов
    RegexGuard,         # Паттерны
    MaxLengthGuard,     # Длина
    KeywordGuard,       # Ключевые слова
    ToxicityGuard,      # Токсичность
    ContentModerationGuard,  # Модерация
    HallucinationGuard  # Галлюцинации
)
```

### ContentFilter

```python
ContentFilter(
    blocked=["спам", "злоупотребление"],
    case_sensitive=False,
    action="block",  # block, warn, override
    override_with="Я не могу помочь с этим."
)
```

### RegexGuard

```python
RegexGuard(
    deny=[r"<script.*?>", r"javascript:"],
    allow=[r"https?://.*"],
    action="block",
    message="Обнаружен подозрительный паттерн"
)
```

### MaxLengthGuard

```python
MaxLengthGuard(
    max_chars=5000,
    action="block"
)
```

### KeywordGuard

```python
KeywordGuard(
    keywords=["конкурент", "аналог"],
    action="warn",
    message="Обнаружено ключевое слово",
    case_sensitive=False,
    override_with="..."
)
```

### ToxicityGuard

```python
ToxicityGuard(
    toxic_terms=["оскорбление1", "оскорбление2"],
    threshold=2,  # Количество совпадений
    action="block"
)
```

### ContentModerationGuard

```python
ContentModerationGuard(
    blocked_categories=["violence", "hate"],
    action="block"
)
```

### HallucinationGuard

```python
HallucinationGuard(
    reference_text="Факты для проверки",
    required_facts=["fact1", "fact2"],
    action="warn"
)
```

### Применение гардов

```python
agent = (
    Agent("bot", model="gpt-4o")
    .input_guardrail(
        ContentFilter(blocked=["спам"]),
        MaxLengthGuard(max_chars=5000)
    )
    .output_guardrail(
        ToxicityGuard(threshold=2),
        HallucinationGuard(reference_text="...")
    )
)
```

---

## 5. RAG

### Загрузчики документов

```python
from logos_adk.rag import (
    TextLoader,      # .txt файлы
    MarkdownLoader,  # .md файлы
    HTMLLoader,      # HTML контент
    CSVLoader,       # .csv файлы
    JSONLoader,      # .json файлы
    URLLoader        # Веб-страницы
)

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

### Сплиттеры

```python
from logos_adk.rag import RecursiveCharacterSplitter

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

### Векторные хранилища

```python
from logos_adk.rag import (
    InMemoryVectorStore,  # Development
    SQLiteVectorStore,    # Локальное
    ChromaVectorStore     # Production
)

# SQLite
vector_store = SQLiteVectorStore("rag.db")

# Chroma
vector_store = ChromaVectorStore(
    collection_name="my_collection",
    path="./chroma_db"
)
```

### KnowledgeBase

```python
from logos_adk import KnowledgeBase

kb = KnowledgeBase(
    store=vector_store,
    embed_fn=embedding_function,
    splitter=splitter
)

# Ингестия
await kb.ingest("docs/")
await kb.ingest_text("content", metadata={"source": "manual"})

# Поиск
chunks = await kb.search("query", limit=5)
```

### RAG инструмент

```python
from logos_adk import rag_tool

rag = rag_tool(kb, limit=5)
agent.tools([rag])

# Или авто-инъекция
agent.knowledge(kb, mode="memory", limit=5)
```

### Режимы RAG

- `"memory"` — Авто-инъекция контекста
- `"tool"` — Явный инструмент поиска
- `"both"` — Оба режима

---

## 6. Рабочие процессы

### Graph

```python
from logos_adk import Graph, AgentStep, FunctionStep

graph = Graph("workflow", max_visits=10, checkpoint_store=store)

# Узлы
graph.node(AgentStep("step1", agent1), metadata={...})
graph.node(FunctionStep("step2", my_function))
graph.node(agent3, name="step3")

# Рёбра
graph.edge("step1", "step2", label="normal")
graph.edge("step1", "step3", when=lambda ctx: condition, label="conditional")

# Условные маршруты
graph.conditional_routes("source", {
    "target1": lambda ctx: condition1,
    "target2": lambda ctx: condition2,
}, default="default_target")

# Точки входа/выхода
graph.entrypoint("step1")
graph.terminal("step3")

# Запуск
result = await graph.run("prompt")

# Стриминг событий
async for event in graph.stream_events("prompt"):
    print(event.event, event.node_name)

# Resume после approval
async for event in graph.resume("prompt", correlation_id="..."):
    ...
```

### Pipeline

```python
from logos_adk import Pipeline

pipeline = Pipeline("pipeline", retry=retry_policy, timeout=60.0, state_store=store)

# Шаги
pipeline.step(agent1, name="step1", retry=..., timeout=..., guardrails=[...])
pipeline.function(my_fn, name="step2")
pipeline.graph(sub_graph, name="step3")
pipeline.parallel(agent1, agent2, agent3, name="parallel")
pipeline.conditional(
    lambda ctx: condition,
    then=agent_yes,
    else_=agent_no,
    name="conditional"
)
pipeline.loop(agent, until=lambda ctx: done, max_iterations=10, name="loop")
pipeline.approval(name="approval", message="Approve?")

# Запуск
result = await pipeline.run("prompt")

# Resume после approval
result = await pipeline.resume(pipeline_id, approval=True)
```

### Step типы

- `AgentStep` — Запуск агента
- `FunctionStep` — Async функция
- `ParallelStep` — Параллельное выполнение
- `ConditionalStep` — Ветвление
- `LoopStep` — Цикл
- `ApprovalStep` — Утверждение
- `PublishEventStep` — Публикация события
- `WaitForEventStep` — Ожидание события

---

## 7. Команды

### Team

```python
from logos_adk import Team

team = Team(
    "team_name",
    agents=[agent1, agent2],
    orchestrator="agent1",
    topology="mesh",  # или dict с рёбрами
    max_rounds=10
)

# Запуск
response = await team.run("prompt")

# Кик-офф с ролью
response = await team.kickoff("prompt", role="researcher")

# Делегирование
response = await team.delegate("task", to_agent="agent1")
```

### CrewProcess

```python
from logos_adk import CrewProcess, CrewTask

tasks = [
    CrewTask(
        name="research",
        description="Исследовать тему",
        task_type="work",  # или "approval"
        role="researcher",
        agent_name="agent1",
        expected_output="Отчёт",
        depends_on=[],
        context=["previous"],
        async_execution=False,
        approval_message="Утвердить?",
        output_key="research",
        handoff_to_role="writer",
        metadata={}
    )
]

crew = CrewProcess(
    name="content_crew",
    team=team,
    tasks=tasks,
    process="sequential",  # или "hierarchical"
    manager_role="manager",
    max_parallel_tasks=3
)

result = await crew.run("kickoff prompt")
result = await crew.resume_approval("task_name", approved=True)
```

### Process режимы

- `sequential` — Последовательное выполнение
- `hierarchical` — Менеджер делегирует ролям

### Topology

```python
# Mesh (все со всеми)
topology="mesh"

# Star (оркестратор в центре)
topology="star"

# Custom
topology={
    "agent1": {"agent2", "agent3"},
    "agent2": {"agent1"},
    "agent3": {"agent1"}
}
```

---

## 8. Провайдеры

### OpenAIProvider

```python
from logos_adk.providers import OpenAIProvider

provider = OpenAIProvider(
    model="gpt-4o",
    api_key="sk-...",
    base_url=None,
    proxy=None
)
```

### OpenAICompatibleProvider

```python
from logos_adk.providers import OpenAICompatibleProvider

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

# Polza AI
provider = OpenAICompatibleProvider(
    model="minimax/minimax-m2.5",
    base_url="https://api.polza.ai/api/v1",
    api_key="pza_..."
)

# Together AI
provider = OpenAICompatibleProvider(
    model="meta-llama/Llama-3-70b",
    base_url="https://api.together.xyz/v1",
    api_key="..."
)
```

### AnthropicProvider

```python
from logos_adk.providers import AnthropicProvider

provider = AnthropicProvider(
    model="claude-sonnet-4-20250514",
    api_key="sk-ant-...",
    max_tokens=4096
)
```

### GeminiProvider

```python
from logos_adk.providers import GeminiProvider

provider = GeminiProvider(
    model="gemini-2.0-flash",
    api_key="...",
    base_url="https://generativelanguage.googleapis.com/v1beta"
)
```

### MockProvider

```python
from logos_adk.providers import MockProvider

mock = MockProvider(responses=[
    "Ответ 1",
    "Ответ 2"
])
```

### Авто-регистрация

- `claude-*` → AnthropicProvider
- `gpt-*`, `o1-*`, `o3-*` → OpenAIProvider
- `gemini-*` → GeminiProvider

---

## 9. Безопасность

### InputValidator

```python
from logos_adk.security import InputValidator

validator = InputValidator(
    min_length=1,
    max_length=20000,
    reject_null_bytes=True
)
```

### PromptShield

```python
from logos_adk.security import PromptShield

shield = PromptShield(
    patterns=["inject", "ignore previous"],
    threshold=0.5
)
```

### PIIDetector

```python
from logos_adk.security import PIIDetector

pii = PIIDetector(
    blocked_types=["ssn", "credit_card", "email", "phone"]
)
```

### AuditLogger

```python
from logos_adk.security import AuditLogger, AuditRetentionPolicy

audit = AuditLogger(
    redact_pii=True,
    retention=AuditRetentionPolicy(ttl_days=30)
)
```

### RateLimiter

```python
from logos_adk.security import RateLimiter, InMemoryRateLimitStore

limiter = RateLimiter(
    store=InMemoryRateLimitStore(),
    limit=100,
    window_seconds=60,
    burst=20
)
```

### SecurityConfig

```python
agent.security(
    input_validator=InputValidator(...),
    prompt_shield=PromptShield(...),
    pii_detector=PIIDetector(...),
    audit_logger=AuditLogger(...)
)
```

---

## 10. Надёжность

### RetryPolicy

```python
from logos_adk.reliability import RetryPolicy

retry = RetryPolicy(
    max_attempts=3,
    base_delay=0.25,
    backoff="exponential",  # или "linear"
    retry_on=(ProviderError, TimeoutError)
)
```

### CircuitBreaker

```python
from logos_adk.reliability import CircuitBreaker

circuit = CircuitBreaker(
    failure_threshold=5,
    recovery_timeout=30.0
)
```

### ProviderHealth

```python
from logos_adk.reliability import ProviderHealth

health = ProviderHealth(
    circuit_breaker=circuit,
    retry_policy=retry
)
```

### ReliabilityConfig

```python
agent.reliability(
    retry_policy=RetryPolicy(max_attempts=3),
    provider_timeout=60.0,
    fallback_models=["gpt-4o", "claude-sonnet-4"]
)
```

---

## 11. Наблюдаемость

### ConsoleExporter

```python
from logos_adk.observe import ConsoleExporter

agent.observe(ConsoleExporter())
```

### InMemoryExporter

```python
from logos_adk.observe import InMemoryExporter

agent.observe(InMemoryExporter())
```

### OpenTelemetryExporter

```python
from logos_adk.observe import OpenTelemetryExporter

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

### LangfuseExporter

```python
from logos_adk.observe import LangfuseExporter

langfuse = LangfuseExporter(
    base_url="https://cloud.langfuse.com",
    public_key="pk-...",
    secret_key="sk-...",
    ingestion_path="/api/public/ingestion",
    compression="gzip"
)
```

### NativeObservabilityExporter

```python
from logos_adk.observe import NativeObservabilityExporter

native = NativeObservabilityExporter(
    backend="postgresql",
    dsn="postgresql://..."
)
```

---

## 12. Кеширование

### ExactCache

```python
from logos_adk.cache import ExactCache, SQLiteCacheBackend

cache = ExactCache(
    backend=SQLiteCacheBackend("cache.db"),
    ttl=3600  # 1 час
)
```

### SemanticCache

```python
from logos_adk.cache import SemanticCache, SQLiteCacheBackend

cache = SemanticCache(
    backend=SQLiteCacheBackend("cache.db"),
    threshold=0.9,  # Порог схожести
    ttl=3600
)
```

---

## 13. Бюджетирование

### Budget

```python
agent.budget(
    task_budget_usd=0.10,
    task_budget_tokens=1000,
    threshold_ratio=0.8,
    fail_on_budget_exhausted=True
)
```

### CostAwareRouting

```python
agent.cost_aware_routing(
    enabled=True,
    budget_preference="balanced",  # cheap, balanced, premium
    workspace_soft_limit_usd=100.0
)
```

### SpendLedger

```python
from logos_adk.cost import SpendLedger

ledger = SpendLedger(
    workspace_id="ws_123",
    soft_limit_usd=100.0,
    hard_limit_usd=150.0
)

agent.spend_ledger(ledger)
```

---

## 14. Обучение

### ModelRoutingLearning

```python
agent.model_routing_learning(engine)
```

### ToolWorkflowLearning

```python
agent.tool_workflow_learning(engine)
pipeline.tool_workflow_learning(engine)
```

### RetrievalLearning

```python
from logos_adk.learning import RetrievalLearning

retrieval = RetrievalLearning(
    path=".logos_adk/retrieval.db"
)
```

---

## 15. События

### Подписка

```python
agent.subscribe_topic(
    "topic.name",
    handler=my_handler,
    publish_to=["other_topic"],
    name="subscription_name"
)
```

### Публикация

```python
await agent.publish_event("topic", {"key": "value"})
```

### Планирование

```python
await agent.schedule_event("topic", payload, delay_seconds=60)
await agent.cancel_event(event_id)
```

### A2A коммуникация

```python
# Отправка
await agent.send_a2a("other_agent", "task")

# Запрос и ожидание
response = await agent.request_a2a("other_agent", "task")

# Ответ
await agent.respond_a2a(request, "response")
```

---

## 16. MCP

### Подключение

```python
# SSE
agent.mcp("http://localhost:3000/sse")

# stdio
agent.mcp("npx @server-github")

# MCPClient
from logos_adk.mcp import MCPClient
client = MCPClient.from_string("http://localhost:3000/sse")
agent.mcp(client)
```

---

## 17. CLI

```bash
# Чат
logos-adk chat agent.yaml

# Запуск
logos-adk run agent.yaml "prompt"

# Стриминг
logos-adk run agent.yaml "prompt" --stream

# Валидация
logos-adk validate agent.yaml

# Тестирование
logos-adk test agent.yaml

# Сервер
logos-adk serve --agents agent.yaml --port 8000

# Управление проектом и апгрейдом
logos-adk project --help
logos-adk upgrade --help

# Состояние
logos-adk storage upgrade-check --kind state --backend sqlite --path .logos_adk/state.db
logos-adk storage migrate --kind state --backend sqlite --path .logos_adk/state.db
```

---

## 18. YAML конфигурация

### Agent

```yaml
name: assistant
model: claude-sonnet-4-20250514
system_prompt: "Ты полезный ассистент"

provider:
  type: openai-compatible
  base_url: http://localhost:11434/v1
  model: llama3

tools:
  - name: search
    description: Поиск
    parameters:
      type: object
      properties:
        query:
          type: string
      required: [query]

memories:
  session:
    strategy: sliding_window
    max_messages: 20
  long_term:
    backend:
      type: sqlite
      path: .logos_adk/memory.db
    retrieval: hybrid
    limit: 5

security:
  input_validation_enabled: true
  prompt_shield_enabled: true
  pii_detection_enabled: true

reliability:
  timeout_seconds: 60.0
  retry_max_attempts: 3

guardrails:
  input:
    - type: max_length
      max_chars: 5000
  output:
    - type: content_filter
      blocked: ["спам"]

knowledge:
  backend: sqlite
  path: .logos_adk/rag.db
  mode: tool
  limit: 5

observe:
  exporter: console
```

### Graph

```yaml
name: workflow
max_visits: 10
entrypoint: "step1"
terminal_nodes: ["step3"]

nodes:
  - name: "step1"
    agent: "agent1"
  - name: "step2"
    approval:
      message: "Утвердить?"
  - name: "step3"
    function: "my_function"

edges:
  - from: "step1"
    to: "step2"
    label: "ready"
  - from: "step2"
    to: "step3"
    when: "approval.status == 'approved'"
    label: "approved"
```

### Team

```yaml
name: team
agents:
  - name: researcher
    role: researcher
    model: claude-sonnet-4
  - name: writer
    role: writer
    model: gpt-4o

orchestrator: researcher
topology: mesh
max_rounds: 10

process: sequential
manager_role: manager
```

---

## Приложения

### A. Производственные примеры

См. [`docs/examples.md`](../docs/examples.md) для рабочих примеров и [`docs/production.md`](../docs/production.md) для production-ориентированного развёртывания.

### B. Production Guide

См. [`docs/production.md`](../docs/production.md) для руководства по развёртыванию.

### C. Examples

См. [`docs/examples.md`](../docs/examples.md) для публичных примеров кода.
