|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""General-purpose multimodal code agent entry point.""" |
| 3 | + |
| 4 | +from __future__ import annotations |
| 5 | + |
| 6 | +import argparse |
| 7 | +import base64 |
| 8 | +import logging |
| 9 | +import random |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +import requests |
| 13 | + |
| 14 | +from argus import Agent, AskWebAgentTool, EverMindMemory, WebAgent |
| 15 | +from argus.config import AgentConfig, Config, LLMConfig, WebAgentConfig |
| 16 | +from argus.data.content import Content |
| 17 | +from argus.llm.anthropic import AnthropicClient |
| 18 | +from argus.llm.base import LLMClient |
| 19 | +from argus.llm.openai import OpenAIClient |
| 20 | +from argus.tools.checklist import ChecklistTool |
| 21 | +from argus.tools.shell import ShellTool |
| 22 | + |
| 23 | +logging.basicConfig(level=logging.INFO, format="%(asctime)s %(levelname)s %(name)s: %(message)s") |
| 24 | +logger = logging.getLogger(__name__) |
| 25 | + |
| 26 | +DEFAULT_DOCKER_IMAGE = "python:3.11" |
| 27 | + |
| 28 | + |
| 29 | +def _load_image(source: str) -> str | None: |
| 30 | + """Load an image from a local path or URL and return base64-encoded bytes.""" |
| 31 | + if source.startswith("http://") or source.startswith("https://"): |
| 32 | + try: |
| 33 | + resp = requests.get(source, timeout=15) |
| 34 | + resp.raise_for_status() |
| 35 | + return base64.b64encode(resp.content).decode() |
| 36 | + except Exception as exc: |
| 37 | + logger.warning("Failed to download image %s: %s", source, exc) |
| 38 | + return None |
| 39 | + path = Path(source) |
| 40 | + if not path.exists(): |
| 41 | + logger.warning("Image file not found: %s", source) |
| 42 | + return None |
| 43 | + return base64.b64encode(path.read_bytes()).decode() |
| 44 | + |
| 45 | + |
| 46 | +def _build_task(text: str, port: int, max_steps: int, images: list[str]) -> Content: |
| 47 | + """Build the task Content, injecting runtime context and optionally attaching images.""" |
| 48 | + preamble = ( |
| 49 | + f"You have {max_steps} steps available. Use them wisely.\n" |
| 50 | + f"A port has been reserved for you on the host: {port}. " |
| 51 | + f"If you need to run a server or web service, bind it to {port} inside the container.\n\n" |
| 52 | + ) |
| 53 | + text = preamble + text |
| 54 | + if not images: |
| 55 | + return Content(text=text) |
| 56 | + loaded = [b64 for src in images if (b64 := _load_image(src)) is not None] |
| 57 | + if loaded: |
| 58 | + text += f"\n\n{len(loaded)} image(s) are attached after this text block." |
| 59 | + return Content(text=text, images=loaded) |
| 60 | + |
| 61 | + |
| 62 | +def _build_llm(cfg: LLMConfig) -> LLMClient: |
| 63 | + provider = cfg.provider.lower() |
| 64 | + if provider == "anthropic": |
| 65 | + return AnthropicClient( |
| 66 | + model=cfg.model, |
| 67 | + api_key=cfg.api_key, |
| 68 | + base_url=cfg.base_url or None, |
| 69 | + temperature=cfg.temperature, |
| 70 | + ) |
| 71 | + if provider == "openai": |
| 72 | + return OpenAIClient( |
| 73 | + model=cfg.model, |
| 74 | + api_key=cfg.api_key, |
| 75 | + base_url=cfg.base_url or None, |
| 76 | + temperature=cfg.temperature, |
| 77 | + ) |
| 78 | + raise ValueError(f"Unknown LLM provider: {cfg.provider!r}. Supported: openai, anthropic") |
| 79 | + |
| 80 | + |
| 81 | +def _build_web_agent(cfg: WebAgentConfig) -> WebAgent: |
| 82 | + llm = _build_llm(cfg.LLM) |
| 83 | + log_dir = Path(cfg.log_dir) if cfg.log_dir else None |
| 84 | + return WebAgent( |
| 85 | + llm=llm, |
| 86 | + system_prompt=cfg.system_prompt, |
| 87 | + max_steps=cfg.max_steps, |
| 88 | + log_dir=log_dir, |
| 89 | + headless=cfg.headless, |
| 90 | + ) |
| 91 | + |
| 92 | + |
| 93 | +def _build_agent( |
| 94 | + cfg: AgentConfig, docker_image: str, workdir: str, port: int, web_agent: WebAgent |
| 95 | +) -> Agent: |
| 96 | + shell = ShellTool(docker_image, workdir=workdir, remove_on_cleanup=False, port=port) |
| 97 | + log_dir = Path(cfg.log_dir) if cfg.log_dir else None |
| 98 | + llm = _build_llm(cfg.LLM) |
| 99 | + |
| 100 | + memory = None |
| 101 | + if cfg.enable_memory: |
| 102 | + memory = EverMindMemory( |
| 103 | + user_id=cfg.Memory.user_id, |
| 104 | + base_url=cfg.Memory.base_url, |
| 105 | + api_key=cfg.Memory.api_key, |
| 106 | + retrieve_method=cfg.Memory.retrieve_method, |
| 107 | + top_k=cfg.Memory.top_k, |
| 108 | + ) |
| 109 | + |
| 110 | + return Agent( |
| 111 | + llm=llm, |
| 112 | + tools=[ChecklistTool(), shell, AskWebAgentTool(web_agent)], |
| 113 | + system_prompt=cfg.system_prompt, |
| 114 | + max_steps=cfg.max_steps, |
| 115 | + log_dir=log_dir, |
| 116 | + memory=memory, |
| 117 | + summarize_threshold=cfg.summarize_threshold, |
| 118 | + ) |
| 119 | + |
| 120 | + |
| 121 | +def main() -> None: |
| 122 | + parser = argparse.ArgumentParser( |
| 123 | + description="Run the Argus multimodal code agent on an arbitrary task." |
| 124 | + ) |
| 125 | + parser.add_argument("--config", help="Path to config.yaml", required=True) |
| 126 | + parser.add_argument( |
| 127 | + "--docker", |
| 128 | + default=DEFAULT_DOCKER_IMAGE, |
| 129 | + metavar="IMAGE", |
| 130 | + help=f"Docker image to use (default: {DEFAULT_DOCKER_IMAGE})", |
| 131 | + ) |
| 132 | + parser.add_argument( |
| 133 | + "--workdir", |
| 134 | + default="/workspace", |
| 135 | + metavar="DIR", |
| 136 | + help="Working directory inside the container (default: /workspace)", |
| 137 | + ) |
| 138 | + parser.add_argument("--task", metavar="TEXT", help="Task description.", required=True) |
| 139 | + parser.add_argument( |
| 140 | + "--images", |
| 141 | + nargs="*", |
| 142 | + metavar="SRC", |
| 143 | + help="Image files or URLs to attach to the task (local paths or http(s):// URLs).", |
| 144 | + ) |
| 145 | + parser.add_argument( |
| 146 | + "--port", |
| 147 | + type=int, |
| 148 | + default=None, |
| 149 | + metavar="PORT", |
| 150 | + help="Host port to expose from the container. Randomly assigned if omitted.", |
| 151 | + ) |
| 152 | + args = parser.parse_args() |
| 153 | + |
| 154 | + # Resolve task text |
| 155 | + task_text = args.task |
| 156 | + |
| 157 | + port = args.port if args.port is not None else random.randint(10000, 65535) |
| 158 | + |
| 159 | + cfg = Config.from_yaml(Path(args.config)) |
| 160 | + task = _build_task(task_text, port, cfg.agent.max_steps, args.images or []) |
| 161 | + |
| 162 | + logger.info("Docker image : %s", args.docker) |
| 163 | + logger.info("Workdir : %s", args.workdir) |
| 164 | + logger.info("Port : %d", port) |
| 165 | + logger.info("Max steps : %d", cfg.agent.max_steps) |
| 166 | + logger.info("Images : %d", len(task.images)) |
| 167 | + |
| 168 | + web_agent = _build_web_agent(cfg.web_agent) |
| 169 | + agent = _build_agent(cfg.agent, args.docker, args.workdir, port, web_agent) |
| 170 | + |
| 171 | + agent.run(task) |
| 172 | + |
| 173 | + shell = next((t for t in agent.tool_list if isinstance(t, ShellTool)), None) |
| 174 | + if shell is not None: |
| 175 | + patch = shell.get_patch() |
| 176 | + if patch: |
| 177 | + logger.info("=== git diff (patch) ===\n%s", patch) |
| 178 | + shell.cleanup() |
| 179 | + |
| 180 | + logger.info("Done.") |
| 181 | + |
| 182 | + |
| 183 | +if __name__ == "__main__": |
| 184 | + main() |
0 commit comments