AI-агенты: подготовка к интервью¶
~9 минут чтения
Предварительно: Учебные материалы AI-агенты | LLM-агенты
AI-агенты -- самая горячая тема на интервью 2026 года: 78% ML-вакансий senior уровня включают вопросы по агентам (LinkedIn ML Jobs Analysis, Jan 2026). SWE-Bench Verified показывает 84% success rate у лучших агентов, WebArena -- 62%. На интервью проверяют: ReAct pattern, multi-agent orchestration, memory architectures, tool use safety. Ниже -- вопросы трёх уровней: Basic, Medium, Killer.
Обновлено: 2026-02-11
1. ReAct Pattern¶
Basic¶
Q: Что такое ReAct?
A: Reasoning + Acting. Паттерн, где модель чередует мысли (Thought) и действия (Action) для решения задач.
Q: Чем agent отличается от обычной LLM?
A: Agent имеет: (1) Tools — может использовать внешние инструменты, (2) Memory — помнит контекст, (3) Planning — планирует действия.
Medium¶
Q: Как работает ReAct loop?
A: (1) Thought — анализ текущего состояния, (2) Action — вызов tool или решение, (3) Observation — результат, (4) Repeat или Finish.
Q: Проблемы ReAct agents?
A: (1) Hallucination tool calls, (2) Infinite loops, (3) Context window limits, (4) Latency, (5) Cost.
Killer¶
Q: Спроектируйте production ReAct agent.
A: (1) Structured output parsing, (2) Tool validation, (3) Timeout/iteration limits, (4) Error recovery, (5) Observability/logging, (6) Rate limiting, (7) Fallback strategies.
2. Multi-Agent Systems¶
Basic¶
Q: Зачем нужны multi-agent системы?
A: (1) Разделение ответственности, (2) Параллельное выполнение, (3) Специализация агентов, (4) Сложные workflow.
Q: Orchestration patterns?
A: (1) Sequential — по очереди, (2) Parallel — одновременно, (3) Hierarchical — manager + workers, (4) Network — свободное общение.
Medium¶
Q: LangChain vs LangGraph vs CrewAI?
A: LangChain — простые цепочки, LangGraph — state machines, CrewAI — role-based teams. Для production агентов — LangGraph.
Q: Как обеспечить agent coordination?
A: (1) Shared memory/state, (2) Message passing, (3) Central orchestrator, (4) Protocol definitions.
Killer¶
Q: Спроектируйте multi-agent систему для code review.
A: Agents: (1) Code Analyzer — статический анализ, (2) Security Reviewer — поиск уязвимостей, (3) Performance Reviewer — оптимизации, (4) Style Checker — code style, (5) Summarizer — итоговый отчёт. Orchestration: parallel analysis -> merge results -> summarizer.
3. Agent Memory Systems¶
Basic¶
Q: Какие типы памяти нужны AI agent?
A: Четыре типа: 1. Internal Knowledge — weights модели (immutable) 2. Context Window — текущий conversation (limited, ~128K tokens) 3. Short-term Memory — recent interactions, working memory (session-based) 4. Long-term Memory — persistent storage across sessions (vector DB, knowledge graph)
Q: Зачем agent нужен long-term memory?
A: Без long-term memory agent "забывает" всё между сессиями. С LTM: (1) Персонализация — помнит предпочтения пользователя; (2) Learning — накапливает опыт; (3) Consistency — последовательные ответы; (4) Efficiency — не повторяет исследования.
Medium¶
Q: Как реализовать long-term memory с vector database?
A: Architecture: 1. Storage: Embeddings в Pinecone/Milvus/Qdrant + metadata (timestamp, type, importance) 2. Retrieval: Semantic search по current context → top-k relevant memories 3. Summarization: Периодическая компрессия старых memories (LLM summary) 4. Forgetting: TTL или importance-based eviction
Code pattern:
Q: Episodic vs Semantic memory в контексте AI agents?
A: - Episodic: Конкретные события ("User asked about Python decorators at 3pm"). Stored as-is, retrieved по similarity. - Semantic: Extracted facts ("User prefers Python over JavaScript"). Stored как knowledge graph triples или structured facts.
Production: Episodic для short-term, Semantic для long-term. Redis для episodic (TTL), Vector DB для semantic.
Killer¶
Q: Спроектируйте memory architecture для customer service agent.
A:
Layer 1: Session Memory (Redis) - Current conversation context - TTL: 24 hours - Size: last 50 turns
Layer 2: Episodic Memory (Vector DB) - Past conversations with this user - Summarized per-interaction - Retrieved по relevance к current query
Layer 3: Semantic Memory (Knowledge Graph) - User facts: preferences, account info, history - Domain knowledge: product catalog, policies - Neo4j или ArangoDB
Layer 4: Procedural Memory - Learned workflows: successful resolution paths - Stored как state machine definitions
Retrieval Strategy: Hybrid = BM25 (keywords) + Dense (semantic) + Graph traversal (related entities)
Killer (Advanced)¶
Q: Что такое Agentic Memory (AgeMem) и чем отличается от традиционных memory architectures?
A:
Agentic Memory (AgeMem) — framework (arXiv:2601.01885, Jan 2026) который unifies long-term и short-term memory management directly в agent's policy.
| Aspect | Traditional Memory | Agentic Memory (AgeMem) |
|---|---|---|
| LTM/STM | Separate components | Unified in agent policy |
| Control | Heuristics/auxiliary controllers | LLM decides autonomously |
| Operations | Fixed rules | Tool-based actions |
| Training | Hand-crafted | RL-optimized end-to-end |
Key Innovation — Memory as Tools:
AgeMem exposes memory operations как tool-based actions:
# Agent can call these memory tools
memory_tools = [
"memory_store", # What to store
"memory_retrieve", # When to retrieve
"memory_update", # Update existing
"memory_summarize", # Compress
"memory_discard", # When to forget
]
# Agent decides autonomously
action = agent.decide(context)
if action.type == "memory_store":
memory.store(action.content, metadata)
Training — Three-Stage Progressive RL: 1. Stage 1: Supervised learning на successful memory trajectories 2. Stage 2: RL с dense rewards на memory quality 3. Stage 3: Step-wise GRPO для sparse/discontinuous rewards
Results on long-horizon benchmarks: - Improved task performance - Higher-quality long-term memory - More efficient context usage
Когда использовать: - Long-horizon reasoning tasks (multi-step, multi-session) - Adaptive memory needs (agent decides what to remember) - Production agents с evolving memory requirements
Source: arXiv:2601.01885 "Agentic Memory: Learning Unified Long-Term and Short-Term Memory Management for LLM Agents"
4. Tool Use & Safety¶
Basic¶
Q: Что такое function calling в LLM?
A: Модель генерирует structured output с tool name и parameters, которые можно исполнить. Format:
{"tool": "search", "args": {"query": "python tutorial"}}. OpenAI, Anthropic, Google поддерживают native function calling.
Q: Зачем нужен tool validation?
A: (1) Security — предотвратить malicious tool calls; (2) Correctness — проверить аргументы перед execution; (3) Error handling — graceful degradation при invalid inputs.
Medium¶
Q: Как защитить agent от prompt injection через tool outputs?
A: Multi-layer defense: 1. Sanitization: Strip control characters, escape HTML/JSON 2. Delimiter enforcement: Wrap tool output в markers 3. Output validation: Check for injection patterns в tool responses 4. Sandboxed execution: Run tools в isolated environment 5. Human approval: Require confirmation для sensitive operations
Q: Permission models для agent tool use?
A: - Allowlist: Explicit list разрешённых tools - Role-based: Different tools для different user roles - Context-aware: Tool доступ зависит от conversation state - Risk-scoring: High-risk tools требуют additional confirmation
Implementation:
Killer¶
Q: Спроектируйте secure tool execution environment.
A:
Layer 1: Input Validation - Schema validation (JSON Schema для каждого tool) - Type checking, range validation - Injection pattern detection (regex + ML classifier)
Layer 2: Execution Sandbox - Docker container per tool execution - Resource limits (CPU, memory, time) - Network isolation (whitelist domains) - No filesystem access кроме designated volumes
Layer 3: Output Filtering - PII detection (regex + NER) - Sensitive data masking - Size limits (truncate long outputs)
Layer 4: Audit & Monitoring - Log all tool calls с arguments и outputs - Rate limiting per user/session - Anomaly detection для unusual patterns
Layer 5: Human-in-the-Loop - Require approval для write operations - Async approval queue для high-risk actions - Bypass только для trusted users
5. Agent Evaluation¶
Basic¶
Q: Как оценить качество AI agent?
A: Key metrics: - Success Rate: % задач выполненных правильно - Efficiency: Steps taken vs optimal - Cost: Tokens used, API calls, time - Safety: No harmful actions
Q: Что такое WebArena benchmark?
A: Benchmark для web agents: 812 tasks на реальных websites (shopping, forums, maps). Agent должен navigate, interact с UI, complete multi-step tasks. Metrics: success rate, step efficiency. State-of-art: ~62% success (IBM CUGA, 2025).
Medium¶
Q: SWE-Bench для coding agents?
A: 2,294 real GitHub issues из 12 popular Python repos. Agent должен: (1) Understand issue, (2) Locate relevant code, (3) Write fix, (4) Pass tests. Metrics: % resolved issues. Top agents: 71-84% on SWE-Bench Verified (2025-2026). Проблема: requires actual codebase understanding.
Q: Agent evaluation vs LLM evaluation — в чём разница?
A: - LLM eval: Single-turn quality (answer correctness) - Agent eval: Multi-step success, planning quality, tool usage efficiency
Agent-specific metrics: - Trajectory correctness - Tool selection accuracy - Recovery from errors - Context management
Killer¶
Q: Спроектируйте evaluation pipeline для customer support agent.
A:
Dataset: 500 golden conversations с ground truth
Metrics Layer 1: Task Completion - Resolution rate (issue actually solved) - First-contact resolution % - Escalation rate
Metrics Layer 2: Quality - Answer accuracy (LLM-as-judge against ground truth) - Tone appropriateness (sentiment analysis) - Policy compliance (rule checker)
Metrics Layer 3: Efficiency - Turns to resolution - Tool calls count - Latency (p50, p99)
Metrics Layer 4: Business Impact - Customer satisfaction (CSAT) - Cost per conversation - Agent takeover rate (human needed)
Evaluation Loop: 1. Automated: Run на test set nightly 2. A/B: Compare versions в production 3. Human: Review 5% random conversations
See Also¶
- MLOps Interview Q&A -- model serving, CI/CD, monitoring
- Data Engineering Interview Q&A -- data leakage, Spark, feature stores
- AI Agents Materials -- ресурсы для подготовки по агентам
- LLM Agents -- архитектура LLM agents подробнее
- Agent Frameworks -- LangGraph, CrewAI, AutoGen
- Multi-Agent Orchestration -- паттерны координации агентов
Заблуждение: LLM-агент не может зацикливаться
ReAct agents часто попадают в infinite loops: повторяют одно и то же действие, не получая нужного результата. Production решение: max iterations (10-50), timeout, error recovery с fallback стратегией. На SWE-Bench 15% failures -- именно зацикливание.
Заблуждение: multi-agent = всегда лучше single-agent
Multi-agent добавляет: communication overhead, координацию, debugging complexity. Для простых задач single ReAct agent быстрее и дешевле. Multi-agent оправдан когда: задачи параллелизуемы, нужны разные специализации, или один контекст не вмещает всю информацию.
Заблуждение: vector DB = полноценная long-term memory
Vector DB хорош для semantic search, но не заменяет: structured facts (knowledge graph), procedural memory (state machines), temporal ordering. Production memory = hybrid: Redis для STM, Vector DB для semantic LTM, Knowledge Graph для structured facts.
Интервью: формат ответов¶
ReAct и Agent Design¶
Красный флаг: "Агент -- это LLM с промптом, который вызывает функции"
Сильный ответ: "Агент = LLM + Tools + Memory + Planning. ReAct чередует Thought/Action/Observation. Production требует: structured output parsing, tool validation, timeout/iteration limits, error recovery, observability. LangGraph для state machines, CrewAI для role-based teams."
Memory Systems¶
Красный флаг: "Для памяти агента достаточно передавать conversation history в контекст"
Сильный ответ: "4 типа: Internal Knowledge (weights), Context Window (128K tokens, limited), Short-term (session-based, Redis с TTL), Long-term (persistent, Vector DB + Knowledge Graph). AgeMem (2026) объединяет LTM/STM через RL-оптимизированные memory tools."
Agent Safety¶
Красный флаг: "Достаточно проверять input пользователя"
Сильный ответ: "Defence-in-depth: Layer 1 input validation, Layer 2 deterministic guardrails (tool allowlists, SQL sanitization), Layer 3 model-level (Constitutional AI), Layer 4 human-in-the-loop (approval workflows), Layer 5 LLM-as-Judge (output validation). OWASP LLM Top 10 покрывает ключевые угрозы."