MCPcopy
hub / github.com/shareAI-lab/learn-claude-code / agent_loop

Function agent_loop

s13_background_tasks/code.py:410–457  ·  view source on GitHub ↗
(messages: list, context: dict)

Source from the content-addressed store, hash-verified

408# ── Agent Loop (simplified, focused on background tasks) ──
409
410def agent_loop(messages: list, context: dict):
411 system = get_system_prompt(context)
412 while True:
413 try:
414 response = client.messages.create(
415 model=MODEL, system=system, messages=messages,
416 tools=TOOLS, max_tokens=8000)
417 except Exception as e:
418 messages.append({"role": "assistant", "content": [
419 {"type": "text",
420 "text": f"[Error] {type(e).__name__}: {e}"}]})
421 return
422
423 messages.append({"role": "assistant", "content": response.content})
424 if response.stop_reason != "tool_use":
425 return
426
427 results = []
428 for block in response.content:
429 if block.type != "tool_use":
430 continue
431 print(f"\033[36m> {block.name}\033[0m")
432
433 if should_run_background(block.name, block.input):
434 bg_id = start_background_task(block)
435 results.append({"type": "tool_result",
436 "tool_use_id": block.id,
437 "content": f"[Background task {bg_id} started] "
438 f"Command: {block.input.get('command', '')}. "
439 f"Result will be available when complete."})
440 else:
441 output = execute_tool(block)
442 print(str(output)[:300])
443 results.append({"type": "tool_result",
444 "tool_use_id": block.id,
445 "content": output})
446
447 # Inject tool results + background notifications in one user message
448 user_content = list(results)
449 bg_notifications = collect_background_results()
450 if bg_notifications:
451 for notif in bg_notifications:
452 user_content.append({"type": "text", "text": notif})
453 print(f" \033[32m[inject] {len(bg_notifications)} background "
454 f"notification(s)\033[0m")
455 messages.append({"role": "user", "content": user_content})
456 context = update_context(context, messages)
457 system = get_system_prompt(context)
458
459
460if __name__ == "__main__":

Callers 1

code.pyFile · 0.70

Calls 8

get_system_promptFunction · 0.70
should_run_backgroundFunction · 0.70
start_background_taskFunction · 0.70
execute_toolFunction · 0.70
update_contextFunction · 0.70
createMethod · 0.45
getMethod · 0.45

Tested by

no test coverage detected