Spaces:
Runtime error
Runtime error
Download agent.py from evaleval/best-model-finder: direct link, hf CLI and curl.
- Browser
- Download file 6.78 kB
-
https://huggingface.co/spaces/evaleval/best-model-finder/resolve/main/agent.py
- Command line
-
hf download hf://spaces/evaleval/best-model-finder/agent.py
-
curl -L -o agent.py https://huggingface.co/spaces/evaleval/best-model-finder/resolve/main/agent.py
6.78 kB
| """A small JSON-action agent loop over the EEE warehouse tools. | |
| Works with any chat model on HF Inference Providers (no native function | |
| calling required): the model emits one JSON action per turn, we execute it | |
| and feed the result back. Billing goes to whoever owns the token — with the | |
| Space's OAuth login, that is the signed-in visitor. | |
| """ | |
| from __future__ import annotations | |
| import json | |
| from typing import Any, Generator | |
| from huggingface_hub import InferenceClient | |
| import datastore | |
| MAX_STEPS = 10 | |
| MAX_TOOL_RESULT_CHARS = 6000 | |
| SYSTEM_PROMPT = f"""You are Best Model Finder, an agent that recommends AI models for a user's \ | |
| use case using ONLY evidence from the EvalEval EEE datastore (765 real evaluation leaderboards, \ | |
| 5,700+ models, third-party and first-party results). | |
| You act by replying with EXACTLY ONE JSON object per turn — no prose outside the JSON. | |
| Actions available: | |
| 1. {{"thought": "...", "action": "search_evaluations", "args": {{"query": "keywords", "tags": [], "limit": 8}}}} | |
| Keyword search over evaluation leaderboards (names, benchmark cards, domains). | |
| Results are already ranked to favour up-to-date benchmarks (each carries a | |
| "newest_model_date"); prefer the more recent ones when relevance is similar. | |
| Optional "tags" filter, from: {json.dumps(datastore.ALL_TAGS)} | |
| 2. {{"thought": "...", "action": "get_leaderboard", "args": {{"evaluation_id": "<exact id from search>", "limit": 12, "open_weights_only": false, "max_params_b": null}}}} | |
| Ranked model scores for one evaluation. Respect the user's constraints via the filters. | |
| 3. {{"thought": "...", "action": "get_model_profile", "args": {{"model_id": "org/model"}}}} | |
| Full profile of a candidate model (params, openness, coverage across benchmarks, top scores). | |
| 4. {{"thought": "...", "action": "final", "args": {{"summary": "2-4 sentence answer in plain language", | |
| "recommendations": [{{"model_id": "org/model", "model_name": "...", "why": "one concrete, evidence-based sentence", | |
| "evidence": [{{"evaluation": "name", "score": "0.79 (rank 1 of 70)"}}]}}]}}}} | |
| Strategy: | |
| - Run 2-3 search_evaluations calls with DIFFERENT keyword angles for the use case (task type, domain, capability). | |
| - Pull leaderboards for the 2-3 most relevant evaluations. Prefer leaderboards with more models. | |
| - Cross-check: a good recommendation scores well on more than one relevant evaluation. Use get_model_profile on your top candidate. | |
| - Honor constraints the user states (open weights, size/cost, latency proxies like small params, multilingual, safety). | |
| - Recommend 1-3 models, ranked. Every "why" must cite actual scores/ranks you retrieved. Never invent scores. | |
| - If the datastore has no relevant evaluation, say so honestly in final.summary instead of guessing. | |
| - Be efficient: you have at most {MAX_STEPS} turns.""" | |
| def _extract_json(text: str) -> dict | None: | |
| """Pull the first balanced JSON object out of a model reply.""" | |
| text = text.strip() | |
| if text.startswith("```"): | |
| text = text.split("```", 2)[1] | |
| if text.startswith("json"): | |
| text = text[4:] | |
| start = text.find("{") | |
| if start == -1: | |
| return None | |
| depth, in_str, esc = 0, False, False | |
| for i in range(start, len(text)): | |
| c = text[i] | |
| if in_str: | |
| if esc: | |
| esc = False | |
| elif c == "\\": | |
| esc = True | |
| elif c == '"': | |
| in_str = False | |
| elif c == '"': | |
| in_str = True | |
| elif c == "{": | |
| depth += 1 | |
| elif c == "}": | |
| depth -= 1 | |
| if depth == 0: | |
| try: | |
| return json.loads(text[start:i + 1]) | |
| except json.JSONDecodeError: | |
| return None | |
| return None | |
| def run_agent(use_case: str, constraints: str, llm_model: str, token: str, | |
| ) -> Generator[dict[str, Any], None, None]: | |
| """Yields events: {'type': 'thought'|'tool'|'final'|'error', ...}.""" | |
| client = InferenceClient(provider="auto", api_key=token) | |
| user_msg = f"Use case: {use_case.strip()}" | |
| if constraints.strip(): | |
| user_msg += f"\nHard constraints: {constraints.strip()}" | |
| messages: list[dict] = [ | |
| {"role": "system", "content": SYSTEM_PROMPT}, | |
| {"role": "user", "content": user_msg}, | |
| ] | |
| for step in range(1, MAX_STEPS + 1): | |
| try: | |
| resp = client.chat.completions.create( | |
| model=llm_model, messages=messages, max_tokens=1500, temperature=0.2) | |
| reply = resp.choices[0].message.content or "" | |
| except Exception as e: # surface provider/auth errors to the UI | |
| yield {"type": "error", "message": f"Inference call failed: {e}"} | |
| return | |
| obj = _extract_json(reply) | |
| messages.append({"role": "assistant", "content": reply}) | |
| if obj is None or "action" not in obj: | |
| messages.append({"role": "user", "content": | |
| "That was not a valid action. Reply with exactly one JSON object " | |
| "using the schema from the instructions."}) | |
| continue | |
| thought = str(obj.get("thought") or "").strip() | |
| action = obj["action"] | |
| args = obj.get("args") or {} | |
| if thought: | |
| yield {"type": "thought", "step": step, "text": thought} | |
| if action == "final": | |
| yield {"type": "final", "step": step, | |
| "summary": str(args.get("summary") or ""), | |
| "recommendations": args.get("recommendations") or []} | |
| return | |
| fn = datastore.TOOLS.get(action) | |
| if fn is None: | |
| messages.append({"role": "user", "content": | |
| f"Unknown action '{action}'. Valid: " | |
| f"{list(datastore.TOOLS)} or 'final'."}) | |
| continue | |
| try: | |
| result = fn(**{k: v for k, v in args.items() if v is not None}) | |
| except TypeError as e: | |
| result = {"error": f"Bad arguments for {action}: {e}"} | |
| except Exception as e: | |
| result = {"error": f"{action} failed: {e}"} | |
| yield {"type": "tool", "step": step, "action": action, "args": args, "result": result} | |
| payload = json.dumps(result, ensure_ascii=False, default=str) | |
| if len(payload) > MAX_TOOL_RESULT_CHARS: | |
| payload = payload[:MAX_TOOL_RESULT_CHARS] + '... (truncated)"}' | |
| messages.append({"role": "user", | |
| "content": f"TOOL_RESULT {action}:\n{payload}\n\nNext JSON action:"}) | |
| yield {"type": "error", | |
| "message": "The agent hit its step limit without a final answer. " | |
| "Try a more specific use case, or a stronger search model."} | |