refactor: clean up agent architecture and coordination loop
Squash merged refactoring of agent architecture.
This commit is contained in:
+20
-11
@@ -2,9 +2,10 @@ import asyncio
|
||||
import logging
|
||||
import lmstudio as lms
|
||||
from typing import Any, Callable
|
||||
from core.interfaces import Agent
|
||||
from .prompt import CAVEMAN_PROMPT
|
||||
|
||||
logger: logging.Logger = logging.getLogger("agent-caveman")
|
||||
logger: logging.Logger = logging.getLogger("agent-base")
|
||||
|
||||
|
||||
class _ActResponseCapture:
|
||||
@@ -53,17 +54,17 @@ class _ActResponseCapture:
|
||||
return '\n'.join(self.responses) if self.responses else "No response captured."
|
||||
|
||||
|
||||
class CavemanAgent:
|
||||
"""Caveman AI agent - minimal token usage variant."""
|
||||
class BaseAgent(Agent):
|
||||
"""Base AI agent implementing common LMStudio interaction patterns."""
|
||||
|
||||
def __init__(self, model_name: str) -> None:
|
||||
self.model_name: str = model_name
|
||||
self.model: Any | None = None
|
||||
self.system_prompt: str = CAVEMAN_PROMPT
|
||||
self.system_prompt: str = ""
|
||||
|
||||
async def initialize(self) -> None:
|
||||
"""Initialize the LM Studio model."""
|
||||
logger.info(f"Initializing CavemanAgent with model: {self.model_name}")
|
||||
logger.info(f"Initializing agent with model: {self.model_name}")
|
||||
self.model = lms.llm(self.model_name)
|
||||
|
||||
async def run(self, user_input: str) -> str:
|
||||
@@ -78,12 +79,12 @@ class CavemanAgent:
|
||||
]
|
||||
|
||||
try:
|
||||
logger.info(f"Running CavemanAgent interactively (input length: {len(user_input)})")
|
||||
logger.info(f"Running agent interactively (input length: {len(user_input)})")
|
||||
response = await self.model.respond(user_input, messages=messages)
|
||||
logger.info(f"CavemanAgent responded successfully (response length: {len(response)})")
|
||||
logger.info(f"Agent responded successfully (response length: {len(response)})")
|
||||
return response
|
||||
except Exception as e:
|
||||
logger.error(f"CavemanAgent execution error: {e}")
|
||||
logger.error(f"Agent execution error: {e}")
|
||||
return f"Error in agent execution: {str(e)}"
|
||||
|
||||
async def run_with_tools(self, user_input: str, tools: list[Any]) -> str:
|
||||
@@ -94,14 +95,22 @@ class CavemanAgent:
|
||||
|
||||
try:
|
||||
capture = _ActResponseCapture()
|
||||
logger.info(f"Calling LMStudio act() on CavemanAgent with {len(tools)} tools...")
|
||||
logger.info(f"Calling LMStudio act() on agent with {len(tools)} tools...")
|
||||
result: lms.ActResult = self.model.act(user_input, tools=tools, on_message=capture)
|
||||
logger.info(f"act() on CavemanAgent returned: {result}")
|
||||
logger.info(f"act() on agent returned: {result}")
|
||||
response: str = capture.full_response
|
||||
if not response or response == "No response captured.":
|
||||
logger.warning(f"Act completed with {result.rounds} rounds but no response was captured.")
|
||||
return f"Act completed with {result.rounds} rounds but no response captured."
|
||||
return response
|
||||
except Exception as e:
|
||||
logger.error(f"CavemanAgent tool execution error: {e}")
|
||||
logger.error(f"Agent tool execution error: {e}")
|
||||
return f"Error in agent tool execution: {str(e)}"
|
||||
|
||||
|
||||
class CavemanAgent(BaseAgent):
|
||||
"""Caveman AI agent - minimal token usage variant."""
|
||||
|
||||
def __init__(self, model_name: str) -> None:
|
||||
super().__init__(model_name)
|
||||
self.system_prompt = CAVEMAN_PROMPT
|
||||
|
||||
+5
-100
@@ -1,108 +1,13 @@
|
||||
import asyncio
|
||||
import logging
|
||||
import lmstudio as lms
|
||||
from typing import Any, Callable
|
||||
from .prompt import CAVEMAN_PROMPT
|
||||
from core.agent import BaseAgent
|
||||
from .coding_prompt import CODING_AGENT_SYSTEM_PROMPT
|
||||
|
||||
logger: logging.Logger = logging.getLogger("agent-coding")
|
||||
|
||||
|
||||
class _ActResponseCapture:
|
||||
"""Captures the AI response from LMStudio act() callback."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.responses: list[str] = []
|
||||
|
||||
def __call__(self, message: Any) -> None:
|
||||
content: str = ""
|
||||
if hasattr(message, 'content'):
|
||||
content = message.content
|
||||
elif hasattr(message, 'text'):
|
||||
content = message.text
|
||||
elif hasattr(message, 'response'):
|
||||
content = message.response
|
||||
elif hasattr(message, 'message'):
|
||||
content = message.message
|
||||
else:
|
||||
return
|
||||
|
||||
if isinstance(content, list):
|
||||
parts: list[str] = []
|
||||
for item in content:
|
||||
if isinstance(item, dict):
|
||||
text: str = item.get('text', '')
|
||||
if isinstance(text, list):
|
||||
parts.extend([str(t) for t in text])
|
||||
else:
|
||||
parts.append(str(text))
|
||||
elif isinstance(item, str):
|
||||
parts.append(item)
|
||||
elif hasattr(item, 'text'):
|
||||
parts.append(str(item.text))
|
||||
elif hasattr(item, 'content'):
|
||||
parts.append(str(item.content))
|
||||
content = ''.join(parts)
|
||||
elif not isinstance(content, str):
|
||||
content = str(content)
|
||||
|
||||
if content.strip():
|
||||
self.responses.append(content.strip())
|
||||
|
||||
@property
|
||||
def full_response(self) -> str:
|
||||
return '\n'.join(self.responses) if self.responses else "No response captured."
|
||||
|
||||
|
||||
class CodingAgent:
|
||||
"""AI agent that interacts with LMStudio models and tools."""
|
||||
class CodingAgent(BaseAgent):
|
||||
"""AI agent that interacts with LMStudio models and tools for coding tasks."""
|
||||
|
||||
def __init__(self, model_name: str) -> None:
|
||||
self.model_name: str = model_name
|
||||
self.model: Any | None = None
|
||||
self.system_prompt: str = CODING_AGENT_SYSTEM_PROMPT
|
||||
|
||||
async def initialize(self) -> None:
|
||||
"""Initialize the LM Studio model."""
|
||||
logger.info(f"Initializing CodingAgent with model: {self.model_name}")
|
||||
self.model = lms.llm(self.model_name)
|
||||
|
||||
async def run(self, user_input: str) -> str:
|
||||
"""Run a single interaction with the agent."""
|
||||
if self.model is None:
|
||||
await self.initialize()
|
||||
assert self.model is not None
|
||||
|
||||
messages: list[dict[str, str]] = [
|
||||
{"role": "system", "content": self.system_prompt},
|
||||
{"role": "user", "content": user_input},
|
||||
]
|
||||
|
||||
try:
|
||||
logger.info(f"Running CodingAgent interactively (input length: {len(user_input)})")
|
||||
response = await self.model.respond(user_input, messages=messages)
|
||||
logger.info(f"CodingAgent responded successfully (response length: {len(response)})")
|
||||
return response
|
||||
except Exception as e:
|
||||
logger.error(f"CodingAgent execution error: {e}")
|
||||
return f"Error in agent execution: {str(e)}"
|
||||
|
||||
async def run_with_tools(self, user_input: str, tools: list[Callable[..., Any]]) -> str:
|
||||
"""Run the agent with tool calling capability."""
|
||||
if self.model is None:
|
||||
await self.initialize()
|
||||
assert self.model is not None
|
||||
|
||||
try:
|
||||
capture = _ActResponseCapture()
|
||||
logger.info(f"Calling LMStudio act() on CodingAgent with {len(tools)} tools...")
|
||||
result: lms.ActResult = self.model.act(user_input, tools=tools, on_message=capture)
|
||||
logger.info(f"act() on CodingAgent returned: {result}")
|
||||
response: str = capture.full_response
|
||||
if not response or response == "No response captured.":
|
||||
logger.warning(f"Act completed with {result.rounds} rounds but no response was captured.")
|
||||
return f"Act completed with {result.rounds} rounds but no response captured."
|
||||
return response
|
||||
except Exception as e:
|
||||
logger.error(f"CodingAgent tool execution error: {e}")
|
||||
return f"Error in agent tool execution: {str(e)}"
|
||||
super().__init__(model_name)
|
||||
self.system_prompt = CODING_AGENT_SYSTEM_PROMPT
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
import logging
|
||||
from typing import Any, Callable
|
||||
from core.agent import BaseAgent
|
||||
from core.prompts import COORDINATOR_SYSTEM_PROMPT
|
||||
from core.coordinator_tools import CoordinatorTools
|
||||
|
||||
logger: logging.Logger = logging.getLogger("agent-coordinator")
|
||||
|
||||
|
||||
class CoordinatorNoToolCalledError(Exception):
|
||||
"""Raised when the Coordinator Agent completes execution without calling any routing tool."""
|
||||
pass
|
||||
|
||||
|
||||
class CoordinatorAgent(BaseAgent):
|
||||
"""AI agent that coordinates Gitea issues and decides the next action."""
|
||||
|
||||
def __init__(self, model_name: str) -> None:
|
||||
super().__init__(model_name)
|
||||
self.system_prompt = COORDINATOR_SYSTEM_PROMPT
|
||||
|
||||
async def decide_action(
|
||||
self,
|
||||
mission: str,
|
||||
planning_tools: list[Callable[..., Any]],
|
||||
coord_tools: CoordinatorTools,
|
||||
) -> str:
|
||||
"""Run the Coordinator Agent and ensure a tool is called."""
|
||||
coord_tools_list: list[Callable[..., Any]] = [
|
||||
coord_tools.propose_plan,
|
||||
coord_tools.start_implementation,
|
||||
coord_tools.answer_question,
|
||||
coord_tools.close_issue,
|
||||
coord_tools.take_no_action,
|
||||
]
|
||||
combined_tools: list[Callable[..., Any]] = planning_tools + coord_tools_list
|
||||
|
||||
logger.info("Running CoordinatorAgent to decide action...")
|
||||
response_text: str = await self.run_with_tools(mission, combined_tools)
|
||||
|
||||
if not coord_tools.tool_called:
|
||||
logger.warning("CoordinatorAgent did not call any tools!")
|
||||
raise CoordinatorNoToolCalledError(
|
||||
"CoordinatorAgent failed to call a routing tool during execution."
|
||||
)
|
||||
|
||||
return response_text
|
||||
+601
-614
File diff suppressed because it is too large
Load Diff
@@ -9,6 +9,8 @@ from core.interfaces import (
|
||||
)
|
||||
from core.coding_agent import CodingAgent
|
||||
from core.agent import CavemanAgent
|
||||
from core.coordinator_agent import CoordinatorAgent
|
||||
from core.planning_agent import PlanningAgent
|
||||
from gitea.workspace import WorkspaceManager
|
||||
|
||||
logger: logging.Logger = logging.getLogger("core-factory")
|
||||
@@ -65,6 +67,16 @@ class AgentFactory:
|
||||
logger.info(f"Factory creating CavemanAgent with model: {model_name}")
|
||||
return CavemanAgent(model_name)
|
||||
|
||||
@staticmethod
|
||||
def create_coordinator_agent(model_name: str) -> CoordinatorAgent:
|
||||
logger.info(f"Factory creating CoordinatorAgent with model: {model_name}")
|
||||
return CoordinatorAgent(model_name)
|
||||
|
||||
@staticmethod
|
||||
def create_planning_agent(model_name: str) -> PlanningAgent:
|
||||
logger.info(f"Factory creating PlanningAgent with model: {model_name}")
|
||||
return PlanningAgent(model_name)
|
||||
|
||||
|
||||
class WorkspaceFactory:
|
||||
"""Factory for creating workspace manager instances."""
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import logging
|
||||
from core.agent import BaseAgent
|
||||
from .coding_prompt import CODING_AGENT_SYSTEM_PROMPT
|
||||
|
||||
logger: logging.Logger = logging.getLogger("agent-planning")
|
||||
|
||||
|
||||
class PlanningAgent(BaseAgent):
|
||||
"""AI agent that analyzes a PR/issue and builds an implementation plan."""
|
||||
|
||||
def __init__(self, model_name: str) -> None:
|
||||
super().__init__(model_name)
|
||||
self.system_prompt = CODING_AGENT_SYSTEM_PROMPT
|
||||
Reference in New Issue
Block a user