|

Building a Policy-Governed Multi-Agent Financial Research Workflow with Omnigent

✅

In this tutorial, we construct and execute a multi-agent workflow with Omnigent utilizing a dependable, remoted Python setting created with uv. We configure a monetary analysis lead agent that retrieves a stay USD-to-EUR alternate charge from an exterior API, prepares a concise client-ready abstract, and delegates its draft to a devoted text-auditing sub-agent for readability and size validation. We outline reusable Python capabilities as callable agent instruments, describe the whole agent construction in YAML, and use the Claude Agent SDK because the execution harness. We additionally handle the Anthropic API key securely via setting variables, apply non-interactive insurance policies that restrict instrument calls and management session prices, and run the workflow straight from Colab with out requiring Node.js, tmux, or an interactive terminal. Through this implementation, we discover how Omnigent combines brokers, instruments, delegation, stay information entry, and governance inside a single configurable system.

import os, sys, subprocess, textwrap, pathlib, getpass
def sh(cmd, **kw):
   """Run a command, and on failure present the ACTUAL error, not simply a code."""
   print("$", " ".be part of(map(str, cmd)))
   p = subprocess.run(cmd, textual content=True, capture_output=True, **kw)
   if p.returncode != 0:
       print(p.stdout or "", p.stderr or "", sep="n")
       elevate RuntimeError(f"Command failed ({p.returncode}): {' '.be part of(map(str, cmd))}")
   return p
WORKDIR = pathlib.Path("/content material/omnigent_tutorial")
WORKDIR.mkdir(mother and father=True, exist_ok=True)
VENV = WORKDIR / ".venv"
subprocess.run([sys.executable, "-m", "pip", "install", "-q", "uv"], test=True)
if not (VENV / "bin" / "python").exists():
   sh(["uv", "venv", "--python", "3.12", str(VENV)])
PY = str(VENV / "bin" / "python")
sh(["uv", "pip", "install", "--python", PY, "-q", "omnigent", "requests"])
OMNI = str(VENV / "bin" / "omnigent")
print("n✅", subprocess.run([OMNI, "--version"], capture_output=True, textual content=True).stdout.strip())

We import the required Python modules and outline a helper operate that executes shell instructions whereas displaying detailed error info when a command fails. We create a devoted working listing and use uv to construct an remoted Python 3.12 digital setting that avoids Colab’s ensurepip limitation. We then set up Omnigent and Requests contained in the setting, find the Omnigent CLI executable, and confirm the set up by printing its model.

if not os.environ.get("ANTHROPIC_API_KEY"):
   os.environ["ANTHROPIC_API_KEY"] = getpass.getpass("Anthropic API key: ")
env = os.environ.copy()
env["OMNIGENT_NO_UPDATE_CHECK"] = "1"

We securely acquire the Anthropic API key solely when it’s not already accessible within the pocket book setting. We retailer the credential within the present course of setting in order that Omnigent can detect it with out writing delicate info to a file. We additionally create a separate setting configuration for the subprocess and switch off Omnigent’s computerized replace test throughout execution.

(WORKDIR / "agent_tools.py").write_text(textwrap.dedent('''
   """Local instruments uncovered to the Omnigent brokers on this tutorial."""
   import requests
   def get_exchange_rate(base_currency: str, target_currency: str) -> dict:
       """Look up the newest FX charge between two ISO-4217 forex codes."""
       r = requests.get(
           "https://api.frankfurter.app/newest",
           params={"from": base_currency.higher(), "to": target_currency.higher()},
           timeout=10,
       )
       r.raise_for_status()
       information = r.json()
       return {
           "base": base_currency.higher(),
           "goal": target_currency.higher(),
           "charge": information["rates"][target_currency.upper()],
           "date": information["date"],
       }
   def word_count(textual content: str) -> int:
       """Count the phrases in a piece of textual content."""
       return len(textual content.cut up())
'''))

We generate a Python module containing the native capabilities that Omnigent exposes as callable instruments to the brokers. We outline a stay exchange-rate instrument that sends a request to the Frankfurter API and returns the newest charge, forex codes, and relevant date. We additionally implement a easy word-count instrument that enables the auditing sub-agent to measure the size of the monetary abstract.

(WORKDIR / "fx_research_lead.yaml").write_text(textwrap.dedent('''
   identify: fx_research_lead
   immediate: |
     You are a monetary analysis lead. For any query about forex
     actions: name get_exchange_rate to fetch the stay charge, then hand
     your draft abstract to the text_auditor sub-agent for a readability and
     size test earlier than giving your ultimate reply to the consumer.
   executor:
     harness: claude-sdk
   instruments:
     get_exchange_rate:
       sort: operate
       callable: agent_tools.get_exchange_rate
     text_auditor:
       sort: agent
       immediate: |
         You audit quick items of monetary writing. Call word_count to
         report its size, flag any unexplained jargon, and recommend one
         concrete readability enchancment.
       instruments:
         word_count:
           sort: operate
           callable: agent_tools.word_count
   insurance policies:
     cap_calls:
       sort: operate
       handler: omnigent.insurance policies.builtins.security.max_tool_calls_per_session
       factory_params:
         restrict: 20
     finances:
       sort: operate
       handler: omnigent.insurance policies.builtins.price.cost_budget
       factory_params:
         max_cost_usd: 1.00
'''))

We outline the whole multi-agent structure via a YAML configuration file. We configure the monetary analysis lead, join it to the exchange-rate instrument, and add a text-auditing sub-agent that evaluates the draft utilizing the word-count operate. We additionally apply laborious governance insurance policies that limit the variety of instrument calls and restrict the utmost API price for the session.

env["PYTHONPATH"] = str(WORKDIR)
query = (
   "What is the present USD to EUR alternate charge? Give me a two-sentence "
   "abstract I may paste into a shopper notice."
)
outcome = subprocess.run(
   [OMNI, "run", str(WORKDIR / "fx_research_lead.yaml"), "-p", question, "--no-session"],
   cwd=WORKDIR, env=env, stdin=subprocess.DEVNULL,
   capture_output=True, textual content=True, timeout=300,
)
print("n" + "=" * 70)
print(outcome.stdout.strip() or "(no stdout)")
if outcome.returncode != 0 or "error" in outcome.stdout.decrease():
   print("-" * 70)
   print("stderr:", outcome.stderr[-2000:])
   print(f"nDebug: test ~/.omnigent/logs/runner/ , or rerun with:n"
         f"  !{OMNI} --debug --log-to-stderr run {WORKDIR/'fx_research_lead.yaml'} -p "..." --no-session")
print("=" * 70)
print(f"""
Next steps:
 • Explore the CLI:  !{OMNI} run --help
 • Bundled demo brokers:
       !{OMNI} polly -p "evaluation this repo" --no-session
       !{OMNI} debby -p "brainstorm 3 names for a espresso store" --no-session
 • YAML schema:  https://github.com/omnigent-ai/omnigent/blob/principal/docs/AGENT_YAML_SPEC.md
 • Policies:     https://github.com/omnigent-ai/omnigent/blob/principal/docs/POLICIES.md
""")

We add the tutorial listing to PYTHONPATH, outline the currency-related query, and execute the Omnigent agent via a non-interactive subprocess. We seize the generated response, show diagnostic output when execution fails, and supply a debug command for analyzing runner points. We end by printing helpful subsequent steps for exploring Omnigent’s CLI, bundled brokers, YAML specification, and coverage documentation.

In conclusion, we created a sensible Omnigent multi-agent software that integrates stay monetary information retrieval, hierarchical agent delegation, automated writing evaluation, and policy-based execution controls. We used uv to resolve Colab’s ensurepip limitation and preserve a separate Python 3.12 setting with out modifying the pocket book’s system interpreter. We uncovered native Python capabilities as agent-accessible instruments, outlined the agent and sub-agent conduct via a readable YAML configuration, and enforced laborious limits on instrument utilization and API spending. We additionally executed the workflow non-interactively, captured each normal output and diagnostic errors, and established a construction that helps simple mannequin adjustments with out altering the underlying agent logic. We now have a reusable basis for growing extra refined, safe, cost-controlled, and tool-enabled multi-agent techniques for monetary analysis and different real-world purposes in Google Colab.


Check out the Full Code hereAlso, be at liberty to observe us on Twitter and don’t neglect to hitch our 150k+ML SubReddit and Subscribe to our Newsletter. Wait! are you on telegram? now you can join us on telegram as well.

Need to companion with us for selling your GitHub Repo OR Hugging Face Page OR Product Release OR Webinar and many others.? Connect with us

The submit Building a Policy-Governed Multi-Agent Financial Research Workflow with Omnigent appeared first on MarkTechPost.

Similar Posts