agent.py aktualisiert

This commit is contained in:
2026-07-05 09:44:47 +00:00
parent ea9d2dd783
commit af9fed431f
+75 -26
View File
@@ -12,43 +12,71 @@ class Agent:
self.mcp = MCPClient(MCP_URL) self.mcp = MCPClient(MCP_URL)
self.tools = [] self.tools = []
self.messages = [ self.messages = [
{ {
"role": "system", "role": "system",
"content": [ "content": [
{ {
"text": "Du bist N.O.R.A, ein Smart-Home Assistent. Nutze Tools wenn nötig." "text": (
"Du bist N.O.R.A, ein Smart-Home Assistent. "
"Du steuerst Geräte über Tools. "
"Nutze Tools wenn sinnvoll."
)
} }
] ]
} }
] ]
# -------------------------
# TOOL LOADING
# -------------------------
async def load_tools(self): async def load_tools(self):
res = await self.mcp.list_tools() try:
res = await self.mcp.list_tools()
self.tools = [] self.tools = [
{
for t in res.tools: "toolSpec": {
self.tools.append({ "name": t.name,
"toolSpec": { "description": t.description,
"name": t.name, "inputSchema": t.inputSchema
"description": t.description, }
"inputSchema": t.inputSchema
} }
}) for t in res.tools
]
self.logger.info(f"{len(self.tools)} Tools geladen") self.logger.info(f"{len(self.tools)} Tools geladen")
except Exception as e:
self.logger.error(f"Tool Load Error: {e}")
self.tools = []
# -------------------------
# TOOL EXECUTION
# -------------------------
async def _run_tool(self, tool): async def _run_tool(self, tool):
name = tool["name"] try:
args = tool.get("input", {}) name = tool.get("name")
args = tool.get("input", {}) or {}
self.logger.info(f"Tool Call: {name} -> {args}") self.logger.info(f"Tool Call {name} | args={args}")
result = await self.mcp.call_tool(name, args) result = await self.mcp.call_tool(name, args)
return result # MCP result stabilisieren
if hasattr(result, "content"):
return result.content
return result
except Exception as e:
self.logger.error(f"Tool Error ({tool.get('name')}): {e}")
return f"ERROR: {e}"
# -------------------------
# MAIN LOOP
# -------------------------
async def run(self, user_input: str): async def run(self, user_input: str):
self.messages.append({ self.messages.append({
@@ -58,28 +86,42 @@ class Agent:
for _ in range(8): for _ in range(8):
response = await self.llm.chat( try:
messages=self.messages, response = await self.llm.chat(
tools=self.tools messages=self.messages,
) tools=self.tools
)
except Exception as e:
self.logger.error(f"LLM Error: {e}")
return f"LLM Fehler: {e}"
output = response.get("output", {}) output = response.get("output", {})
message = output.get("message", {}) message = output.get("message", {})
content = message.get("content", []) content = message.get("content", [])
tool_uses = [] tool_uses = []
final_text = "" final_text = []
# -------------------------
# PARSE RESPONSE SAFE
# -------------------------
for c in content: for c in content:
tool = c.get("toolUse") tool = c.get("toolUse")
if tool: if tool:
tool_uses.append(tool) tool_uses.append(tool)
if "text" in c: if "text" in c:
final_text += c["text"] final_text.append(c["text"])
# -------------------------
# TOOL EXECUTION PATH
# -------------------------
if tool_uses: if tool_uses:
self.logger.info(f"{len(tool_uses)} Tool(s) detected")
self.messages.append({ self.messages.append({
"role": "assistant", "role": "assistant",
"content": content "content": content
@@ -88,11 +130,12 @@ class Agent:
tool_results = [] tool_results = []
for tool in tool_uses: for tool in tool_uses:
result = await self._run_tool(tool) result = await self._run_tool(tool)
tool_results.append({ tool_results.append({
"toolResult": { "toolResult": {
"toolUseId": tool["toolUseId"], "toolUseId": tool.get("toolUseId"),
"content": [ "content": [
{ {
"text": str(result) "text": str(result)
@@ -108,12 +151,18 @@ class Agent:
continue continue
# -------------------------
# FINAL RESPONSE
# -------------------------
if final_text: if final_text:
text = "\n".join(final_text)
self.messages.append({ self.messages.append({
"role": "assistant", "role": "assistant",
"content": [{"text": final_text}] "content": [{"text": text}]
}) })
return final_text return text
return "Tool Loop Limit erreicht" return "Tool Loop Limit erreicht"