Created
June 7, 2026 02:11
-
-
Save a-n-d-a-i/bd50aaa4bdb15f9a4cc8176ee387b212 to your computer and use it in GitHub Desktop.
agent in 50 lines
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import os | |
| import json | |
| import re | |
| import subprocess | |
| import urllib.request as req | |
| import urllib.error | |
| from urllib.parse import urlencode | |
| # --------------------------------------------------------------------------- | |
| # web.py (inlined) | |
| # --------------------------------------------------------------------------- | |
| UA = { | |
| "User-Agent": "python-requests/2.31.0" | |
| } | |
| def fetch(url: str, method: str = 'GET', data: dict = None, headers: dict = None) -> str: | |
| headers = {**UA, **(headers or {})} | |
| headers = {**(headers or {})} | |
| if data and method == 'GET': | |
| url = f"{url}?{urlencode(data)}" | |
| request = req.Request(url, method=method, headers=headers) | |
| if data and method != 'GET': | |
| request.add_header("Content-Type", "application/json") | |
| request.data = json.dumps(data).encode() | |
| try: | |
| return req.urlopen(request).read().decode() | |
| except urllib.error.HTTPError as e: | |
| body = e.read().decode(errors="replace") | |
| raise Exception( | |
| f"HTTP {e.code} {e.reason}\n" | |
| f"URL: {e.url}\n" | |
| f"Response:\n{body}" | |
| ) | |
| def post_json(url: str, data: dict, headers: dict = None) -> dict: | |
| response = fetch(url, method='POST', data=data, headers=headers) | |
| return json.loads(response) | |
| # --------------------------------------------------------------------------- | |
| # llm.py (inlined) | |
| # --------------------------------------------------------------------------- | |
| API_URL = "https://openrouter.ai/api/v1/chat/completions" | |
| API_KEY = os.getenv("OPENROUTER_API_KEY") | |
| FLASH = "deepseek/deepseek-v4-flash" | |
| PRO = "xiaomi/mimo-v2.5-pro" | |
| PROVIDER_MAP = { | |
| FLASH: "alibaba", | |
| PRO: "xiaomi", | |
| } | |
| def chat( | |
| messages, | |
| model: str = FLASH, | |
| reasoning_effort: str = "default", | |
| **kw, | |
| ) -> str: | |
| def _to_messages(input): | |
| if isinstance(input, str): | |
| return [{"role": "user", "content": input}] | |
| return input | |
| payload = { | |
| "model": model, | |
| "messages": messages, | |
| "stream": False, | |
| **kw, | |
| } | |
| provider = PROVIDER_MAP.get(model) | |
| if provider: | |
| payload["provider"] = { | |
| "only": [provider], | |
| "allow_fallbacks": False, | |
| } | |
| if reasoning_effort == "default": | |
| payload["reasoning"] = { | |
| "enabled": True, | |
| } | |
| elif reasoning_effort is not None: | |
| payload["reasoning"] = { | |
| "effort": reasoning_effort, | |
| } | |
| headers = { | |
| "Content-Type": "application/json", | |
| "Authorization": f"Bearer {API_KEY}", | |
| } | |
| result = post_json(API_URL, payload, headers) | |
| return result["choices"][0]["message"]["content"] | |
| def chat_flash(messages, **kw): | |
| return chat(messages, model=FLASH, **kw) | |
| def chat_flash_nr(messages, **kw): | |
| return chat(messages, model=FLASH, reasoning_effort="none", **kw) | |
| def chat_pro(messages, **kw): | |
| return chat(messages, model=PRO, **kw) | |
| def chat_pro_nr(messages, **kw): | |
| return chat(messages, model=PRO, reasoning_effort="none", **kw) | |
| # --------------------------------------------------------------------------- | |
| # main.py logic | |
| # --------------------------------------------------------------------------- | |
| def get_cmd(lm_output: str) -> str: | |
| matches = re.findall( | |
| r"```bash-action\s*\n(.*?)\n```", | |
| lm_output, | |
| re.DOTALL | |
| ) | |
| return matches[0].strip() if matches else "" | |
| def run_cmd(command: str) -> str: | |
| result = subprocess.run( | |
| command, | |
| shell=True, | |
| text=True, | |
| env=os.environ, | |
| encoding='utf-8', | |
| errors='replace', | |
| stdout=subprocess.PIPE, | |
| stderr=subprocess.STDOUT, | |
| timeout=30, | |
| ) | |
| return result.stdout | |
| def main(): | |
| # Use chat_flash as the default model | |
| SYSTEM = "You are a helpful assistant. When you want to run a command, wrap it in ```bash-action\n<command>\n```. To finish a turn, run the exit command." | |
| messages = [] | |
| messages.append({"role": "system", "content": SYSTEM}) | |
| while True: | |
| user_msg = input("> ") | |
| messages.append({"role": "user", "content": user_msg}) | |
| print() | |
| while True: | |
| lm_output = chat_flash(messages) | |
| print("Agent:\n", lm_output, "\n") | |
| messages.append({"role": "assistant", "content": lm_output}) | |
| cmd = get_cmd(lm_output) | |
| if not cmd: | |
| break | |
| if cmd == "exit": | |
| return | |
| output = run_cmd(cmd) | |
| print("Output:\n", output, "\n") | |
| messages.append({"role": "user", "content": output}) | |
| if __name__ == '__main__': | |
| main() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Shouldn’t it be
reasoning_effort=None? (in thechatfunction above you compare withNone)