惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
K
Kaspersky official blog
T
The Exploit Database - CXSecurity.com
NISL@THU
NISL@THU
AWS News Blog
AWS News Blog
V2EX - 技术
V2EX - 技术
Google DeepMind News
Google DeepMind News
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
S
Security @ Cisco Blogs
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recent Commits to openclaw:main
Recent Commits to openclaw:main
J
Java Code Geeks
Microsoft Azure Blog
Microsoft Azure Blog
Attack and Defense Labs
Attack and Defense Labs
Jina AI
Jina AI
The Last Watchdog
The Last Watchdog
W
WeLiveSecurity
H
Help Net Security
V
Visual Studio Blog
宝玉的分享
宝玉的分享
C
Cybersecurity and Infrastructure Security Agency CISA
T
Threat Research - Cisco Blogs
IT之家
IT之家
Hugging Face - Blog
Hugging Face - Blog
Latest news
Latest news
T
Tor Project blog
I
Intezer
美团技术团队
GbyAI
GbyAI
T
Tailwind CSS Blog
Last Week in AI
Last Week in AI
博客园 - 三生石上(FineUI控件)
Google DeepMind News
Google DeepMind News
Scott Helme
Scott Helme
Y
Y Combinator Blog
博客园 - 司徒正美
T
Tenable Blog
O
OpenAI News
N
News and Events Feed by Topic
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
V
Vulnerabilities – Threatpost
P
Palo Alto Networks Blog
博客园 - 聂微东
酷 壳 – CoolShell
酷 壳 – CoolShell
D
Darknet – Hacking Tools, Hacker News & Cyber Security
T
Threatpost
Google Online Security Blog
Google Online Security Blog
Apple Machine Learning Research
Apple Machine Learning Research
云风的 BLOG
云风的 BLOG
Help Net Security
Help Net Security

MarkTechPost

A Coding Implementation of End-to-End Brain Decoding from MEG Signals Using NeuralSet and Deep Learning for Predicting Linguistic Features Meta Introduces Autodata: An Agentic Framework That Turns AI Models into Autonomous Data Scientists for High-Quality Training Data Creation A Coding Guide on LLM Post Training with TRL from Supervised Fine Tuning to DPO and GRPO Reasoning Qwen AI Releases Qwen-Scope: An Open-Source Sparse AutoEncoders (SAE) Suite That Turns LLM Internal Features into Practical Development Tools A Coding Deep Dive into Agentic UI, Generative UI, State Synchronization, and Interrupt-Driven Approval Flows Moonshot AI Open-Sources FlashKDA: CUTLASS Kernels for Kimi Delta Attention with Variable-Length Batching and H20 Benchmarks Microsoft Research’s World-R1 Uses Flow-GRPO and 3D-Aware Rewards to Inject Geometric Consistency Into Wan 2.1 Without Architectural Changes A Coding Implementation on Pyright Type Checking Covering Generics, Protocols, Strict Mode, Type Narrowing, and Modern Python Typing IBM Releases Two Granite Speech 4.1 2B Models: Autoregressive ASR with Translation and Non-Autoregressive Editing for Fast Inference Top 10 KV Cache Compression Techniques for LLM Inference: Reducing Memory Overhead Across Eviction, Quantization, and Low-Rank Methods Qwen Team Releases FlashQLA: a High-Performance Linear Attention Kernel Library That Achieves Up to 3× Speedup on NVIDIA Hopper GPUs Step by Step Guide to Build a Complete PII Detection and Redaction Pipeline with OpenAI Privacy Filter Meta FAIR Releases NeuralSet: A Python Package for Neuro-AI That Supports fMRI, M/EEG, Spikes, and HuggingFace Embeddings smol-audio: A Colab-Friendly Notebook Collection for Fine-Tuning Whisper, Parakeet, Voxtral, Granite Speech, and Audio Flamingo 3 A Coding Implementation on Document Parsing Benchmarking with LlamaIndex ParseBench Using Python, Hugging Face, and Evaluation Metrics Poolside AI Introduces Laguna XS.2 and M.1: Agentic Coding Models Reaching 68.2% and 72.5% on SWE-bench Verified How to Build Traceable and Evaluated LLM Workflows Using Promptflow, Prompty, and OpenAI OpenAI Releases Privacy Filter: A 1.5B-Parameter Open-Source PII Redaction Model with 50M Active Parameters Top 10 Physical AI Models Powering Real-World Robots in 2026 How to Build a Lightweight Vision-Language-Action-Inspired Embodied Agent with Latent World Modeling and Model Predictive Control Meet Talkie-1930: A 13B Open-Weight LLM Trained on Pre-1931 English Text for Historical Reasoning and Generalization Research Build a Reinforcement Learning Powered Agent that Learns to Retrieve Relevant Long-Term Memories for Accurate LLM Question Answering OpenMOSS Releases MOSS-Audio: An Open-Source Foundation Model for Speech, Sound, Music, and Time-Aware Audio Reasoning Meta AI Releases Sapiens2: A High-Resolution Human-Centric Vision Model for Pose, Segmentation, Normals, Pointmap, and Albedo The LoRA Assumption That Breaks in Production How to Build a Fully Searchable AI Knowledge Base with OpenKB, OpenRouter, and Llama How to Build Smarter Multilingual Text Wrapping with BudouX Through Parsing, HTML Rendering, Model Introspection, and Toy Training Top 7 Benchmarks That Actually Matter for Agentic Reasoning in Large Language Models RAG Without Vectors: How PageIndex Retrieves by Reasoning A Coding Tutorial on Datashader on Rendering Massive Datasets with High-Performance Python Visual Analytics xAI Launches grok-voice-think-fast-1.0: Topping τ-voice Bench at 67.3%, Outperforming Gemini, GPT Realtime, and More A Coding Implementation on kvcached for Elastic KV Cache Memory, Bursty LLM Serving, and Multi-Model GPU Sharing Google DeepMind Introduces Vision Banana: An Instruction-Tuned Image Generator That Beats SAM 3 on Segmentation and Depth Anything V3 on Metric Depth Estimation Meet GitNexus: An Open-Source MCP-Native Knowledge Graph Engine That Gives Claude Code and Cursor Full Codebase Structural Awareness A Coding Implementation on Deepgram Python SDK for Transcription, Text-to-Speech, Async Audio Processing, and Text Intelligence A Coding Implementation on Microsoft’s OpenMementos with Trace Structure Analysis, Context Compression, and Fine-Tuning Data Preparation DeepSeek AI Releases DeepSeek-V4: Compressed Sparse Attention and Heavily Compressed Attention Enable One-Million-Token Contexts Google DeepMind Introduces Decoupled DiLoCo: An Asynchronous Training Architecture Achieving 88% Goodput Under High Hardware Failure Rates Mend Releases AI Security Governance Framework: Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model Mend.io Releases AI Security Governance Framework Covering Asset Inventory, Risk Tiering, AI Supply Chain Security, and Maturity Model OpenAI Releases GPT-5.5, a Fully Retrained Agentic Model That Scores 82.7% on Terminal-Bench 2.0 and 84.9% on GDPval A Coding Tutorial on OpenMythos on Recurrent-Depth Transformers with Depth Extrapolation, Adaptive Computation, and Mixture-of-Experts Routing Google Cloud AI Research Introduces ReasoningBank: A Memory Framework that Distills Reasoning Strategies from Agent Successes and Failures Xiaomi Releases MiMo-V2.5-Pro and MiMo-V2.5: Matching Frontier Model Benchmarks at Significantly Lower Token Cost Alibaba Qwen Team Releases Qwen3.6-27B: A Dense Open-Weight Model Outperforming 397B MoE on Agentic Coding Benchmarks A Detailed Implementation on Equinox with JAX Native Modules, Filtered Transforms, Stateful Layers, and End-to-End Training Workflows Next Leap to Harness Engineering: JiuwenClaw Pioneers ‘Coordination Engineering’ Photon Releases Spectrum: An Open-Source TypeScript Framework that Deploys AI Agents Directly to iMessage, WhatsApp, and Telegram OpenAI Open-Sources Euphony: A Browser-Based Visualization Tool for Harmony Chat Data and Codex Session Logs Hugging Face Releases ml-intern: An Open-Source AI Agent that Automates the LLM Post-Training Workflow A Coding Implementation to Build a Conditional Bayesian Hyperparameter Optimization Pipeline with Hyperopt, TPE, and Early Stopping Google Introduces Simula: A Reasoning-First Framework for Generating Controllable, Scalable Synthetic Datasets Across Specialized AI Domains A Coding Implementation on Qwen 3.6-35B-A3B Covering Multimodal Inference, Thinking Control, Tool Calling, MoE Routing, RAG, and Session Persistence Moonshot AI Releases Kimi K2.6 with Long-Horizon Coding, Agent Swarm Scaling to 300 Sub-Agents and 4,000 Coordinated Steps A Coding Implementation on Microsoft’s Phi-4-Mini for Quantized Inference Reasoning Tool Use RAG and LoRA Fine-Tuning OpenAI Scales Trusted Access for Cyber Defense With GPT-5.4-Cyber: a Fine-Tuned Model Built for Verified Security Defenders Moonshot AI and Tsinghua Researchers Propose PrfaaS: A Cross-Datacenter KVCache Architecture that Rethinks How LLMs are Served at Scale Meet OpenMythos: An Open-Source PyTorch Reconstruction of Claude Mythos Where 770M Parameters Match a 1.3B Transformer How TabPFN Leverages In-Context Learning to Achieve Superior Accuracy on Tabular Datasets Compared to Random Forest and CatBoost A Coding Implementation to Build an AI-Powered File Type Detection and Security Analysis Pipeline with Magika and OpenAI NVIDIA Releases Ising: the First Open Quantum AI Model Family for Hybrid Quantum-Classical Systems xAI Launches Standalone Grok Speech-to-Text and Text-to-Speech APIs, Targeting Enterprise Voice Developers A Coding Tutorial for Running PrismML Bonsai 1-Bit LLM on CUDA with GGUF, Benchmarking, Chat, JSON, and RAG A Coding Guide for Property-Based Testing Using Hypothesis with Stateful, Differential, and Metamorphic Test Design Anthropic Releases Claude Opus 4.7: A Major Upgrade for Agentic Coding, High-Resolution Vision, and Long-Horizon Autonomous Tasks Google AI Releases Auto-Diagnose: An Large Language Model LLM-Based System to Diagnose Integration Test Failures at Scale A End-to-End Coding Guide to Running OpenAI GPT-OSS Open-Weight Models with Advanced Inference Workflows Top 19 AI Red Teaming Tools (2026): Secure Your ML Models A Coding Guide to Build a Production-Grade Background Task Processing System Using Huey with SQLite, Scheduling, Retries, Pipelines, and Concurrency Control Qwen Team Open-Sources Qwen3.6-35B-A3B: A Sparse MoE Vision-Language Model with 3B Active Parameters and Agentic Coding Capabilities OpenAI Launches GPT-Rosalind: Its First Life Sciences AI Model Built to Accelerate Drug Discovery and Genomics Research Building Transformer-Based NQS for Frustrated Spin Systems with NetKet UCSD and Together AI Research Introduces Parcae: A Stable Architecture for Looped Language Models That Achieves the Quality of a Transformer Twice the Size How to Build a Universal Long-Term Memory Layer for AI Agents Using Mem0 and OpenAI A Coding Implementation to Build Multi-Agent AI Systems with SmolAgents Using Code Execution, Tool Calling, and Dynamic Orchestration A Technical Deep Dive into the Essential Stages of Modern Large Language Model Training, Alignment, and Deployment Google AI Launches Gemini 3.1 Flash TTS: A New Benchmark in Expressive and Controllable AI Voice Google DeepMind Releases Gemini Robotics-ER 1.6: Bringing Enhanced Embodied Reasoning and Instrument Reading to Physical AI Google Launches ‘Skills’ in Chrome: Turning Reusable AI Prompts into One-Click Browser Workflows A Coding Implementation of Crawl4AI for Web Crawling, Markdown Generation, JavaScript Execution, and LLM-Based Structured Extraction TinyFish AI Releases Full Web Infrastructure Platform for AI Agents: Search, Fetch, Browser, and Agent Under One API Key NVIDIA and the University of Maryland Researchers Released Audio Flamingo Next (AF-Next): A Super Powerful and Open Large Audio-Language Model A Hands-On Coding Tutorial for Microsoft VibeVoice Covering Speaker-Aware ASR, Real-Time TTS, and Speech-to-Speech Pipelines Meta AI and KAUST Researchers Propose Neural Computers That Fold Computation, Memory, and I/O Into One Learned Model A Coding Implementation of MolmoAct for Depth-Aware Spatial Reasoning, Visual Trajectory Tracing, and Robotic Action Prediction MiniMax Just Open Sourced MiniMax M2.7: A Self-Evolving Agent Model that Scores 56.22% on SWE-Pro and 57.0% on Terminal Bench 2 Liquid AI Releases LFM2.5-VL-450M: a 450M-Parameter Vision-Language Model with Bounding Box Prediction, Multilingual Support, and Sub-250ms Edge Inference Researchers from MIT, NVIDIA, and Zhejiang University Propose TriAttention: A KV Cache Compression Method That Matches Full Attention at 2.5× Higher Throughput How to Build a Secure Local-First Agent Runtime with OpenClaw Gateway, Skills, and Controlled Tool Execution How Knowledge Distillation Compresses Ensemble Intelligence into a Single Deployable AI Model Alibaba’s Tongyi Lab Releases VimRAG: a Multimodal RAG Framework that Uses a Memory Graph to Navigate Massive Visual Contexts A Coding Guide to Markerless 3D Human Kinematics with Pose2Sim, RTMPose, and OpenSim NVIDIA Releases AITune: An Open-Source Inference Toolkit That Automatically Finds the Fastest Inference Backend for Any PyTorch Model Five AI Compute Architectures Every Engineer Should Know: CPUs, GPUs, TPUs, NPUs, and LPUs Compared An End-to-End Coding Guide to NVIDIA KVPress for Long-Context LLM Inference, KV Cache Compression, and Memory-Efficient Generation Meta Superintelligence Lab Releases Muse Spark: A Multimodal Reasoning Model With Thought Compression and Parallel Agents Sigmoid vs ReLU Activation Functions: The Inference Cost of Losing Geometric Context A Coding Guide to Build Advanced Document Intelligence Pipelines with Google LangExtract, OpenAI Models, Structured Extraction, and Interactive Visualization Google AI Research Introduces PaperOrchestra: A Multi-Agent Framework for Automated AI Research Paper Writing A Comprehensive Implementation Guide to ModelScope for Model Search, Inference, Fine-Tuning, Evaluation, and Export
How to Design a Production-Grade CAMEL Multi-Agent System with Planning, Tool Use, Self-Consistency, and Critique-Driven Refinement
Asif Razzaq · 2026-04-23 · via MarkTechPost

In this tutorial, we implement an advanced agentic AI system using the CAMEL framework, orchestrating multiple specialized agents to collaboratively solve a complex task. We design a structured multi-agent pipeline consisting of a planner, researcher, writer, critic, and rewriter, each with clearly defined responsibilities and schema-constrained outputs. We integrate tool usage, self-consistency sampling, structured validation with Pydantic, and iterative critique-driven refinement to build a robust, research-backed technical brief generator. Through this process, we demonstrate how modern agent architectures combine planning, reasoning, external tool interaction, and autonomous quality control within a single coherent workflow.

import os, sys, re, json, subprocess
from typing import List, Dict, Any, Optional, Tuple


def _pip_install(pkgs: List[str]):
   subprocess.check_call([sys.executable, "-m", "pip", "install", "-q", "-U"] + pkgs)


_pip_install(["camel-ai[web_tools]~=0.2", "pydantic>=2.7", "rich>=13.7"])


from pydantic import BaseModel, Field
from rich.console import Console
from rich.panel import Panel
from rich.table import Table


console = Console()


def _get_colab_secret(name: str) -> Optional[str]:
   try:
       from google.colab import userdata
       v = userdata.get(name)
       return v if v else None
   except Exception:
       return None


def ensure_openai_key():
   if os.getenv("OPENAI_API_KEY"):
       return
   v = _get_colab_secret("OPENAI_API_KEY")
   if v:
       os.environ["OPENAI_API_KEY"] = v
       return
   try:
       from getpass import getpass
       k = getpass("Enter OPENAI_API_KEY (input hidden): ").strip()
       if k:
           os.environ["OPENAI_API_KEY"] = k
   except Exception:
       pass


ensure_openai_key()
if not os.getenv("OPENAI_API_KEY"):
   raise RuntimeError("OPENAI_API_KEY is not set. Add it via Colab Secrets (OPENAI_API_KEY) or paste it when prompted.")

We set up the execution environment and install all required dependencies directly within Colab. We securely configure the OpenAI API key using either Colab secrets or manual input. We also initialize the console utilities that allow us to render structured outputs cleanly during execution.

from camel.models import ModelFactory
from camel.types import ModelPlatformType, ModelType
from camel.agents import ChatAgent
from camel.toolkits import SearchToolkit


def make_model(temperature: float = 0.2):
   return ModelFactory.create(
       model_platform=ModelPlatformType.OPENAI,
       model_type=ModelType.GPT_4O,
       model_config_dict={"temperature": float(temperature)},
   )


def strip_code_fences(s: str) -> str:
   s = s.strip()
   s = re.sub(r"^```(?:json)?\s*", "", s, flags=re.IGNORECASE)
   s = re.sub(r"\s*```$", "", s)
   return s.strip()


def extract_first_json_object(s: str) -> str:
   s2 = strip_code_fences(s)
   start = None
   stack = []
   for i, ch in enumerate(s2):
       if ch == "{":
           if start is None:
               start = i
           stack.append("{")
       elif ch == "}":
           if stack:
               stack.pop()
               if not stack and start is not None:
                   return s2[start:i+1]
   m = re.search(r"\{[\s\S]*\}", s2)
   if m:
       return m.group(0)
   return s2

We import the core CAMEL components and define the model factory used across all agents. We implement helper utilities to clean and extract JSON reliably from LLM responses. This ensures that our multi-agent pipeline remains structurally robust even when models return formatted text.

class PlanTask(BaseModel):
   id: str = Field(..., min_length=1)
   title: str = Field(..., min_length=1)
   objective: str = Field(..., min_length=1)
   deliverable: str = Field(..., min_length=1)
   tool_hints: List[str] = Field(default_factory=list)
   risks: List[str] = Field(default_factory=list)


class Plan(BaseModel):
   goal: str
   assumptions: List[str] = Field(default_factory=list)
   tasks: List[PlanTask]
   success_criteria: List[str] = Field(default_factory=list)


class EvidenceItem(BaseModel):
   query: str
   notes: str
   key_points: List[str] = Field(default_factory=list)


class Critique(BaseModel):
   score_0_to_10: float = Field(..., ge=0, le=10)
   strengths: List[str] = Field(default_factory=list)
   issues: List[str] = Field(default_factory=list)
   fix_plan: List[str] = Field(default_factory=list)


class RunConfig(BaseModel):
   goal: str
   max_tasks: int = 5
   max_searches_per_task: int = 2
   max_revision_rounds: int = 1
   self_consistency_samples: int = 2


DEFAULT_GOAL = "Create a concise, evidence-backed technical brief explaining CAMEL (the multi-agent framework), its core abstractions, and a practical recipe to build a tool-using multi-agent pipeline (planner/researcher/writer/critic) with safeguards."


cfg = RunConfig(goal=DEFAULT_GOAL)


search_tool = SearchToolkit().search_duckduckgo

We define all structured schemas using Pydantic for planning, evidence, critique, and runtime configuration. We formalize the agent communication protocol so that every step is validated and typed. This allows us to transform free-form LLM outputs into predictable, production-ready data structures.

planner_system = (
   "You are a senior agent architect. Produce a compact, high-leverage plan for achieving the goal.\n"
   "Return ONLY valid JSON that matches this schema:\n"
   "{{\"goal\": \"...\", \"assumptions\": [\"...\"], \"tasks\": "
   "[{{\"id\": \"T1\", \"title\": \"...\", \"objective\": \"...\", \"deliverable\": \"...\", "
   "\"tool_hints\": [\"...\"], \"risks\": [\"...\"]}}], "
   "\"success_criteria\": [\"...\"]}}\n"
   "Constraints: tasks length <= {max_tasks}. Each task should be executable with web search + reasoning."
).format(max_tasks=cfg.max_tasks)


planner = ChatAgent(system_message=planner_system, model=make_model(0.1))


researcher = ChatAgent(
   system_message=(
       "You are a meticulous research agent. Use the web search tool when useful.\n"
       "You must:\n"
       "- Search for authoritative sources (docs, official repos) first.\n"
       "- Write notes that are directly relevant to the task objective.\n"
       "- Return ONLY valid JSON:\n"
       "{\"query\": \"...\", \"notes\": \"...\", \"key_points\": [\"...\"]}\n"
       "Do not include markdown code fences."
   ),
   model=make_model(0.2),
   tools=[search_tool],
)


writer = ChatAgent(
   system_message=(
       "You are a technical writer agent. You will be given a goal, a plan, and evidence notes.\n"
       "Write a deliverable that is clear, actionable, and concise.\n"
       "Include:\n"
       "- A crisp overview\n"
       "- Key abstractions and how they connect\n"
       "- A practical implementation recipe\n"
       "- Minimal caveats/limitations\n"
       "Do NOT fabricate citations. If evidence is thin, state uncertainty.\n"
       "Return plain text only."
   ),
   model=make_model(0.3),
)


critic = ChatAgent(
   system_message=(
       "You are a strict reviewer. Evaluate the draft against the goal, correctness, and completeness.\n"
       "Return ONLY valid JSON:\n"
       "{\"score_0_to_10\": 0.0, \"strengths\": [\"...\"], \"issues\": [\"...\"], \"fix_plan\": [\"...\"]}\n"
       "Do not include markdown code fences."
   ),
   model=make_model(0.0),
)


rewriter = ChatAgent(
   system_message=(
       "You are a revising editor. Improve the draft based on critique. Preserve factual accuracy.\n"
       "Return the improved draft as plain text only."
   ),
   model=make_model(0.25),
)

We construct the specialized agents: planner, researcher, writer, critic, and rewriter. We define their system roles carefully to enforce task boundaries and structured behavior. This establishes the modular multi-agent architecture that enables collaboration and iterative refinement.

def plan_goal(goal: str) -> Plan:
   resp = planner.step("GOAL:\n" + goal + "\n\nReturn JSON plan now.")
   raw = resp.msgs[0].content if hasattr(resp, "msgs") else resp.msg.content
   js = extract_first_json_object(raw)
   try:
       return Plan.model_validate_json(js)
   except Exception:
       return Plan.model_validate(json.loads(js))


def research_task(task: PlanTask, goal: str, k: int) -> EvidenceItem:
   prompt = (
       "GOAL:\n" + goal + "\n\nTASK:\n" + task.model_dump_json(indent=2) + "\n\n"
       f"Perform research. Use at most {k} web searches. First search official documentation or GitHub if relevant."
   )
   resp = researcher.step(prompt)
   raw = resp.msgs[0].content if hasattr(resp, "msgs") else resp.msg.content
   js = extract_first_json_object(raw)
   try:
       return EvidenceItem.model_validate_json(js)
   except Exception:
       return EvidenceItem.model_validate(json.loads(js))


def draft_with_self_consistency(goal: str, plan: Plan, evidence: List[Tuple[PlanTask, EvidenceItem]], n: int) -> str:
   packed_evidence = []
   for t, ev in evidence:
       packed_evidence.append({
           "task_id": t.id,
           "task_title": t.title,
           "objective": t.objective,
           "notes": ev.notes,
           "key_points": ev.key_points
       })
   payload = {
       "goal": goal,
       "assumptions": plan.assumptions,
       "tasks": [t.model_dump() for t in plan.tasks],
       "evidence": packed_evidence,
       "success_criteria": plan.success_criteria,
   }
   drafts = []
   for _ in range(max(1, n)):
       resp = writer.step("INPUT:\n" + json.dumps(payload, ensure_ascii=False, indent=2))
       txt = resp.msgs[0].content if hasattr(resp, "msgs") else resp.msg.content
       drafts.append(txt.strip())
   if len(drafts) == 1:
       return drafts[0]
   chooser = ChatAgent(
       system_message=(
           "You are a selector agent. Choose the best draft among candidates for correctness, clarity, and actionability.\n"
           "Return ONLY the winning draft text, unchanged."
       ),
       model=make_model(0.0),
   )
   resp = chooser.step("GOAL:\n" + goal + "\n\nCANDIDATES:\n" + "\n\n---\n\n".join([f"[DRAFT {i+1}]\n{d}" for i, d in enumerate(drafts)]))
   return (resp.msgs[0].content if hasattr(resp, "msgs") else resp.msg.content).strip()

We implement the orchestration logic for planning, research, and self-consistent drafting. We aggregate structured evidence and generate multiple candidate drafts to improve robustness. We then select the best draft through an additional evaluation agent, simulating ensemble-style reasoning.

def critique_text(goal: str, draft: str) -> Critique:
   resp = critic.step("GOAL:\n" + goal + "\n\nDRAFT:\n" + draft + "\n\nReturn critique JSON now.")
   raw = resp.msgs[0].content if hasattr(resp, "msgs") else resp.msg.content
   js = extract_first_json_object(raw)
   try:
       return Critique.model_validate_json(js)
   except Exception:
       return Critique.model_validate(json.loads(js))


def revise(goal: str, draft: str, critique: Critique) -> str:
   resp = rewriter.step(
       "GOAL:\n" + goal +
       "\n\nCRITIQUE:\n" + critique.model_dump_json(indent=2) +
       "\n\nDRAFT:\n" + draft +
       "\n\nRewrite now."
   )
   return (resp.msgs[0].content if hasattr(resp, "msgs") else resp.msg.content).strip()


def pretty_plan(plan: Plan):
   tab = Table(title="Agent Plan", show_lines=True)
   tab.add_column("ID", style="bold")
   tab.add_column("Title")
   tab.add_column("Objective")
   tab.add_column("Deliverable")
   for t in plan.tasks:
       tab.add_row(t.id, t.title, t.objective, t.deliverable)
   console.print(tab)


def run(cfg: RunConfig):
   console.print(Panel.fit("CAMEL Advanced Agentic Tutorial Runner", style="bold"))
   plan = plan_goal(cfg.goal)
   pretty_plan(plan)


   evidence = []
   for task in plan.tasks[: cfg.max_tasks]:
       ev = research_task(task, cfg.goal, cfg.max_searches_per_task)
       evidence.append((task, ev))


   console.print(Panel.fit("Drafting (self-consistency)", style="bold"))
   draft = draft_with_self_consistency(cfg.goal, plan, evidence, cfg.self_consistency_samples)


   for r in range(cfg.max_revision_rounds + 1):
       crit = critique_text(cfg.goal, draft)
       console.print(Panel.fit(f"Critique round {r+1} — score {crit.score_0_to_10:.1f}/10", style="bold"))
       if crit.strengths:
           console.print(Panel("Strengths:\n- " + "\n- ".join(crit.strengths), title="Strengths"))
       if crit.issues:
           console.print(Panel("Issues:\n- " + "\n- ".join(crit.issues), title="Issues"))
       if crit.fix_plan:
           console.print(Panel("Fix plan:\n- " + "\n- ".join(crit.fix_plan), title="Fix plan"))
       if crit.score_0_to_10 >= 8.5 or r >= cfg.max_revision_rounds:
           break
       draft = revise(cfg.goal, draft, crit)


   console.print(Panel.fit("FINAL DELIVERABLE", style="bold green"))
   console.print(draft)


run(cfg)

We implement the critique-and-revision loop to enforce quality control. We score the draft, identify weaknesses, and iteratively refine it as needed. Finally, we execute the full pipeline, producing a structured, research-backed deliverable through coordinated collaboration among agents.

In conclusion, we built a production-style CAMEL-based multi-agent system that goes far beyond simple prompt chaining. We structured agent communication through validated schemas, incorporated web search tools for grounded reasoning, applied self-consistency to improve output reliability, and enforced quality using an internal critic loop. By combining these advanced ideas, we showed how we can construct scalable, modular, and reliable agentic pipelines suitable for real-world AI applications.


Check out the Full Codes with Notebook here. Also, feel free to follow us on Twitter and don’t forget to join our 130k+ ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.

Need to partner with us for promoting your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar etc.? Connect with us