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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
agents.py β Multi-provider agent runner.
|
| 3 |
+
|
| 4 |
+
Supported providers (set per-agent in config.yaml):
|
| 5 |
+
anthropic β Anthropic Claude (claude-sonnet-4-6, claude-opus-4-6, etc.)
|
| 6 |
+
groq β Groq (free tier, very fast) β llama-3.3-70b-versatile, mixtral-8x7b, etc.
|
| 7 |
+
nvidia β NVIDIA NIM ($200 free credits) β meta/llama-3.3-70b-instruct, etc.
|
| 8 |
+
huggingface β HuggingFace Inference API (free, rate-limited)
|
| 9 |
+
kimi β Moonshot AI / Kimi β moonshot-v1-8k, moonshot-v1-32k, etc.
|
| 10 |
+
openai β OpenAI β gpt-4o, gpt-4o-mini, etc.
|
| 11 |
+
custom β Any OpenAI-compatible endpoint (set base_url in config)
|
| 12 |
+
|
| 13 |
+
Each agent picks its provider independently, so you can mix and match freely.
|
| 14 |
+
"""
|
| 15 |
+
|
| 16 |
+
import os
|
| 17 |
+
import time
|
| 18 |
+
from typing import Optional
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
# ββ Provider routing ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 22 |
+
|
| 23 |
+
# OpenAI-compatible base URLs for known providers.
|
| 24 |
+
# These are used when base_url is not explicitly set in config.yaml.
|
| 25 |
+
PROVIDER_DEFAULTS = {
|
| 26 |
+
"groq": "https://api.groq.com/openai/v1",
|
| 27 |
+
"nvidia": "https://integrate.api.nvidia.com/v1",
|
| 28 |
+
"huggingface": "https://api-inference.huggingface.co/v1",
|
| 29 |
+
"kimi": "https://api.moonshot.cn/v1",
|
| 30 |
+
"openai": None, # openai SDK uses its default
|
| 31 |
+
"together": "https://api.together.xyz/v1",
|
| 32 |
+
"mistral": "https://api.mistral.ai/v1",
|
| 33 |
+
}
|
| 34 |
+
|
| 35 |
+
# Default env var names per provider (override with api_key_env in config.yaml)
|
| 36 |
+
PROVIDER_KEY_ENVS = {
|
| 37 |
+
"anthropic": "ANTHROPIC_API_KEY",
|
| 38 |
+
"groq": "GROQ_API_KEY",
|
| 39 |
+
"nvidia": "NVIDIA_API_KEY",
|
| 40 |
+
"huggingface": "HF_TOKEN",
|
| 41 |
+
"kimi": "MOONSHOT_API_KEY",
|
| 42 |
+
"openai": "OPENAI_API_KEY",
|
| 43 |
+
"together": "TOGETHER_API_KEY",
|
| 44 |
+
"mistral": "MISTRAL_API_KEY",
|
| 45 |
+
"custom": "CUSTOM_API_KEY",
|
| 46 |
+
}
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
def _get_api_key(agent_config: dict) -> str:
|
| 50 |
+
"""Read the API key from the environment."""
|
| 51 |
+
provider = agent_config.get("provider", "anthropic")
|
| 52 |
+
env_var = agent_config.get("api_key_env") or PROVIDER_KEY_ENVS.get(provider, "API_KEY")
|
| 53 |
+
key = os.environ.get(env_var, "")
|
| 54 |
+
if not key:
|
| 55 |
+
raise EnvironmentError(
|
| 56 |
+
f"API key not found. Set the '{env_var}' environment variable "
|
| 57 |
+
f"for the '{provider}' provider.\n"
|
| 58 |
+
f" export {env_var}='your-key-here'"
|
| 59 |
+
)
|
| 60 |
+
return key
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
def _call_anthropic(agent_config: dict, user_input: str) -> tuple[str, int, int]:
|
| 64 |
+
"""Call the Anthropic API. Returns (content, input_tokens, output_tokens)."""
|
| 65 |
+
import anthropic
|
| 66 |
+
|
| 67 |
+
key = _get_api_key(agent_config)
|
| 68 |
+
client = anthropic.Anthropic(api_key=key)
|
| 69 |
+
|
| 70 |
+
response = client.messages.create(
|
| 71 |
+
model=agent_config["model"],
|
| 72 |
+
max_tokens=agent_config.get("max_tokens", 4096),
|
| 73 |
+
temperature=agent_config.get("temperature", 0.7),
|
| 74 |
+
system=agent_config["system_prompt"].strip(),
|
| 75 |
+
messages=[{"role": "user", "content": user_input}],
|
| 76 |
+
)
|
| 77 |
+
|
| 78 |
+
content = response.content[0].text
|
| 79 |
+
return content, response.usage.input_tokens, response.usage.output_tokens
|
| 80 |
+
|
| 81 |
+
|
| 82 |
+
def _call_openai_compat(agent_config: dict, user_input: str) -> tuple[str, int, int]:
|
| 83 |
+
"""
|
| 84 |
+
Call any OpenAI-compatible API (Groq, NVIDIA, HuggingFace, Kimi, OpenAI, customβ¦).
|
| 85 |
+
Returns (content, input_tokens, output_tokens).
|
| 86 |
+
"""
|
| 87 |
+
import openai
|
| 88 |
+
|
| 89 |
+
provider = agent_config.get("provider", "openai")
|
| 90 |
+
key = _get_api_key(agent_config)
|
| 91 |
+
|
| 92 |
+
# Resolve base URL: explicit config overrides provider default
|
| 93 |
+
base_url = agent_config.get("base_url") or PROVIDER_DEFAULTS.get(provider)
|
| 94 |
+
|
| 95 |
+
client = openai.OpenAI(api_key=key, base_url=base_url)
|
| 96 |
+
|
| 97 |
+
response = client.chat.completions.create(
|
| 98 |
+
model=agent_config["model"],
|
| 99 |
+
max_tokens=agent_config.get("max_tokens", 4096),
|
| 100 |
+
temperature=agent_config.get("temperature", 0.7),
|
| 101 |
+
messages=[
|
| 102 |
+
{"role": "system", "content": agent_config["system_prompt"].strip()},
|
| 103 |
+
{"role": "user", "content": user_input},
|
| 104 |
+
],
|
| 105 |
+
)
|
| 106 |
+
|
| 107 |
+
content = response.choices[0].message.content or ""
|
| 108 |
+
usage = response.usage
|
| 109 |
+
input_tokens = usage.prompt_tokens if usage else 0
|
| 110 |
+
output_tokens = usage.completion_tokens if usage else 0
|
| 111 |
+
return content, input_tokens, output_tokens
|
| 112 |
+
|
| 113 |
+
|
| 114 |
+
# ββ Public API ββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ
|
| 115 |
+
|
| 116 |
+
def run_agent(
|
| 117 |
+
agent_config: dict,
|
| 118 |
+
model: Optional[str], # global default model (can be overridden per-agent)
|
| 119 |
+
user_input: str,
|
| 120 |
+
stage: str,
|
| 121 |
+
verbose: bool = True,
|
| 122 |
+
) -> dict:
|
| 123 |
+
"""
|
| 124 |
+
Run a single agent using the provider specified in agent_config.
|
| 125 |
+
|
| 126 |
+
agent_config keys (all from config.yaml):
|
| 127 |
+
provider β 'anthropic' | 'groq' | 'nvidia' | 'huggingface' | 'kimi' | 'openai' | 'custom'
|
| 128 |
+
model β model name for this agent (overrides global model)
|
| 129 |
+
api_key_env β env var name for API key (optional, defaults per provider)
|
| 130 |
+
base_url β custom API endpoint (optional, for 'custom' provider or overrides)
|
| 131 |
+
temperature β float 0β1
|
| 132 |
+
max_tokens β int
|
| 133 |
+
system_prompt β str
|
| 134 |
+
name β display name
|
| 135 |
+
|
| 136 |
+
Returns a result dict with stage, agent_name, content, token counts, duration.
|
| 137 |
+
"""
|
| 138 |
+
provider = agent_config.get("provider", "anthropic")
|
| 139 |
+
|
| 140 |
+
# Per-agent model takes priority over global default
|
| 141 |
+
effective_model = agent_config.get("model") or model or "claude-sonnet-4-6"
|
| 142 |
+
agent_config = {**agent_config, "model": effective_model}
|
| 143 |
+
|
| 144 |
+
if verbose:
|
| 145 |
+
print(f" β [{provider.upper()}] {agent_config['name']} ({effective_model})...")
|
| 146 |
+
|
| 147 |
+
start = time.time()
|
| 148 |
+
|
| 149 |
+
try:
|
| 150 |
+
if provider == "anthropic":
|
| 151 |
+
content, input_tok, output_tok = _call_anthropic(agent_config, user_input)
|
| 152 |
+
else:
|
| 153 |
+
content, input_tok, output_tok = _call_openai_compat(agent_config, user_input)
|
| 154 |
+
except Exception as e:
|
| 155 |
+
raise RuntimeError(
|
| 156 |
+
f"Agent '{agent_config['name']}' ({provider}) failed: {e}"
|
| 157 |
+
) from e
|
| 158 |
+
|
| 159 |
+
duration = round(time.time() - start, 2)
|
| 160 |
+
|
| 161 |
+
if verbose:
|
| 162 |
+
total_tok = input_tok + output_tok
|
| 163 |
+
tok_str = f"{total_tok:,} tokens" if total_tok else "tokens unavailable"
|
| 164 |
+
print(f" β {agent_config['name']} done ({tok_str}, {duration}s)")
|
| 165 |
+
|
| 166 |
+
return {
|
| 167 |
+
"stage": stage,
|
| 168 |
+
"agent_name": agent_config["name"],
|
| 169 |
+
"provider": provider,
|
| 170 |
+
"model": effective_model,
|
| 171 |
+
"content": content,
|
| 172 |
+
"input_tokens": input_tok,
|
| 173 |
+
"output_tokens": output_tok,
|
| 174 |
+
"duration_s": duration,
|
| 175 |
+
}
|