|
| 1 | +"""Agent orchestrator — builds the agent, runs autonomous or interactive mode.""" |
| 2 | + |
| 3 | +import shutil |
| 4 | +import sys |
| 5 | +from contextlib import AsyncExitStack |
| 6 | +from pathlib import Path |
| 7 | + |
| 8 | +from langchain.agents import create_agent |
| 9 | +from langchain_core.messages import HumanMessage, SystemMessage |
| 10 | + |
| 11 | +from .archive import ArchiveManager |
| 12 | +from .config import AgentConfig, INPUT_MARKER |
| 13 | +from .llm import create_llm |
| 14 | +from .mcp_client import connect_mcp, find_mcp_server |
| 15 | +from .prompts import ( |
| 16 | + AUTONOMOUS_GOAL, |
| 17 | + INTERACTIVE_GOAL, |
| 18 | + INTERACTIVE_REVIEW_GOAL, |
| 19 | + build_system_prompt, |
| 20 | +) |
| 21 | +from .scripts import detect_run_script |
| 22 | +from .skills import load_skills |
| 23 | +from .skills.generator import GeneratorSkill |
| 24 | + |
| 25 | + |
| 26 | +async def run_agent(config: AgentConfig): |
| 27 | + """Main entry point: build skills, connect MCP, run the agent loop.""" |
| 28 | + |
| 29 | + # Set up archive manager |
| 30 | + archive = ArchiveManager(config.output_dir) |
| 31 | + |
| 32 | + # Load skills |
| 33 | + skills = load_skills(config.skills, config, archive) |
| 34 | + has_generator = any(isinstance(s, GeneratorSkill) for s in skills) |
| 35 | + |
| 36 | + # MCP setup for generator skill |
| 37 | + async with AsyncExitStack() as stack: |
| 38 | + if has_generator: |
| 39 | + mcp_server = find_mcp_server(config.mcp_server) |
| 40 | + print(f"Generator MCP: {mcp_server}") |
| 41 | + session = await stack.enter_async_context(connect_mcp(mcp_server)) |
| 42 | + print("Connected to MCP server") |
| 43 | + |
| 44 | + # Get MCP tool schema and inject into generator skill |
| 45 | + mcp_tools = await session.list_tools() |
| 46 | + mcp_tool = mcp_tools.tools[0] |
| 47 | + for skill in skills: |
| 48 | + if isinstance(skill, GeneratorSkill): |
| 49 | + skill.set_mcp_session(session) |
| 50 | + skill.set_mcp_tool_schema(mcp_tool) |
| 51 | + |
| 52 | + # Collect tools from all skills |
| 53 | + tools = [] |
| 54 | + for skill in skills: |
| 55 | + tools.extend(skill.get_tools()) |
| 56 | + |
| 57 | + # Create LLM and agent |
| 58 | + llm = create_llm(config.model, config.temperature, config.base_url) |
| 59 | + agent = create_agent(llm, tools) |
| 60 | + print("Agent initialized\n") |
| 61 | + |
| 62 | + # Build system prompt |
| 63 | + system_prompt = build_system_prompt(skills, has_generator) |
| 64 | + messages = [("system", system_prompt)] |
| 65 | + |
| 66 | + if config.show_prompts: |
| 67 | + print(f"System prompt:\n{system_prompt}\n") |
| 68 | + |
| 69 | + # Determine initial message |
| 70 | + initial_msg = _build_initial_message(config, archive) |
| 71 | + |
| 72 | + if not config.interactive: |
| 73 | + await _run_autonomous(agent, messages, initial_msg, config) |
| 74 | + else: |
| 75 | + await _run_interactive(agent, messages, initial_msg, config, has_generator) |
| 76 | + |
| 77 | + |
| 78 | +def _build_initial_message(config, archive): |
| 79 | + """Build the first user message based on config.""" |
| 80 | + if config.scripts_dir: |
| 81 | + scripts_dir = Path(config.scripts_dir) |
| 82 | + for f in sorted(scripts_dir.glob("*.py")): |
| 83 | + shutil.copy(f, archive.work_dir) |
| 84 | + print(f"Copied: {f.name}") |
| 85 | + archive.start("copied_scripts") |
| 86 | + archive.archive_scripts() |
| 87 | + |
| 88 | + run_scripts = list(archive.work_dir.glob("run_*.py")) |
| 89 | + run_name = run_scripts[0].name if run_scripts else "run_libe.py" |
| 90 | + return INTERACTIVE_REVIEW_GOAL.format(run_script_name=run_name) |
| 91 | + |
| 92 | + user_prompt = config.get_user_prompt() |
| 93 | + if user_prompt: |
| 94 | + return user_prompt |
| 95 | + |
| 96 | + if config.interactive: |
| 97 | + print("Describe the scripts you want to generate (or press Enter for default demo):", flush=True) |
| 98 | + print(INPUT_MARKER, flush=True) |
| 99 | + user_input = input().strip() |
| 100 | + if user_input: |
| 101 | + return user_input |
| 102 | + print("Using default demo prompt") |
| 103 | + |
| 104 | + return ( |
| 105 | + "Create six_hump_camel APOSMM scripts:\n" |
| 106 | + "- Executable: six_hump_camel/six_hump_camel.x\n" |
| 107 | + "- Input: six_hump_camel/input.txt\n" |
| 108 | + "- Template vars: X0, X1\n" |
| 109 | + "- 4 workers, 100 sims.\n" |
| 110 | + "- The output file for each simulation is output.txt\n" |
| 111 | + "- The bounds should be 0,1 and -1,2 for X0 and X1 respectively" |
| 112 | + ) |
| 113 | + |
| 114 | + |
| 115 | +async def _run_autonomous(agent, messages, initial_msg, config): |
| 116 | + """Single invocation — agent generates/loads, runs, fixes, reports.""" |
| 117 | + goal = AUTONOMOUS_GOAL.format(initial_msg=initial_msg) |
| 118 | + messages.append(("user", goal)) |
| 119 | + |
| 120 | + if config.show_prompts: |
| 121 | + print(f"Goal: {goal}\n") |
| 122 | + print("Starting agent...\n") |
| 123 | + |
| 124 | + result = await agent.ainvoke({"messages": messages}) |
| 125 | + print(f"\n{'=' * 60}") |
| 126 | + print("Agent completed") |
| 127 | + print(f"{'=' * 60}") |
| 128 | + print(result["messages"][-1].content) |
| 129 | + |
| 130 | + |
| 131 | +async def _run_interactive(agent, messages, initial_msg, config, has_generator): |
| 132 | + """Chat loop — agent responds, waits for user input, repeats.""" |
| 133 | + if has_generator: |
| 134 | + goal = INTERACTIVE_GOAL.format(initial_msg=initial_msg) |
| 135 | + else: |
| 136 | + goal = initial_msg |
| 137 | + messages.append(("user", goal)) |
| 138 | + print("Starting agent...\n") |
| 139 | + |
| 140 | + while True: |
| 141 | + try: |
| 142 | + result = await agent.ainvoke({"messages": messages}) |
| 143 | + messages = result["messages"] |
| 144 | + response = messages[-1].content |
| 145 | + if response: |
| 146 | + print(f"\n{response}", flush=True) |
| 147 | + except Exception as e: |
| 148 | + print(f"\nAgent error: {e}", flush=True) |
| 149 | + |
| 150 | + # Wait for user input |
| 151 | + print(INPUT_MARKER, flush=True) |
| 152 | + user_input = input().strip() |
| 153 | + |
| 154 | + if not user_input or user_input.lower() in ("quit", "exit", "done"): |
| 155 | + print("\nSession ended") |
| 156 | + break |
| 157 | + |
| 158 | + messages.append( |
| 159 | + SystemMessage( |
| 160 | + content="STOP. Read the user's next message carefully and respond to exactly what they ask. " |
| 161 | + "Do not continue previous tasks." |
| 162 | + ) |
| 163 | + ) |
| 164 | + messages.append(HumanMessage(content=user_input)) |
0 commit comments