Spaces:
Running
Running
KaiWu Cursor commited on
Commit ·
3ce633c
1
Parent(s): 6bd7fbe
feat(agent): harden agent loop against stalls and truncation
Browse files- Stream responses and raise max_tokens to 64000.
- On max_tokens, retry once with low reasoning effort and never keep a
truncated tool_use in history; give up with a clear message after that.
- Nudge the model once when it replies without a tool call, and let it
opt out with NO_TOOL for non-modeling requests.
- Turn tool exceptions into tool results instead of crashing the loop.
- Roll back the turn's messages in run_chat_turn if the loop raises.
- Prompt the model to call the tool directly instead of only planning.
Co-authored-by: Cursor <cursoragent@cursor.com>
- agent_core/agent.py +65 -18
- agent_core/prompts.py +2 -0
- agent_core/service.py +6 -1
agent_core/agent.py
CHANGED
|
@@ -2,40 +2,87 @@ from agent_core.config import get_client, get_model_id
|
|
| 2 |
from agent_core.prompts import SYSTEM
|
| 3 |
from agent_core.tools.registry import TOOL_HANDLERS, TOOLS
|
| 4 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 5 |
|
| 6 |
def latest_user_prompt(messages: list) -> str | None:
|
| 7 |
for message in reversed(messages):
|
| 8 |
-
|
| 9 |
-
|
|
|
|
| 10 |
return None
|
| 11 |
|
| 12 |
|
| 13 |
-
def
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 14 |
client = get_client()
|
| 15 |
model = get_model_id()
|
|
|
|
|
|
|
|
|
|
| 16 |
|
| 17 |
while True:
|
| 18 |
-
response =
|
|
|
|
| 19 |
model=model,
|
| 20 |
system=SYSTEM,
|
| 21 |
messages=messages,
|
| 22 |
tools=TOOLS,
|
| 23 |
-
max_tokens=
|
|
|
|
| 24 |
)
|
| 25 |
-
|
| 26 |
-
if response.stop_reason
|
|
|
|
|
|
|
|
|
|
|
|
|
| 27 |
return
|
| 28 |
|
| 29 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 30 |
prompt = latest_user_prompt(messages)
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
else:
|
| 37 |
-
output = f"Unknown tool: {block.name}"
|
| 38 |
-
|
| 39 |
-
print(f"> {block.name}: {output[:200]}")
|
| 40 |
-
results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
|
| 41 |
messages.append({"role": "user", "content": results})
|
|
|
|
| 2 |
from agent_core.prompts import SYSTEM
|
| 3 |
from agent_core.tools.registry import TOOL_HANDLERS, TOOLS
|
| 4 |
|
| 5 |
+
MAX_TOKENS = 64000
|
| 6 |
+
# DeepSeek ignores thinking.budget_tokens; effort is the only knob to shorten reasoning.
|
| 7 |
+
TRUNCATION_FALLBACK = {"output_config": {"effort": "low"}}
|
| 8 |
+
NO_TOOL = "NO_TOOL"
|
| 9 |
+
BUILD_NUDGE = (
|
| 10 |
+
"You replied without calling any tool. If this request needs a CAD model, call the tool now instead of "
|
| 11 |
+
f"describing a plan. If no model is needed (e.g. a question or a needed clarification), reply with exactly {NO_TOOL}."
|
| 12 |
+
)
|
| 13 |
+
TRUNCATED_REPLY = "The model output exceeded the length limit before finishing. Please retry or simplify the request."
|
| 14 |
+
|
| 15 |
|
| 16 |
def latest_user_prompt(messages: list) -> str | None:
|
| 17 |
for message in reversed(messages):
|
| 18 |
+
content = message.get("content")
|
| 19 |
+
if message.get("role") == "user" and isinstance(content, str) and content != BUILD_NUDGE:
|
| 20 |
+
return content
|
| 21 |
return None
|
| 22 |
|
| 23 |
|
| 24 |
+
def _text_of(content) -> str:
|
| 25 |
+
return "".join(getattr(block, "text", "") or "" for block in content).strip()
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
def _run_tool(block, prompt: str | None) -> str:
|
| 29 |
+
handler = TOOL_HANDLERS.get(block.name)
|
| 30 |
+
if not handler:
|
| 31 |
+
return f"Unknown tool: {block.name}"
|
| 32 |
+
try:
|
| 33 |
+
return handler(prompt=prompt, **block.input)
|
| 34 |
+
except Exception as exc:
|
| 35 |
+
return f"Tool {block.name} raised {type(exc).__name__}: {exc}"
|
| 36 |
+
|
| 37 |
+
|
| 38 |
+
def _create(client, **kwargs):
|
| 39 |
+
with client.messages.stream(**kwargs) as stream:
|
| 40 |
+
return stream.get_final_message()
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
def agent_loop(messages: list) -> None:
|
| 44 |
client = get_client()
|
| 45 |
model = get_model_id()
|
| 46 |
+
used_tool = False
|
| 47 |
+
nudged = False
|
| 48 |
+
truncated = False
|
| 49 |
|
| 50 |
while True:
|
| 51 |
+
response = _create(
|
| 52 |
+
client,
|
| 53 |
model=model,
|
| 54 |
system=SYSTEM,
|
| 55 |
messages=messages,
|
| 56 |
tools=TOOLS,
|
| 57 |
+
max_tokens=MAX_TOKENS,
|
| 58 |
+
**(TRUNCATION_FALLBACK if truncated else {}),
|
| 59 |
)
|
| 60 |
+
# A truncated reply may hold a tool_use with partial input; never put it into history.
|
| 61 |
+
if response.stop_reason == "max_tokens":
|
| 62 |
+
if not truncated:
|
| 63 |
+
truncated = True
|
| 64 |
+
continue
|
| 65 |
+
messages.append({"role": "assistant", "content": TRUNCATED_REPLY})
|
| 66 |
return
|
| 67 |
|
| 68 |
+
messages.append({"role": "assistant", "content": response.content})
|
| 69 |
+
tool_uses = [block for block in response.content if block.type == "tool_use"]
|
| 70 |
+
|
| 71 |
+
if not tool_uses:
|
| 72 |
+
if nudged and _text_of(response.content) == NO_TOOL:
|
| 73 |
+
del messages[-2:]
|
| 74 |
+
return
|
| 75 |
+
if used_tool or nudged:
|
| 76 |
+
return
|
| 77 |
+
nudged = True
|
| 78 |
+
messages.append({"role": "user", "content": BUILD_NUDGE})
|
| 79 |
+
continue
|
| 80 |
+
|
| 81 |
+
used_tool = True
|
| 82 |
prompt = latest_user_prompt(messages)
|
| 83 |
+
results = []
|
| 84 |
+
for block in tool_uses:
|
| 85 |
+
output = _run_tool(block, prompt)
|
| 86 |
+
print(f"> {block.name}: {output[:200]}")
|
| 87 |
+
results.append({"type": "tool_result", "tool_use_id": block.id, "content": output})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 88 |
messages.append({"role": "user", "content": results})
|
agent_core/prompts.py
CHANGED
|
@@ -11,6 +11,8 @@ You are a CAD and 3D model generation agent at {WORKDIR}.
|
|
| 11 |
Active tool instructions:
|
| 12 |
{tool_sections}
|
| 13 |
|
|
|
|
|
|
|
| 14 |
When a tool returns ok=true, report output_path, run_dir, and manifest_path to the user.
|
| 15 |
|
| 16 |
Do not ask the user to run commands or create files manually.
|
|
|
|
| 11 |
Active tool instructions:
|
| 12 |
{tool_sections}
|
| 13 |
|
| 14 |
+
When the user asks for a model, call the tool in the same reply. Do not stop after describing a plan or ask for confirmation; choose reasonable defaults for missing details and state them.
|
| 15 |
+
|
| 16 |
When a tool returns ok=true, report output_path, run_dir, and manifest_path to the user.
|
| 17 |
|
| 18 |
Do not ask the user to run commands or create files manually.
|
agent_core/service.py
CHANGED
|
@@ -53,8 +53,13 @@ def run_chat_turn(messages: list, user_text: str, image_path: str | None = None)
|
|
| 53 |
if image_path:
|
| 54 |
text = f"{text}\n\nUploaded image path for image-to-3D generation: {image_path}".strip()
|
| 55 |
|
|
|
|
| 56 |
messages.append({"role": "user", "content": text})
|
| 57 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 58 |
|
| 59 |
assistant_text = content_to_text(messages[-1].get("content"))
|
| 60 |
tool_payload = latest_tool_payload(messages)
|
|
|
|
| 53 |
if image_path:
|
| 54 |
text = f"{text}\n\nUploaded image path for image-to-3D generation: {image_path}".strip()
|
| 55 |
|
| 56 |
+
turn_start = len(messages)
|
| 57 |
messages.append({"role": "user", "content": text})
|
| 58 |
+
try:
|
| 59 |
+
agent_loop(messages)
|
| 60 |
+
except Exception:
|
| 61 |
+
del messages[turn_start:]
|
| 62 |
+
raise
|
| 63 |
|
| 64 |
assistant_text = content_to_text(messages[-1].get("content"))
|
| 65 |
tool_payload = latest_tool_payload(messages)
|