{"slug": "agent-expanded-py", "title": "agent_expanded.py", "summary": "An engineer shared a Python script, agent_expanded.py, that implements a simple agent loop for a large language model with a 1,050,000-token context window. The script uses a custom shell tool to execute commands and iterates until no tool calls remain, printing the final response and context usage percentage.", "body_md": "| import json | |\n| import sys | |\n| from subprocess import getoutput as run_shell | |\n| from urllib.request import Request, urlopen | |\n| MODEL = \"gpt-5.6\" | |\n| CONTEXT_WINDOW_TOKENS = 1_050_000 | |\n| endpoint_url = sys.argv[1] | |\n| history = [] | |\n| request_body = dict( | |\n| model=MODEL, | |\n| input=history, | |\n| tools=[dict(type=\"custom\", name=\"sh\")], | |\n| ) | |\n| while user_prompt := input(\"> \"): | |\n| history += [dict(role=\"user\", content=user_prompt)] | |\n| headers = {\"Content-Type\": \"application/json\"} | |\n| while True: | |\n| output_items = ( | |\n| response := json.load( | |\n| urlopen( | |\n| Request( | |\n| endpoint_url, | |\n| json.dumps(request_body).encode(), | |\n| headers, | |\n| ) | |\n| ) | |\n| ) | |\n| )[\"output\"] | |\n| history += output_items | |\n| tool_calls = [ | |\n| item | |\n| for item in output_items | |\n| if item[\"type\"] == \"custom_tool_call\" | |\n| ] | |\n| context_usage_percent = ( | |\n| response[\"usage\"][\"total_tokens\"] / CONTEXT_WINDOW_TOKENS * 100 | |\n| ) | |\n| if not tool_calls: | |\n| print( | |\n| output_items[-1][\"content\"][0][\"text\"], | |\n| f\"\\n[{context_usage_percent:06.3f}%]\", | |\n| ) | |\n| break | |\n| history += [ | |\n| dict( | |\n| type=\"custom_tool_call_output\", | |\n| call_id=tool_call[\"call_id\"], | |\n| output=run_shell(tool_call[\"input\"]), | |\n| ) | |\n| for tool_call in tool_calls | |\n| ] |", "url": "https://wpnews.pro/news/agent-expanded-py", "canonical_source": "https://gist.github.com/tosh/61aca9ffa9ea115fa4df332407d7a9a9", "published_at": "2026-07-22 17:16:42+00:00", "updated_at": "2026-07-22 22:27:21.330314+00:00", "lang": "en", "topics": ["large-language-models", "ai-agents", "developer-tools"], "entities": [], "alternates": {"html": "https://wpnews.pro/news/agent-expanded-py", "markdown": "https://wpnews.pro/news/agent-expanded-py.md", "text": "https://wpnews.pro/news/agent-expanded-py.txt", "jsonld": "https://wpnews.pro/news/agent-expanded-py.jsonld"}}