|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | +import signal |
| 4 | +from functools import partial |
| 5 | +from typing import Any, Dict, List, Optional |
| 6 | + |
| 7 | +import typer |
| 8 | +from rich import print |
| 9 | + |
| 10 | +from .agent import Agent |
| 11 | +from .utils import _load_agent_config |
| 12 | + |
| 13 | + |
| 14 | +app = typer.Typer( |
| 15 | + rich_markup_mode="rich", |
| 16 | + help="A squad of lightweight composable AI applications built on Hugging Face's Inference Client and MCP stack.", |
| 17 | +) |
| 18 | + |
| 19 | +run_cli = typer.Typer( |
| 20 | + name="run", |
| 21 | + help="Run the Agent in the CLI", |
| 22 | + invoke_without_command=True, |
| 23 | +) |
| 24 | +app.add_typer(run_cli, name="run") |
| 25 | + |
| 26 | + |
| 27 | +async def _ainput(prompt: str = "» ") -> str: |
| 28 | + loop = asyncio.get_running_loop() |
| 29 | + return await loop.run_in_executor(None, partial(typer.prompt, prompt, prompt_suffix=" ")) |
| 30 | + |
| 31 | + |
| 32 | +async def run_agent( |
| 33 | + agent_path: Optional[str], |
| 34 | +) -> None: |
| 35 | + """ |
| 36 | + Tiny Agent loop. |
| 37 | +
|
| 38 | + Args: |
| 39 | + agent_path (`str`, *optional*): |
| 40 | + Path to a local folder containing an `agent.json` and optionally a custom `PROMPT.md` file or a built-in agent stored in a Hugging Face dataset. |
| 41 | +
|
| 42 | + """ |
| 43 | + config, prompt = _load_agent_config(agent_path) |
| 44 | + |
| 45 | + servers: List[Dict[str, Any]] = config.get("servers", []) |
| 46 | + |
| 47 | + abort_event = asyncio.Event() |
| 48 | + first_sigint = True |
| 49 | + |
| 50 | + loop = asyncio.get_running_loop() |
| 51 | + original_sigint_handler = signal.getsignal(signal.SIGINT) |
| 52 | + |
| 53 | + def _sigint_handler() -> None: |
| 54 | + nonlocal first_sigint |
| 55 | + if first_sigint: |
| 56 | + first_sigint = False |
| 57 | + abort_event.set() |
| 58 | + print("\n[red]Interrupted. Press Ctrl+C again to quit.[/red]", flush=True) |
| 59 | + return |
| 60 | + |
| 61 | + print("\n[red]Exiting...[/red]", flush=True) |
| 62 | + |
| 63 | + os._exit(130) |
| 64 | + |
| 65 | + try: |
| 66 | + loop.add_signal_handler(signal.SIGINT, _sigint_handler) |
| 67 | + |
| 68 | + async with Agent( |
| 69 | + provider=config["provider"], |
| 70 | + model=config["model"], |
| 71 | + servers=servers, |
| 72 | + prompt=prompt, |
| 73 | + ) as agent: |
| 74 | + await agent.load_tools() |
| 75 | + print(f"[bold blue]Agent loaded with {len(agent.available_tools)} tools:[/bold blue]") |
| 76 | + for t in agent.available_tools: |
| 77 | + print(f"[blue] • {t.function.name}[/blue]") |
| 78 | + |
| 79 | + while True: |
| 80 | + abort_event.clear() |
| 81 | + |
| 82 | + try: |
| 83 | + user_input = await _ainput() |
| 84 | + first_sigint = True |
| 85 | + except EOFError: |
| 86 | + print("\n[red]EOF received, exiting.[/red]", flush=True) |
| 87 | + break |
| 88 | + except KeyboardInterrupt: |
| 89 | + if not first_sigint and abort_event.is_set(): |
| 90 | + continue |
| 91 | + else: |
| 92 | + print("\n[red]Keyboard interrupt during input processing.[/red]", flush=True) |
| 93 | + break |
| 94 | + |
| 95 | + try: |
| 96 | + async for chunk in agent.run(user_input, abort_event=abort_event): |
| 97 | + if abort_event.is_set() and not first_sigint: |
| 98 | + break |
| 99 | + |
| 100 | + if hasattr(chunk, "choices"): |
| 101 | + delta = chunk.choices[0].delta |
| 102 | + if delta.content: |
| 103 | + print(delta.content, end="", flush=True) |
| 104 | + if delta.tool_calls: |
| 105 | + for call in delta.tool_calls: |
| 106 | + if call.id: |
| 107 | + print(f"<Tool {call.id}>", end="") |
| 108 | + if call.function.name: |
| 109 | + print(f"{call.function.name}", end=" ") |
| 110 | + if call.function.arguments: |
| 111 | + print(f"{call.function.arguments}", end="") |
| 112 | + else: |
| 113 | + print( |
| 114 | + f"\n\n[green]Tool[{chunk.name}] {chunk.tool_call_id}\n{chunk.content}[/green]\n", |
| 115 | + flush=True, |
| 116 | + ) |
| 117 | + |
| 118 | + print() |
| 119 | + |
| 120 | + except Exception as e: |
| 121 | + print(f"\n[bold red]Error during agent run: {e}[/bold red]", flush=True) |
| 122 | + first_sigint = True # Allow graceful interrupt for the next command |
| 123 | + |
| 124 | + finally: |
| 125 | + if loop and not loop.is_closed(): |
| 126 | + loop.remove_signal_handler(signal.SIGINT) |
| 127 | + elif original_sigint_handler: |
| 128 | + signal.signal(signal.SIGINT, original_sigint_handler) |
| 129 | + |
| 130 | + |
| 131 | +@run_cli.callback() |
| 132 | +def run( |
| 133 | + path: Optional[str] = typer.Argument( |
| 134 | + None, |
| 135 | + help=( |
| 136 | + "Path to a local folder containing an agent.json file or a built-in agent " |
| 137 | + "stored in a Hugging Face dataset (default: " |
| 138 | + "https://huggingface.co/datasets/tiny-agents/tiny-agents)" |
| 139 | + ), |
| 140 | + ), |
| 141 | +): |
| 142 | + try: |
| 143 | + asyncio.run(run_agent(path)) |
| 144 | + except KeyboardInterrupt: |
| 145 | + print("\n[red]Application terminated by KeyboardInterrupt.[/red]", flush=True) |
| 146 | + raise typer.Exit(code=130) |
| 147 | + except Exception as e: |
| 148 | + print(f"\n[bold red]An unexpected error occurred: {e}[/bold red]", flush=True) |
| 149 | + raise e |
| 150 | + |
| 151 | + |
| 152 | +if __name__ == "__main__": |
| 153 | + app() |
0 commit comments