tinycodinglm / agentic /aiagent-0060.jsonl
winapiadmin's picture
Upload folder using huggingface_hub
1f3a244 verified
|
Raw History Blame Contribute Delete
2.49 kB
opencode trace
System 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 c...

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.

User

How do agents recover from tool errors with bounded retry, backoff, fallback and escalation? Show retry handling with tool_call_id. Include code examples.

Assistant

Recovery: retry transient errors, rephrase, try another tool, else escalate. Always bound retries.

python
import time

def execute_with_recovery(llm, run_tool, task: str, max_retries: int = 3) -> str:
    history: list[dict] = [{"role": "user", "content": task}]
    attempts = 0
    while attempts <= max_retries:
        msg = llm.chat.completions.create(
            model="model-identifier-from-lm-studio", messages=history,
        ).choices[0].message
        if not msg.tool_calls:
            return msg.content or ""
        history.append({
            "role": "assistant", "content": msg.content,
            "tool_calls": [{"id": tc.id, "type": "function",
                            "function": {"name": tc.function.name,
                                         "arguments": tc.function.arguments or "{}"}}
                           for tc in msg.tool_calls],
        })
        for tc in msg.tool_calls:
            try:
                result = run_tool(tc.function.name, tc.function.arguments or "{}")
            except (TimeoutError, ConnectionError) as e:
                attempts += 1
                if attempts > max_retries:
                    return f"Failed after {max_retries} retries: {e}"
                time.sleep(min(2 ** attempts, 8))
                result = f"RETRYABLE ERROR: {type(e).__name__}: {e}"
            except Exception as e:
                result = f"ERROR: {type(e).__name__}: {e}"
            history.append({"role": "tool", "tool_call_id": tc.id, "content": str(result)})
        attempts += 1
    return "Failed after max retries"