File size: 6,250 Bytes
f786ba3
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
"""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 <code>AGENTS.md</code> and are loaded verbatim at startup. "
        f"Model: <code>{MODEL_ID}</code>. 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()