- Environment: Python, virtualenv, and the OpenAI SDK are preinstalled.
- Working directory:
/root/code. - Goal: start from the safe agent and add logging for tool calls, timing, token usage, and iteration warnings.
- Faster debugging of tool failures.
- Identify slow tools and optimize or cache them.
- Track token usage to control costs.
- Get advance warning before hitting the iteration cap.
- The baseline already enforces a max iteration cap of 10 and includes try/except handling for tool execution.
- Example baseline snippet (trimmed for clarity):
run_log: a list of dictionaries capturing each tool call: tool name, args, truncated result, and duration_ms.- Timing inside
execute_tool: measure start/end, compute duration in milliseconds, and append a compact trace torun_log. - Token tracking: maintain running totals of prompt and completion tokens after each API call.
- Iteration tracking: maintain
iteration_countand print a warning when within the last two iterations. - Execution summary: when the agent finishes, print iterations used, total tokens, number of tool calls, each call’s timing, and total wall-clock time.
run_log and an instrumented execute_tool
- Initialize
run_logand token counters immediately before your agent loop. - Replace the old
execute_toolwith the instrumented version below. It measures duration and stores a truncated string result so logs remain compact.
- Maintain running counters for prompt and completion tokens and update them after each
client.chat.completions.createcall. - Different SDK versions may return
usageeither as an attribute or a dict — handle both forms.
- Keep
iteration_countand increment it at the start of each loop iteration. - Print an advance warning when you are within the last two iterations so you can take corrective action or gracefully exit.
- Record a wall-clock start time before the loop and compute elapsed time after it completes.
- Print a concise summary with iterations used, tokens, tool call counts and timings, and total elapsed time.
Full integration notes
- Initialize
run_log,total_prompt_tokens,total_completion_tokens, anditeration_countimmediately before entering your agent loop. - Replace your existing
execute_toolwith the instrumented version and call it asexecute_tool(name, args, run_log). - After every call to
client.chat.completions.create, update token counters fromresponse.usage. - Preserve try/except handling inside
execute_toolso tool failures continue to produce descriptive results that are logged. - Keep the safety cap
MAX_ITERATIONSunchanged — instrumentation should not alter agent control flow.
This instrumentation records what happened (tools called, durations, token usage, and iteration counts) without changing agent decision logic or safety limits. Use these logs to pinpoint slow tools, unexpected exceptions, or high token usage.
Be careful what you log. Logs may contain sensitive information from tool arguments or results. Mask or redact secrets before writing logs to persistent storage or sharing them.
- Run the monitored agent. It will:
- Call tools (for example,
check_calendar) via the instrumentedexecute_tool. - Append compact entries to
run_logfor each tool call. - Print a one-line answer (your agent’s response) followed by the Execution Summary block showing iterations, tokens, per-tool durations, and total elapsed time.
- Call tools (for example,
- Persist
run_logto a JSON file for later analysis or attach it to a debugging UI. - Add contextual IDs to log entries (request_id, session_id) to correlate logs from multiple runs.
- If costs are a concern, use the token counters to create alerts when usage exceeds thresholds.