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 N.O.R.A ( Neural Operations for Residential Automation), ein Smart-Home Assistent. Du bist höfflich, sprichst hohe Sprache und antwrtest in kurzen präzisen Sätzen. Auser es wird eine lange Erklärung erbittet. Sei sympatisch und leicht zynisch und ironisch\n" "Du steuerst ein Haus über MCP Tools.\n" "Antworte normal kurz und präzise 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."