Multi-Agent Patterns

Nhiều agents hợp tác: Group Chat, Hand-off, Round Robin và khi nào nên dùng

Khi Nào Cần Multi-Agent?

Single agent đủ cho hầu hết tasks. Nhưng có những scenarios cần nhiều agents:

  • Chuyên môn hoá: Mỗi agent giỏi một lĩnh vực (code, design, research…)
  • Scale: Tasks quá lớn cho 1 agent
  • Giao tiếp tự nhiên: Agents thảo luận để đạt kết quả tốt hơn
  • Checks & balances: Agent A kiểm tra output của Agent B

Patterns Chính

1. Sequential (Hand-off)

Agents truyền kết quả cho nhau theo chuỗi:

Agent A → Agent B → Agent C → Final Output
import { generateText, tool } from "ai";
import { openai } from "@ai-sdk/openai";

// Agent 1: Researcher
async function researcher(topic: string) {
  const result = await generateText({
    model: openai("gpt-4o"),
    system: "Bạn là nhà nghiên cứu. Tìm thông tin chi tiết về topic.",
    tools: { searchWeb },
    maxSteps: 5,
    prompt: `Nghiên cứu: ${topic}`
  });
  return result.text;
}

// Agent 2: Writer
async function writer(research: string) {
  const result = await generateText({
    model: openai("gpt-4o"),
    system: "Bạn là tech writer. Viết bài từ research data.",
    prompt: `Viết blog từ research sau:\n${research}`
  });
  return result.text;
}

// Agent 3: Editor
async function editor(draft: string) {
  const result = await generateText({
    model: openai("gpt-4o"),
    system: "Bạn là editor. Review và cải thiện bài viết.",
    prompt: `Review và sửa:\n${draft}`
  });
  return result.text;
}

// Pipeline
async function contentPipeline(topic: string) {
  const research = await researcher(topic);
  const draft = await writer(research);
  const finalArticle = await editor(draft);
  return finalArticle;
}

2. Parallel (Concurrent)

Agents làm việc đồng thời, kết quả được tổng hợp:

async function parallelAnalysis(codebase: string) {
  const [security, performance, accessibility] = await Promise.all([
    // Security Agent
    generateText({
      model: openai("gpt-4o"),
      system: "Bạn là security auditor. Tìm vulnerabilities.",
      prompt: `Audit security:\n${codebase}`
    }),
    // Performance Agent
    generateText({
      model: openai("gpt-4o"),
      system: "Bạn là performance engineer. Tìm bottlenecks.",
      prompt: `Audit performance:\n${codebase}`
    }),
    // Accessibility Agent
    generateText({
      model: openai("gpt-4o"),
      system: "Bạn là accessibility expert. Kiểm tra WCAG compliance.",
      prompt: `Audit accessibility:\n${codebase}`
    })
  ]);

  // Tổng hợp kết quả
  return { security: security.text, performance: performance.text, accessibility: accessibility.text };
}

3. Group Chat

Nhiều agents thảo luận với nhau, giống cuộc họp:

interface AgentConfig {
  name: string;
  role: string;
  system: string;
}

async function groupChat(
  agents: AgentConfig[],
  topic: string,
  maxRounds: number = 5
) {
  const messages: { agent: string; content: string }[] = [];

  for (let round = 0; round < maxRounds; round++) {
    for (const agent of agents) {
      const context = messages
        .map(m => `[${m.agent}]: ${m.content}`)
        .join("\n");

      const response = await generateText({
        model: openai("gpt-4o-mini"),
        system: `${agent.system}
Bạn đang trong cuộc thảo luận nhóm.
Phản hồi ngắn gọn, tập trung vào quan điểm của role bạn.
Nếu đồng thuận đã đạt được, nói "CONSENSUS".`,
        prompt: `Topic: ${topic}\n\nLịch sử thảo luận:\n${context}\n\nPhản hồi của bạn:`
      });

      messages.push({ agent: agent.name, content: response.text });

      // Dừng nếu đồng thuận
      if (response.text.includes("CONSENSUS")) {
        return { messages, consensus: true };
      }
    }
  }

  return { messages, consensus: false };
}

// Sử dụng
const result = await groupChat(
  [
    {
      name: "Frontend Dev",
      role: "frontend",
      system: "Bạn là frontend developer chuyên React."
    },
    {
      name: "Backend Dev",
      role: "backend",
      system: "Bạn là backend developer chuyên Node.js."
    },
    {
      name: "DevOps",
      role: "devops",
      system: "Bạn là DevOps engineer chuyên deployment."
    }
  ],
  "Nên dùng SSR hay CSR cho ứng dụng e-commerce?"
);

4. Supervisor Pattern

Một agent điều phối các agents khác:

async function supervisor(task: string) {
  // Supervisor phân tích task và assign subtasks
  const { object: plan } = await generateObject({
    model: openai("gpt-4o"),
    schema: z.object({
      subtasks: z.array(z.object({
        description: z.string(),
        assignTo: z.enum(["researcher", "coder", "reviewer"]),
        priority: z.number()
      }))
    }),
    prompt: `Phân tích task và assign cho agents phù hợp: ${task}`
  });

  // Thực thi theo priority
  const results = [];
  for (const subtask of plan.subtasks.sort((a, b) => a.priority - b.priority)) {
    const agentFn = getAgent(subtask.assignTo);
    const result = await agentFn(subtask.description);
    results.push({ subtask: subtask.description, result });
  }

  return results;
}

Multi-Agent Với CrewAI (Python)

from crewai import Agent, Task, Crew, Process

# Agents
pm = Agent(
    role="Product Manager",
    goal="Xác định requirements và ưu tiên features",
    llm="gpt-4o-mini"
)

dev = Agent(
    role="Senior Developer",
    goal="Implement features theo requirements",
    llm="gpt-4o-mini"
)

qa = Agent(
    role="QA Engineer",
    goal="Test và tìm bugs trong implementation",
    llm="gpt-4o-mini"
)

# Sequential process
crew = Crew(
    agents=[pm, dev, qa],
    tasks=[
        Task(description="Phân tích requirements", agent=pm),
        Task(description="Implement solution", agent=dev),
        Task(description="Test và review", agent=qa)
    ],
    process=Process.sequential  # hoặc Process.hierarchical
)

Chọn Pattern Nào?

ScenarioPattern
Content pipeline (research → write → edit)Sequential
Code audit (security + performance + a11y)Parallel
Design review cần nhiều góc nhìnGroup Chat
Task phức tạp cần điều phốiSupervisor
Simple automation chainSequential

Tổng Kết

  • Sequential: Pass kết quả qua chain of agents
  • Parallel: Agents làm việc đồng thời, tổng hợp kết quả
  • Group Chat: Agents thảo luận để đạt consensus
  • Supervisor: Một agent điều phối các agents khác
  • Bắt đầu với single agent, chỉ dùng multi-agent khi thực sự cần