{"type": "session", "harness": "opencode", "id": "aiagent-0000", "name": "agent architecture"} {"type": "message", "message": {"role": "system", "content": "You are an expert software engineer and technical assistant. You provide accurate, detailed, and practical answers. When writing code, use best practices, proper error handling, and clear variable names. When analyzing code, identify bugs, security issues, and performance problems. You have deep knowledge of C/C++, Windows API, Python, and many other technologies."}} {"type": "message", "message": {"role": "user", "content": "How is a ReAct-style LLM agent structured (LLM brain, planner, executor, memory, tools)? Show a minimal OpenAI-compatible tool loop with correct tool_call_id handling. Include code examples."}} {"type": "message", "message": {"role": "assistant", "content": "**AI Agent Architecture (ReAct loop: Thought -> Action -> Observation).**\n\n```\nUser goal -> LLM Brain -> Planner -> Executor -> Tool/Env -> Observation -> Memory\n```\n\n**Core components:**\n1. **LLM Brain:** reasoning and decision-making\n2. **Planner:** decomposes goals into steps\n3. **Executor:** invokes tools, handles errors\n4. **Memory:** short-term (context window) + long-term (vector DB)\n5. **Tools:** search, code exec (sandboxed), file I/O, APIs\n\nReAct (Yao et al., 2022) interleaves reasoning traces with tool actions. Plan-and-Execute plans first, then executes. Reflexion adds self-critique.\n\n```python\nfrom openai import OpenAI\n\nclient = OpenAI(base_url=\"http://localhost:1234/v1\", api_key=\"lm-studio\")\nMODEL = \"model-identifier-from-lm-studio\"\n\ndef tool_schema(name: str, desc: str, props: dict, required: list[str]) -> dict:\n return {\n \"type\": \"function\",\n \"function\": {\n \"name\": name, \"description\": desc,\n \"parameters\": {\"type\": \"object\", \"properties\": props, \"required\": required},\n },\n }\n\ndef run_agent(goal: str, tools: dict, execute_fn, max_steps: int = 5) -> str:\n history: list[dict] = [{\"role\": \"user\", \"content\": goal}]\n schemas = [tool_schema(*t) for t in tools.values()]\n for _ in range(max_steps):\n resp = client.chat.completions.create(\n model=MODEL, messages=history, tools=schemas, tool_choice=\"auto\",\n )\n msg = resp.choices[0].message\n history.append({\n \"role\": \"assistant\",\n \"content\": msg.content,\n \"tool_calls\": [\n {\"id\": tc.id, \"type\": \"function\",\n \"function\": {\"name\": tc.function.name,\n \"arguments\": tc.function.arguments or \"{}\"}}\n for tc in (msg.tool_calls or [])\n ] if msg.tool_calls else None,\n })\n if not msg.tool_calls:\n return msg.content or \"\"\n for tc in msg.tool_calls:\n try:\n result = execute_fn(tc.function.name, tc.function.arguments or \"{}\")\n except Exception as e:\n result = f\"ERROR: {type(e).__name__}: {e}\"\n history.append({\"role\": \"tool\", \"tool_call_id\": tc.id, \"content\": str(result)})\n return \"Max steps reached\"\n```"}}