"""Hub Scout — an AGENTS.md-driven agent. The agent's entire instruction set lives in AGENTS.md, loaded verbatim at startup and passed as the system prompt. app.py only wires tools and the chat loop; edit AGENTS.md to change behavior. Run locally: export HF_TOKEN=hf_... # token with Inference access pip install -r requirements.txt python app.py # opens http://127.0.0.1:7860 """ import json import os import gradio as gr from huggingface_hub import HfApi, InferenceClient HERE = os.path.dirname(os.path.abspath(__file__)) MODEL_ID = os.environ.get("AGENT_MODEL", "Qwen/Qwen2.5-72B-Instruct") HF_TOKEN = os.environ.get("HF_TOKEN") with open(os.path.join(HERE, "AGENTS.md"), encoding="utf-8") as f: AGENTS_MD = f.read() assert AGENTS_MD.strip(), "AGENTS.md is empty — the agent would have no instructions" client = InferenceClient(model=MODEL_ID, provider="auto", token=HF_TOKEN) hf_api = HfApi(token=HF_TOKEN) TOOLS = [ { "type": "function", "function": { "name": "search_hf_models", "description": ( "Search the Hugging Face Hub for model repos matching keywords, " "ranked by likes. Returns repo ids with likes and downloads." ), "parameters": { "type": "object", "properties": { "query": { "type": "string", "description": "Search keywords, e.g. 'multilingual embeddings'", }, "limit": { "type": "integer", "description": "How many results to return (default 5, max 10)", }, "task": { "type": "string", "description": ( "Optional pipeline_tag filter, e.g. 'text-generation', " "'feature-extraction', 'text-classification'" ), }, }, "required": ["query"], }, }, }, { "type": "function", "function": { "name": "get_model_stats", "description": ( "Get current stats for one model repo: downloads, likes, " "pipeline tag and last-modified date." ), "parameters": { "type": "object", "properties": { "repo_id": { "type": "string", "description": "Model repo id, e.g. 'Qwen/Qwen2.5-72B-Instruct'", } }, "required": ["repo_id"], }, }, }, ] def _search_hf_models(query, limit=5, task=None): limit = max(1, min(int(limit or 5), 10)) kwargs = {"search": query, "limit": limit, "sort": "likes", "direction": -1} if task: kwargs["pipeline_tag"] = task lines = [ f"- {m.id} (likes={getattr(m, 'likes', '?')}, downloads={getattr(m, 'downloads', '?')})" for m in hf_api.list_models(**kwargs) ] return "\n".join(lines) if lines else "No models matched that query." def _get_model_stats(repo_id): info = hf_api.model_info(repo_id) return ( f"{info.id}: pipeline_tag={getattr(info, 'pipeline_tag', None)}, " f"downloads={getattr(info, 'downloads', None)}, likes={getattr(info, 'likes', None)}, " f"lastModified={getattr(info, 'lastModified', None)}" ) def run_tool(name, arguments): try: args = json.loads(arguments or "{}") except json.JSONDecodeError: return f"Invalid JSON arguments: {arguments!r}" try: if name == "search_hf_models": return _search_hf_models(args["query"], args.get("limit", 5), args.get("task")) if name == "get_model_stats": return _get_model_stats(args["repo_id"]) return f"Unknown tool: {name}" except Exception as exc: return f"Tool '{name}' failed: {type(exc).__name__}: {exc}" MAX_TOOL_ROUNDS = 3 def run_agent(message, history): """history is OpenAI-style dicts: {"role": "user"|"assistant", "content": str}.""" messages = [{"role": "system", "content": AGENTS_MD}] messages.extend(history) messages.append({"role": "user", "content": message}) reply = "" msg = None for _ in range(MAX_TOOL_ROUNDS): resp = client.chat_completion( messages=messages, tools=TOOLS, tool_choice="auto", max_tokens=1024 ) msg = resp.choices[0].message calls = getattr(msg, "tool_calls", None) or [] if not calls: reply = msg.content or "" break # Record the assistant's tool-call turn, run each tool, feed results back. messages.append( { "role": "assistant", "content": msg.content or "", "tool_calls": [ { "id": tc.id, "type": "function", "function": { "name": tc.function.name, "arguments": tc.function.arguments, }, } for tc in calls ], } ) for tc in calls: result = run_tool(tc.function.name, tc.function.arguments) messages.append({"role": "tool", "tool_call_id": tc.id, "content": result}) else: reply = msg.content or "(I stopped after 3 tool rounds.)" return reply demo = gr.ChatInterface( fn=run_agent, title="Hub Scout — an AGENTS.md agent", description=( f"Instructions live in AGENTS.md and are loaded verbatim at startup. " f"Model: {MODEL_ID}. Tools: search_hf_models, get_model_stats." ), examples=[ "Find me a small chat model that runs on a laptop CPU.", "What's the most downloaded sentence-embedding model right now?", "How actively used is Qwen/Qwen2.5-72B-Instruct?", ], ) if __name__ == "__main__": demo.launch()