Files
secure-agent/agent/loop.py
T
2026-03-04 14:35:44 -07:00

75 lines
2.2 KiB
Python

import asyncio
from http.client import responses
from anthropic import AsyncAnthropic
from agent.config import settings
from agent.history import ConversationHistory
from agent.tools import TOOL_SCHEMAS, dispatch_tool
client = AsyncAnthropic(api_key=settings.anthropic_api_key)
async def run_turn(user_message: str, history: list[dict] = None, sandbox=None) -> str:
if history is None:
history = []
# add the new user message to history
messages = history + [{"role": "user", "content": user_message}]
response = await client.messages.create(
model=settings.model,
max_tokens=settings.max_tokens,
tools=TOOL_SCHEMAS,
messages=messages,
)
while response.stop_reason == "tool_use":
tool_results = []
for block in response.content:
if block.type == "tool_use":
result = await dispatch_tool(
tool_name=block.name, tool_input=block.input, sandbox=sandbox
)
tool_results.append(
{"type": "tool_result", "tool_use_id": block.id, "content": result}
)
messages = messages + [
{"role": "assistant", "content": response.content},
{"role": "user", "content": tool_results},
]
response = await client.messages.create(
model=settings.model,
max_tokens=settings.max_tokens,
tools=TOOL_SCHEMAS,
messages=messages,
)
return next(block.text for block in response.content if hasattr(block, "text"))
async def run_session(sandbox=None):
"""simple CLI session - temporary until TUI is built"""
history = ConversationHistory()
print("Codeing agent ready. Type /quit to quit.")
while True:
user_input = input("You: ").strip()
# __ UI commands_______
if not user_input:
continue
if user_input == "/quit":
print("Goodbye")
break
history.add_message("user", user_input)
response = await run_turn(user_input, history.get_all(), sandbox)
history.add_message("assistant", response)
print(f"\nAssistant: {response}")