import json from config import OPENROUTER_MODEL from openrouter_client import client from mcp_client import MCPClient class Agent: def __init__(self): self.mcp = MCPClient() self.tools = [] self.messages = [ { "role": "system", "content": ( "Du bist JARVIS, ein Smart-Home Assistent.\n" "Du steuerst ein Haus über MCP Tools.\n" "Antworte normal oder nutze Tools wenn nötig." ) } ] async def load_tools(self): res = await self.mcp.list_tools() self.tools = [] for t in res.tools: self.tools.append({ "type": "function", "function": { "name": t.name, "description": t.description, "parameters": t.inputSchema } }) print(f"[JARVIS] {len(self.tools)} Tools geladen") async def _run_tool(self, tool_call): name = tool_call.function.name args = json.loads(tool_call.function.arguments or "{}") result = await self.mcp.call_tool(name, args) return result async def run(self, user_input: str): self.messages.append({ "role": "user", "content": user_input }) for _ in range(8): response = await client.chat.completions.create( model=OPENROUTER_MODEL, messages=self.messages, tools=self.tools ) message = response.choices[0].message # 🧠 TOOL CALL PATH if getattr(message, "tool_calls", None): self.messages.append(message) for tool_call in message.tool_calls: result = await self._run_tool(tool_call) self.messages.append({ "role": "tool", "tool_call_id": tool_call.id, "content": str(result) }) continue # 🧠 NORMAL RESPONSE PATH if message.content: self.messages.append({ "role": "assistant", "content": message.content }) return message.content # 🧠 SAFETY FALLBACK return "Ich konnte keine gültige Antwort generieren." return "Tool Loop Limit erreicht."