Multi-Agent AI System (Collaborating in LangGraph) Source Demo | AI Orchestration from Zero T5
AI For Your Work · 2026-04-08 · 11м 25с · 577 просмотров · YouTube ↗
Топики: ai-loop-engineering
🎧 Аудио
📝 Summary
model=deepseek-v4-flash · prompt=summary-v7 · 3 674→1 806 tokens · 2026-07-20 12:03:49
🎯 Главная суть
Вместо одного агента, выполняющего все задачи (сбор данных, анализ, оформление), строится граф из двух специализированных LLM-узлов: Research Agent (только сбор фактов) и Analysis Agent (только интерпретация). Один и тот же Claude получает разные system prompt’ы, а роутер на основе ключевых слов направляет запрос по одному из трёх возможных путей. Агенты общаются через общий список сообщений (shared state), но каждый использует собственную инструкцию, которая не попадает в общее состояние.
Разделение труда через system prompts
Оба агента работают на одной LLM (Claude), но с разными инструкциями.
- Research Agent: «Собирай точные фактические данные. Используй инструмент. Представляй сырые данные без анализа».
- Analysis Agent: «Интерпретируй данные о цене золота. Дай наблюдения о значимости, волатильности, перспективах. Думай как финансовый аналитик».
System prompt каждого агента добавляется в начало его сообщения при каждом вызове LLM и не сохраняется в общем состоянии — это предотвращает «перетекание» инструкций от одного агента к другому. В shared state находятся только сами сообщения (результаты вызова инструмента, ответы агентов), но не системные промпты.
Маршрутизация запросов: три пути в одном графе
Роутер — простая функция на основе ключевых слов. Проверяет вопрос на наличие слов «price», «cost», «today», «check» и т.п.
- Путь «только данные» (вопрос «Какая была цена золота вчера?»). Роутер направляет в Research Agent. Тот вызывает инструмент и сразу возвращает ответ; Analysis Agent не запускается.
- Путь «данные + анализ» (например, «Текущая цена золота и что она нам говорит?»). Сначала Research Agent собирает данные, затем после проверки на ключевые слова анализа («tell us», «what does it mean») происходит handoff к Analysis Agent. Аналитик получает все собранные данные и генерирует полный рыночный обзор.
- Путь «только анализ» (вопрос «Является ли золото хорошей инвестицией?»). Роутер пропускает Research Agent и отправляет запрос сразу Analysis Agent, который использует память предыдущих диалогов.
Устройство графа LangGraph
Граф включает четыре узла: Research Agent (LLM + инструмент), Analysis Agent (LLM без инструментов), узел tools, и стартовый роутер.
- После Research Agent стоит условное ребро: если нужен анализ — к Analysis Agent, иначе — к конечному узлу.
- Узел tools зациклен на Research Agent (после вызова инструмента агент получает результат и формирует ответ).
- Analysis Agent всегда идёт к конечному узлу.
- Граф компилируется с памятью (shared state), чтобы сохранять историю сообщений между разными вопросами.
Общее состояние (shared state) и изоляция промптов
Единственный список сообщений в state доступен всем узлам. Research Agent пишет в него результат вызова инструмента и свой ответ. Analysis Agent читает оттуда данные, видит весь контекст (включая предыдущие вопросы-ответы), но не имеет доступа к system prompt’у исследователя.
Важный трюк для анализатора: когда он запускается после исследователя, последнее сообщение уже является AI-ответом. Чтобы Claude не вернул пустой ответ, перед вызовом Analysis Agent принудительно добавляется дополнительное human-сообщение «Provide your market analysis».
Демонстрация трёх вопросов
На тестовом запуске каждая из трёх фраз проходит свой путь:
- «What was the gold price yesterday?» — Router → Research → End (аналитик не вызывается).
- «What is the current gold price and what does it tell us?» — Router → Research → (проверка на анализ) → Analysis → End. Аналитик видит все собранные данные и выдаёт полноценный разбор.
- «Based on what we've discussed, is gold a good investment?» — Router → сразу Analysis. Аналитик использует память от предыдущих вопросов (диалог уже содержит цены и анализ).
Сообщения накапливаются: во втором вопросе аналитик видит больше сообщений, чем в первом; в третьем — весь предыдущий диалог.
Дальнейшее развитие: собственные инструменты у каждого агента
В следующем туториале каждый агент получает свой набор инструментов: у исследователя — поиск новостей и цен, у аналитика — калькулятор и форматирование отчётов. Маршрутизация в графе остаётся той же, но специализация становится ещё глубже. Этот паттерн (специализированные агенты, общающиеся через shared state) — основа для построения полноценных multi-agent приложений.
📜 Transcript
en · 1 325 слов · 21 сегментов · clean
Показать текст транскрипта
Welcome back to AI for your work! This is tutorial 5, Multi-Agent Basics. Up until now, we've had one agent doing everything. Thinking, acting, remembering. Today, we build a team. Two agents with different specializations collaborating through shared state. Let's go! In our previous tutorials, one agent did everything. Ask about gold prices and it would fetch the data and interpret it. and summarize it. That works, but it's like asking one person to be the researcher, the analyst, and the writer. Today we split the work. A research agent that only gathers data, an analysis agent that only interprets it. Each agent gets a focused system prompt, and focused agents produce better results. This is the core principle of multi-agent design, specialization through prompt engineering. Same LLM, Different instructions, different output. Here's how the graph works. There are three possible paths through it. Path 1, data only. What was the gold price yesterday? The router sees data keywords, sends it to the research agent. The research agent fetches the data, and that's it. No analyst needed. Straight to end. Path 2, data plus analysis. What's the gold price, and what does it tell us? Data keywords send it to the researcher. Then analysis keywords like tell us trigger a handoff to the analyst. Path three, analysis only. Is gold a good investment? No data keywords, so the router skips the researcher entirely and goes straight to the analyst. Three pads, one graph. The router decides at runtime. This tutorial introduces four new concepts. Multiple agent nodes. For the first time, our graph has more than one LLM-powered node. System prompts. Each agent gets different instructions that define its role. The researcher is told to gather facts. The analyst is told to interpret and advise. Router. A function that examines the question and decides which agent handles it. And sequential handoff. When the researcher finishes, its output flows through the shared state to the analyst. Let's build it! Let's write the multi-agent system. nano-multi-underscore-agent.py The imports are familiar, same lang graph and anthropic setup as before, but notice we now import system message and human message from lang chain core messages. We'll need those for the agent prompts. The tool is the same gold price fetcher from tutorial 3. Nothing changes here. Now the new part... two separate LLM instances. The Research LLM has tools bound to it. It can fetch gold prices. The Analysis LLM has no tools. It works purely with the data already in the state. And here are the system prompts. This is where specialization happens. The Research prompt says, gather accurate factual data. Use your tool. Present raw data clearly without adding analysis. The analysis prompt says, interpret gold price data, provide observations about significance, volatility, and outlook. Think like a financial analyst. Same Claude model, completely different behavior. The agent nodes. Each one prepends its system prompt to the messages, calls its LLM, and returns the response. Notice the analysis agent appends an extra human message. Provide your market analysis. This is needed because when the analyst runs after the researcher, the last message is already an AI response. Without this nudge, Claude would return empty. Also notice the print statements. They show which agent is running and how many messages are in memory. The router. It checks the question for data keywords. Price, cost, today, check, and so on. If it finds one, route to the research agent. Otherwise, route to the analyst. Simple keyword matching, transparent and debuggable. In production, you'd use an LLM-based router, but for learning, you want to see exactly why a question goes where it goes. And the after research decision. This is the second routing point. After the research agent finishes, we check, did the original question also ask for analysis? Keywords like tell us or what does it mean? If yes, hand off to the analyst. If no, go straight to end. This gives us all three paths in one graph. Finally, the graph wiring. Research agent, analysis agent, and tools as nodes. The router at start. Conditional edges after the research agent. Tools loop back to the researcher. Analyst always goes to end. Compile with memory. And three test questions, one for each path. Let's save and run it. Here we go! Question 1. What was the gold price yesterday? Watch the routing. Router says, data needed, research agent. Research agent gathers data. Twice. Once to request the tool, once to see the result. And then, data delivered, no analysis needed, straight to end. The analyst never ran. Pure data question, pure data answer. Question 2. What is the current gold price and what does it tell us? Router sends it to research agent again. Data gathered. But now... Research complete. Handoff to analysis agent. The analyst kicks in and generates a full market briefing. Look at the message count. The analyst sees everything the researcher collected. That's shared state in action. Question 3. Based on what we've discussed, Is gold a good investment? Analysis only, straight to analysis agent. No research, no tool calls. The analyst uses memory from questions one and two to give investment advice. Look at that message count. It's seen the entire conversation. Three questions, three different paths, one graph. That's multi-agent orchestration. Let's understand how the specialization works. Both agents use the same Claude model. The only difference is the system prompt. The researcher is told, gather data, present facts, no opinions. The analyst is told, interpret data, think like a financial analyst, be actionable. Same LLM, completely different output. And an important detail, the system prompt is not stored in the shared state. Each agent prepins its prompt fresh on every call. That way, the researcher's instructions never leak into the analyst's context and vice versa. Here's how agents communicate. There's one message list in the state, shared by all nodes. The researcher writes to it. The analyst reads from it. Tool results go into it. Everything is visible to everyone. But system prompts are separate. Each agent prepens its own prompt before calling Claude, but that prompt never enters the shared state. So the analyst sees the researcher's data, the gold price, the tool result, but not the researcher's instructions. Shared state for data, separate prompts for specialization. That's the pattern. Let's try it interactively. First, how much does an ounce of gold cost? Research agent only, data delivered, no analysis needed. Now, what does the price movement tell us about market sentiment? Research agent gathers data, then hands off to the analyst. Both agents working together. And finally, should I be buying or selling gold based on this? Straight to the analyst, no research needed. It uses memory from the previous questions. Three different questions. Three different paths, all in one conversation. That's the power of multi-agent orchestration. Here are the key concepts from today. Multiple agent nodes, system prompts, router, and sequential handoff. In tutorial six, each agent gets its own set of tools, not just one shared gold price fetcher. And the router becomes even more important in tutorial seven, where we add security-aware routing. The pattern you learn today, specialized agents communicating through shared state, is the foundation for everything that follows. In tutorial 6, we take multi-agent to the next level. In today's tutorial, the research agent had one tool and the analyst had none. In the next tutorial, each agent gets its own set of tools. The research agent might fetch gold prices and news headlines. The analysis agent might have access to a calculator and a report formatter. That's where multi-agent systems start to feel like real applications. Specialized agents with specialized toolkits, all coordinated by the graph. If this tutorial helped you build your first multi-agent system, hit subscribe so you don't miss tutorial 6. The code and the full written guide are linked in the description. I'll see you in the next one!
⚙️ Pipeline jobs
| Stage | Status | Att. | Updated | Error |
|---|---|---|---|---|
| download | done | 1/3 | 2026-07-20 12:03:23 | |
| transcribe | done | 1/3 | 2026-07-20 12:03:30 | |
| summarize | done | 1/3 | 2026-07-20 12:03:49 | |
| embed | done | 1/3 | 2026-07-20 12:03:50 |
📄 Описание YouTube
Показать
One agent doing everything? Time to build a team. In this hands-on tutorial, you'll build a LangGraph system where two specialised agents collaborate — a research agent gathers live gold price data, and an analysis agent interprets it and generates market insights. A router decides which agent handles each question, and a second decision point determines whether analysis is needed after research. What we cover: - Why specialisation beats one agent doing everything - Three paths through one graph: data only, data + analysis, analysis only - System prompts that give the same LLM completely different behaviour - A keyword-based router that directs questions to the right agent - Shared state vs separate prompts — how agents communicate without seeing each other's instructions - Memory across agents — the analyst uses data the researcher collected New concepts: Multiple agent nodes, system prompts, router, sequential handoff This is Tutorial 5 in the AI Orchestration from Zero series. ← Tutorial 7 (Security Fundamentals): https://youtu.be/YMQsCpsiP7I ← Tutorial 6 (Custom Tools + APIs): https://youtu.be/kv-jN4NVmtg ← Tutorial 5 (Multi-Agent Basics): https://youtu.be/nx6HaySGOlc ← Tutorial 4 (State and Memory): https://youtu.be/5UQcHi538-c ← Tutorial 3 (Tool-Using Agent): https://youtu.be/4eUdFquzulU ← Tutorial 2 (Setup + Hello World): https://youtu.be/uGmhG_zSWOs ← Tutorial 1 (Concepts): https://youtu.be/EgIULrnjsL8 📂 Code on GitHub: https://github.com/lngo/ai-orchestration-from-zero/tree/main/tutorial-05 ⏱️ Timestamps: 0:00 Introduction 0:24 Why multiple agents? 1:07 Three paths through the graph 2:01 Four new concepts 2:40 Writing the multi-agent code 6:04 Running the demo — three paths in action 7:41 How system prompts create specialisation 8:25 Shared state vs separate prompts 9:05 Interactive demo 10:00 Key concepts 10:38 What's next: Tutorial 6 11:08 Closing This series covers all three approaches to AI orchestration: → Phase 1 (Tutorials 2–7): Developer-controlled orchestration with LangGraph → Phase 2 (Tutorials 8–9): Autonomous agents with Claude Code → Phase 3 (Tutorials 10–11): LLM-as-orchestrator — agent teams and hybrid architectures 🔔 Subscribe for the full series: @AIForYourWork #LangGraph #MultiAgent #AIOrchestration #SystemPrompts #ClaudeAPI #PythonTutorial #AIForYourWork #BuildMoreHireLess #AgentRouter #AIAgentTeam