HomeSample Page

Sample Page Title


On this tutorial, we construct a complicated, end-to-end multi-agent analysis workflow utilizing the CAMEL framework. We design a coordinated society of brokers, Planner, Researcher, Author, Critic, and Finalizer, that collaboratively remodel a high-level matter into a cultured, evidence-grounded analysis transient. We securely combine the OpenAI API, orchestrate agent interactions programmatically, and add light-weight persistent reminiscence to retain information throughout runs. By structuring the system round clear roles, JSON-based contracts, and iterative refinement, we exhibit how CAMEL can be utilized to assemble dependable, controllable, and scalable agentic pipelines. Try the FULL CODES right here.

!pip -q set up "camel-ai[all]" "python-dotenv" "wealthy"


import os
import json
import time
from typing import Dict, Any
from wealthy import print as rprint


def load_openai_key() -> str:
   key = None
   attempt:
       from google.colab import userdata
       key = userdata.get("OPENAI_API_KEY")
   besides Exception:
       key = None
   if not key:
       import getpass
       key = getpass.getpass("Enter OPENAI_API_KEY (hidden): ").strip()
   if not key:
       increase ValueError("OPENAI_API_KEY is required.")
   return key


os.environ["OPENAI_API_KEY"] = load_openai_key()

We arrange the execution setting and securely load the OpenAI API key utilizing Colab secrets and techniques or a hidden immediate. We make sure the runtime is prepared by putting in dependencies and configuring authentication so the workflow can run safely with out exposing credentials. Try the FULL CODES right here.

from camel.fashions import ModelFactory
from camel.varieties import ModelPlatformType, ModelType
from camel.brokers import ChatAgent
from camel.toolkits import SearchToolkit


MODEL_CFG = {"temperature": 0.2}


mannequin = ModelFactory.create(
   model_platform=ModelPlatformType.OPENAI,
   model_type=ModelType.GPT_4O,
   model_config_dict=MODEL_CFG,
)

We initialize the CAMEL mannequin configuration and create a shared language mannequin occasion utilizing the ModelFactory abstraction. We standardize mannequin habits throughout all brokers to make sure constant, reproducible reasoning all through the multi-agent pipeline. Try the FULL CODES right here.

MEM_PATH = "camel_memory.json"


def mem_load() -> Dict[str, Any]:
   if not os.path.exists(MEM_PATH):
       return {"runs": []}
   with open(MEM_PATH, "r", encoding="utf-8") as f:
       return json.load(f)


def mem_save(mem: Dict[str, Any]) -> None:
   with open(MEM_PATH, "w", encoding="utf-8") as f:
       json.dump(mem, f, ensure_ascii=False, indent=2)


def mem_add_run(matter: str, artifacts: Dict[str, str]) -> None:
   mem = mem_load()
   mem["runs"].append({"ts": int(time.time()), "matter": matter, "artifacts": artifacts})
   mem_save(mem)


def mem_last_summaries(n: int = 3) -> str:
   mem = mem_load()
   runs = mem.get("runs", [])[-n:]
   if not runs:
       return "No previous runs."
   return "n".be part of([f"{i+1}. topic={r['topic']} | ts={r['ts']}" for i, r in enumerate(runs)])

We implement a light-weight persistent reminiscence layer backed by a JSON file. We retailer artifacts from every run and retrieve summaries of earlier executions, permitting us to introduce continuity and historic context throughout classes. Try the FULL CODES right here.

def make_agent(position: str, objective: str, extra_rules: str = "") -> ChatAgent:
   system = (
       f"You might be {position}.n"
       f"Aim: {objective}n"
       f"{extra_rules}n"
       "Output should be crisp, structured, and instantly usable by the subsequent agent."
   )
   return ChatAgent(mannequin=mannequin, system_message=system)


planner = make_agent(
   "Planner",
   "Create a compact plan and analysis questions with acceptance standards.",
   "Return JSON with keys: plan, questions, acceptance_criteria."
)


researcher = make_agent(
   "Researcher",
   "Reply questions utilizing net search outcomes.",
   "Return JSON with keys: findings, sources, open_questions."
)


author = make_agent(
   "Author",
   "Draft a structured analysis transient.",
   "Return Markdown solely."
)


critic = make_agent(
   "Critic",
   "Determine weaknesses and recommend fixes.",
   "Return JSON with keys: points, fixes, rewrite_instructions."
)


finalizer = make_agent(
   "Finalizer",
   "Produce the ultimate improved transient.",
   "Return Markdown solely."
)


search_tool = SearchToolkit().search_duckduckgo
researcher = ChatAgent(
   mannequin=mannequin,
   system_message=researcher.system_message,
   instruments=[search_tool],
)

We outline the core agent roles and their tasks inside the workflow. We assemble specialised brokers with clear objectives and output contracts, and we improve the Researcher by attaching an online search software for evidence-grounded responses. Try the FULL CODES right here.

def step_json(agent: ChatAgent, immediate: str) -> Dict[str, Any]:
   res = agent.step(immediate)
   txt = res.msgs[0].content material.strip()
   attempt:
       return json.hundreds(txt)
   besides Exception:
       return {"uncooked": txt}


def step_text(agent: ChatAgent, immediate: str) -> str:
   res = agent.step(immediate)
   return res.msgs[0].content material

We summary interplay patterns with brokers into helper capabilities that implement structured JSON or free-text outputs. We simplify orchestration by dealing with parsing and fallback logic centrally, making the pipeline extra strong to formatting variability. Try the FULL CODES right here.

def run_workflow(matter: str) -> Dict[str, str]:
   rprint(mem_last_summaries(3))


   plan = step_json(
       planner,
       f"Matter: {matter}nCreate a decent plan and analysis questions."
   )


   analysis = step_json(
       researcher,
       f"Analysis the subject utilizing net search.n{json.dumps(plan)}"
   )


   draft = step_text(
       author,
       f"Write a analysis transient utilizing:n{json.dumps(analysis)}"
   )


   critique = step_json(
       critic,
       f"Critique the draft:n{draft}"
   )


   remaining = step_text(
       finalizer,
       f"Rewrite utilizing critique:n{json.dumps(critique)}nDraft:n{draft}"
   )


   artifacts = {
       "plan_json": json.dumps(plan, indent=2),
       "research_json": json.dumps(analysis, indent=2),
       "draft_md": draft,
       "critique_json": json.dumps(critique, indent=2),
       "final_md": remaining,
   }


   mem_add_run(matter, artifacts)
   return artifacts


TOPIC = "Agentic multi-agent analysis workflow with high quality management"
artifacts = run_workflow(TOPIC)
print(artifacts["final_md"])

We orchestrate the whole multi-agent workflow from planning to finalization. We sequentially move artifacts between brokers, apply critique-driven refinement, persist outcomes to reminiscence, and produce a finalized analysis transient prepared for downstream use.

In conclusion, we applied a sensible CAMEL-based multi-agent system that mirrors real-world analysis and evaluate workflows. We confirmed how clearly outlined agent roles, tool-augmented reasoning, and critique-driven refinement result in higher-quality outputs whereas lowering hallucinations and structural weaknesses. We additionally established a basis for extensibility by persisting artifacts and enabling reuse throughout classes. This strategy permits us to maneuver past single-prompt interactions and towards strong agentic methods that may be tailored for analysis, evaluation, reporting, and decision-support duties at scale.


Try the FULL CODES right here. Additionally, be at liberty to observe us on Twitter and don’t overlook to affix our 100k+ ML SubReddit and Subscribe to our Publication. Wait! are you on telegram? now you’ll be able to be part of us on telegram as nicely.


Michal Sutter is an information science skilled with a Grasp of Science in Information Science from the College of Padova. With a stable basis in statistical evaluation, machine studying, and knowledge engineering, Michal excels at remodeling complicated datasets into actionable insights.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles