Tutorial 2: Multi-Agent Collaboration
β±οΈ Time: 30 minutes | π― Goal: Build a researcher-writer team
Now letβs create a team of agents that work together! Youβll build a system where XAgent coordinates specialist agents β a researcher gathers information and a writer creates content. This introduces the powerful concept of multi-agent collaboration.
What Youβll Learn
Section titled βWhat Youβll Learnβ- How XAgent coordinates specialist agents
- Using different agent modes
- Building collaborative workflows
- Managing multi-step tasks
Prerequisites
Section titled βPrerequisitesβ- Completed Tutorial 1: Your First Agent
- Understanding of basic Viber concepts
- An LLM API key
Understanding Multi-Agent Architecture
Section titled βUnderstanding Multi-Agent ArchitectureβIn Viber, XAgent acts as the project manager. It coordinates specialist agents:
User β XAgent β [Researcher, Writer, Developer, ...] β Task CompletionThe specialist agents include:
| Agent | Role |
|---|---|
| Researcher | Gathers information and sources |
| Writer | Creates content and documentation |
| Developer | Writes and reviews code |
| Reviewer | Provides quality assurance |
| Web Designer | Creates HTML/CSS experiences |
Step 1: Project Setup
Section titled βStep 1: Project SetupβCreate a new project:
mkdir research-writer-teamcd research-writer-teampnpm initpnpm add viber dotenvpnpm add -D typescript tsx @types/nodeCreate your project structure:
research-writer-team/βββ src/β βββ index.ts # Main applicationβββ .env # API keyβββ package.jsonβββ tsconfig.jsonStep 2: Create a Collaborative Workflow
Section titled βStep 2: Create a Collaborative WorkflowβCreate src/index.ts:
import "dotenv/config";import { XAgent } from "viber";
async function main() { console.log("βοΈ Research & Writing Team Demo"); console.log("Watch as XAgent coordinates specialist agents!\n"); console.log("β".repeat(50));
// Create a workspace for our research project const xAgent = await XAgent.start( "Research and write an article about sustainable energy" ); const space = xAgent.getSpace();
console.log(`β¨ Created Space: ${space.spaceId}`); console.log(`π Goal: ${space.goal}\n`);
// Phase 1: Research console.log("π Phase 1: Research"); console.log("β".repeat(40));
const researchStream = await xAgent.streamText({ messages: [ { role: "user", content: `Please research the current state of sustainable energy.Focus on:1. Solar and wind energy trends2. Recent breakthroughs3. Key statistics
Gather comprehensive information for an article.`, }, ], metadata: { mode: "agent", requestedAgent: "X" }, });
for await (const chunk of researchStream.textStream) { process.stdout.write(chunk); } console.log("\n");
// Phase 2: Writing console.log("\nβοΈ Phase 2: Writing"); console.log("β".repeat(40));
const writeStream = await xAgent.streamText({ messages: [ { role: "user", content: `Based on the research you've gathered, write a 500-word article about sustainable energy.Include:- An engaging introduction- Key findings from your research- Future outlook- A compelling conclusion`, }, ], metadata: { mode: "agent", requestedAgent: "X" }, });
for await (const chunk of writeStream.textStream) { process.stdout.write(chunk); } console.log("\n");
// Phase 3: Review console.log("\nπ Phase 3: Review"); console.log("β".repeat(40));
const reviewStream = await xAgent.streamText({ messages: [ { role: "user", content: "Review the article you just wrote. Check for clarity, flow, and accuracy. Suggest any improvements.", }, ], metadata: { mode: "agent", requestedAgent: "X" }, });
for await (const chunk of reviewStream.textStream) { process.stdout.write(chunk); } console.log("\n");
// Save the workspace await space.persistState();
console.log("β".repeat(50)); console.log("π Collaboration complete!"); console.log(`πΎ Space saved: ${space.spaceId}`); console.log( "\nYou can resume this workspace later to continue refining the article." );}
main().catch(console.error);Step 3: Run the Collaborative Team
Section titled βStep 3: Run the Collaborative TeamβAdd scripts to package.json:
{ "type": "module", "scripts": { "start": "tsx src/index.ts" }}Run the team:
pnpm startYouβll see something like:
βοΈ Research & Writing Team DemoWatch as XAgent coordinates specialist agents!
βββββββββββββββββββββββββββββββββββββββββββββββββββ¨ Created Space: space_abc123xyzπ Goal: Research and write an article about sustainable energy
π Phase 1: ResearchββββββββββββββββββββββββββββββββββββββββI'll research the current state of sustainable energy for you...
[XAgent gathers information and presents findings]
βοΈ Phase 2: WritingββββββββββββββββββββββββββββββββββββββββBased on the research, I'll now write a comprehensive article...
[XAgent creates the article]
π Phase 3: ReviewββββββββββββββββββββββββββββββββββββββββLet me review the article for clarity and accuracy...
[XAgent provides feedback]
ββββββββββββββββββββββββββββββββββββββββββββββββββπ Collaboration complete!πΎ Space saved: space_abc123xyzStep 4: Interactive Collaboration
Section titled βStep 4: Interactive CollaborationβCreate an interactive version in src/interactive.ts:
import "dotenv/config";import { XAgent, Space } from "viber";import * as readline from "readline";
const rl = readline.createInterface({ input: process.stdin, output: process.stdout,});
function prompt(question: string): Promise<string> { return new Promise((resolve) => { rl.question(question, resolve); });}
async function main() { console.log("π€ Interactive Multi-Agent Collaboration\n");
// Check for existing space const existingSpaceId = process.env.SPACE_ID;
let xAgent: XAgent; let space: Space;
if (existingSpaceId) { console.log(`π Found existing space: ${existingSpaceId}`); const resume = await prompt("Resume previous session? (y/n): ");
if (resume.toLowerCase() === "y") { xAgent = await XAgent.resume(existingSpaceId); space = xAgent.getSpace(); console.log(`\nβ¨ Resumed: ${space.name}`); console.log(`π Previous messages: ${space.history.messages.length}`); } else { const result = await createNewSpace(); xAgent = result.xAgent; space = result.space; } } else { const result = await createNewSpace(); xAgent = result.xAgent; space = result.space; }
console.log("\nπ‘ Commands:"); console.log(" - Type your request to collaborate with XAgent"); console.log(" - Type 'status' to see workspace info"); console.log(' - Type "quit" to save and exit\n');
// Main interaction loop while (true) { const input = await prompt("\nπ You: ");
if (input.toLowerCase() === "quit") { console.log("\nπΎ Saving workspace..."); await space.persistState(); console.log(`β
Saved! Space ID: ${space.spaceId}`); break; }
if (input.toLowerCase() === "status") { console.log("\nπ Workspace Status:"); console.log(` Space: ${space.name}`); console.log(` Goal: ${space.goal}`); console.log(` Messages: ${space.history.messages.length}`); continue; }
if (!input.trim()) continue;
console.log("\nπ€ XAgent: ");
const stream = await xAgent.streamText({ messages: [{ role: "user", content: input }], metadata: { mode: "agent", requestedAgent: "X" }, });
for await (const chunk of stream.textStream) { process.stdout.write(chunk); } console.log(""); }
rl.close();}
async function createNewSpace(): Promise<{ xAgent: XAgent; space: Space }> { const topic = await prompt("What would you like to work on? "); const xAgent = await XAgent.start(topic || "Research and writing project"); const space = xAgent.getSpace();
console.log(`\n⨠Created new workspace: ${space.spaceId}`); return { xAgent, space };}
main().catch(console.error);Add the script:
{ "scripts": { "start": "tsx src/index.ts", "interactive": "tsx src/interactive.ts" }}Run:
pnpm interactiveπ Congratulations!
Section titled βπ Congratulations!βYouβve built your first multi-agent collaborative system! Hereβs what you accomplished:
β
Coordinated specialist agents through XAgent
β
Built multi-phase workflows (research β write β review)
β
Created interactive sessions with persistent context
β
Observed real-time collaboration between AI agents
π‘ Key Concepts Learned
Section titled βπ‘ Key Concepts Learnedβ- XAgent Coordination: XAgent manages the overall workflow and delegates to specialists
- Context Preservation: All phases share context within the Space
- Iterative Refinement: Work improves through multiple passes
- Persistent Collaboration: Resume work at any time
π Understanding the Collaboration
Section titled βπ Understanding the CollaborationβWhy This Works
Section titled βWhy This Worksβ- Unified Context: All agents work within the same Space
- Accumulated Knowledge: Each phase builds on previous work
- Natural Workflow: Research β Write β Review mirrors how humans work
- Persistent State: Everything is saved automatically
Real-World Applications
Section titled βReal-World Applicationsβ- Content Creation: Blog posts, documentation, marketing copy
- Research Projects: Gather information, analyze, synthesize
- Code Development: Plan, implement, review, refine
- Customer Service: Triage, respond, follow-up
π Whatβs Next?
Section titled βπ Whatβs Next?βYour agents can collaborate, but theyβre still limited to built-in capabilities. In Tutorial 3: Custom Tools, youβll learn how to give your agents superpowers by creating custom tools that connect to external APIs and services.
Preview: What Youβll Build Next
Section titled βPreview: What Youβll Build Nextβ- Custom search tool that fetches real data
- File operations for saving artifacts
- External API integration for enhanced capabilities
- Tool permissions and security
π§ Troubleshooting
Section titled βπ§ TroubleshootingβAgents not responding well?
- Try more specific prompts
- Break complex tasks into smaller steps
- Provide clear context about what you need
Workflow getting stuck?
- Check your API key and quota
- Verify network connectivity
- Try simpler requests to diagnose
Want to experiment?
- Try different types of content (technical docs, creative writing)
- Add more phases (outline β draft β revise β polish)
- Create domain-specific workflows
Ready to give your agents superpowers? Continue to Tutorial 3: Custom Tools! π οΈ