This commit is contained in:
Timothy Jaeryang Baek committed 2026-10-31 08:06:23 +09:00
1 parent f9d1d8cdaf
commit b6c46ab00a
5 files changed
+245 -34

No files matched your search

+78 -11
View File
@@ -76,6 +76,51 @@ from cptr.utils.identity import identity_for_context
logger = logging.getLogger(__name__)
def _is_tool_result_error(value: Any) -> bool:
if isinstance(value, str):
text = value.strip().lower()
if (
text.startswith("error:")
or text.startswith("exception:")
or text.startswith("traceback")
or text.startswith("http error!")
):
return True
parsed = value
while isinstance(parsed, str):
try:
parsed = json.loads(parsed)
except (json.JSONDecodeError, TypeError, ValueError):
break
if not isinstance(parsed, dict):
return False
error = parsed.get("error")
if isinstance(error, str):
has_error = bool(error.strip())
else:
has_error = isinstance(error, (dict, list)) and bool(error)
if has_error:
return True
status = parsed.get("status")
if isinstance(status, str) and status.strip().lower() in {"error", "failed"}:
return True
if parsed.get("success") is False or parsed.get("ok") is False:
message = parsed.get("message")
return has_error or (
bool(message.strip())
if isinstance(message, str)
else isinstance(message, (dict, list)) and bool(message)
)
return False
ASK_USER_NAME = "ask_user"
DEFAULT_AUTO_RESOLUTION_MS = 120_000
ASK_USER_SCHEMA = {
@@ -927,7 +972,11 @@ def _output_items_to_messages(
):
continue
pending_reasoning_items.append(item)
elif itype == "function_call" and item.get("status") in {"completed", "rejected"}:
elif itype == "function_call" and item.get("status") in {
"completed",
"failed",
"rejected",
}:
call_id = item.get("call_id")
if not call_id or call_id in native_agent_call_ids:
continue
@@ -2002,12 +2051,21 @@ async def run_chat_task(
if item.get("status") in {"completed", "rejected", "failed"}:
continue
call_id = item.get("call_id")
if call_id and any(
result.get("type") == "function_call_output"
and result.get("call_id") == call_id
for result in output_items
):
item["status"] = "completed"
existing_result = next(
(
result
for result in output_items
if result.get("type") == "function_call_output"
and result.get("call_id") == call_id
),
None,
)
if call_id and existing_result:
item["status"] = existing_result.get("status") or (
"failed"
if _is_tool_result_error(existing_result.get("output", ""))
else "completed"
)
continue
name = item.get("name", "")
@@ -2090,9 +2148,10 @@ async def run_chat_task(
"type": "function_call_output",
"call_id": item["call_id"],
"output": result,
"status": "failed" if _is_tool_result_error(result) else "completed",
}
output_items.append(result_item)
item["status"] = "completed"
item["status"] = result_item["status"]
await emit(output=item)
await emit(output=result_item)
_sync_state()
@@ -2648,9 +2707,10 @@ async def run_chat_task(
"type": "function_call_output",
"call_id": tc["call_id"],
"output": result,
"status": "failed" if _is_tool_result_error(result) else "completed",
}
output_items.append(result_item)
item["status"] = "completed"
item["status"] = result_item["status"]
await emit(output=item)
await emit(output=result_item)
_sync_state()
@@ -2704,9 +2764,12 @@ async def run_chat_task(
"type": "function_call_output",
"call_id": tc["call_id"],
"output": result,
"status": "failed"
if _is_tool_result_error(result)
else "completed",
}
output_items.append(result_item)
item["status"] = "completed"
item["status"] = result_item["status"]
await emit(output=item)
await emit(output=result_item)
_sync_state()
@@ -2716,7 +2779,11 @@ async def run_chat_task(
[
*response_reasoning_items,
*([flushed_item] if flushed_item else []),
*(item for _, item in call_items if item.get("status") == "completed"),
*(
item
for _, item in call_items
if item.get("status") in {"completed", "failed"}
),
*sequential_result_items,
*delegate_result_items,
]
+17 -5
View File
@@ -9,7 +9,6 @@ from __future__ import annotations
import copy
import json
import logging
from typing import Any
import httpx
@@ -66,9 +65,7 @@ async def fetch_openapi_spec(
# ── Schema conversion ──────────────────────────────────────
def _resolve_schema(
schema: dict, components: dict, resolved: set | None = None
) -> dict:
def _resolve_schema(schema: dict, components: dict, resolved: set | None = None) -> dict:
"""Recursively resolve $ref references in a JSON schema."""
if not schema:
return {}
@@ -168,7 +165,7 @@ def convert_openapi_to_tool_specs(openapi_spec: dict) -> list[dict]:
pschema = param.get("schema", {})
desc = pschema.get("description", "") or param.get("description", "")
if pschema.get("enum") and isinstance(pschema["enum"], list):
desc += f'. Possible values: {", ".join(str(v) for v in pschema["enum"])}'
desc += f". Possible values: {', '.join(str(v) for v in pschema['enum'])}"
prop = {
"type": pschema.get("type") or "string",
@@ -298,6 +295,21 @@ async def execute_openapi_tool(
json=body_params if body_params else None,
)
if resp.status_code >= 400:
body = resp.text.strip()
try:
body = json.dumps(resp.json(), indent=2, ensure_ascii=False)
except Exception:
pass
return json.dumps(
{
"error": f"HTTP {resp.status_code} from tool server",
"status_code": resp.status_code,
"body": body[:4000],
},
ensure_ascii=False,
)
# Try to parse as JSON
try:
data = resp.json()