From fd4bed7481452ceadeb1bc785d96edb2f6778ca8 Mon Sep 17 00:00:00 2001 From: ZhuLinsen Date: Sun, 11 Oct 2026 20:36:17 +0800 Subject: [PATCH] feat: unify async model calls with isolated provider credentials --- .env.example | 13 +++-- docs/CHANGELOG.md | 1 + docs/lean-harness.md | 22 ++++++++ miniagent/agent.py | 7 +-- miniagent/config.py | 61 +++++++++++----------- miniagent/harness.py | 8 ++- miniagent/llm.py | 117 +++++++++++++++++++++++++++++++++++++++++++ pyproject.toml | 2 + tests/test_llm.py | 97 +++++++++++++++++++++++++++++++++++ 9 files changed, 290 insertions(+), 38 deletions(-) create mode 100644 miniagent/llm.py create mode 100644 tests/test_llm.py diff --git a/.env.example b/.env.example index b37c0ee..545b09c 100644 --- a/.env.example +++ b/.env.example @@ -33,8 +33,11 @@ LLM_API_BASE=https://api.deepseek.com/v1 # ===== Optional: Web search ===== # SERPAPI_KEY=your_serpapi_key_here -# ===== Optional: Multi-provider aliases ===== -# MiniAgent also reads OPENAI_API_KEY, DEEPSEEK_API_KEY, GEMINI_API_KEY, -# GOOGLE_API_KEY, ANTHROPIC_API_KEY, AZURE_OPENAI_API_KEY as fallbacks -# if LLM_API_KEY is not set. -# See config.py for full fallback chain. +# ===== Provider isolation ===== +# Prefer LLM_MODEL=provider:model-id with that provider's own credential. +# OPENAI_API_KEY, DEEPSEEK_API_KEY, ANTHROPIC_API_KEY, DASHSCOPE_API_KEY, etc. +# LLM_API_KEY and LLM_API_BASE are explicit compatibility endpoint overrides. +# Keys from unrelated providers are never searched as a fallback chain. +# MINIAGENT_TEST_MODEL=provider:model-id # opt-in live smoke test only +# Custom endpoints are configured in JSON: providers. with +# type=openai-compatible, base_url, api_key_env; then LLM_MODEL=:. diff --git a/docs/CHANGELOG.md b/docs/CHANGELOG.md index 8e43dbc..00aba4a 100644 --- a/docs/CHANGELOG.md +++ b/docs/CHANGELOG.md @@ -7,3 +7,4 @@ - [文档] 记录六阶段迁移、权限边界和可复现源码统计。 - [新功能] 异步 Harness、实例级工具、静态插件生命周期和统一授权入口。 - [改进] Python 最低版本提升至 3.11,打包元数据统一到 pyproject.toml。 +- [新功能] any-llm 异步模型适配、自定义 Provider、完整流式工具组装及 Provider 密钥隔离。 diff --git a/docs/lean-harness.md b/docs/lean-harness.md index 823c4b2..9408220 100644 --- a/docs/lean-harness.md +++ b/docs/lean-harness.md @@ -32,3 +32,25 @@ Windows baseline: 189 passed, 2 failures caused by Unix-only `sleep` in timeout tests. Those tests now invoke the running Python interpreter on every platform. Original commit `4d61483d039e802f6d34fb6b42d6e2a99b1b6a1c`: 20 files, 4,009 physical lines, 3,288 nonempty lines. + +## Models + +Python >=3.11; validated SDK: any-llm-sdk 1.33.0. SDK HTTP normalization and +stream assembly are tested without a remote service. Real DeepSeek/Qwen/Claude +calls have not been validated without explicit test credentials. +Use `Harness(model="provider:model-id")` with the provider's environment key. +Custom JSON configuration: + +```json +{"llm": {"model": "gateway:model-id"}, "providers": {"gateway": { + "type": "openai-compatible", "base_url": "https://example.com/v1", + "api_key_env": "GATEWAY_API_KEY" +}}} +``` + +Pass `providers=cfg.providers` to Harness. Empty key configuration is supported +only for explicitly configured keyless custom endpoints. Base URL overrides +use compatibility mode. Native provider clients retain SDK retry behavior; +custom endpoints disable retries. The loop never retries tools or interrupted +streams. `temperature=None` leaves provider defaults unchanged. +Run live tests with `MINIAGENT_TEST_MODEL` and `python -m pytest -m live -v`. diff --git a/miniagent/agent.py b/miniagent/agent.py index cf4733a..58adadf 100644 --- a/miniagent/agent.py +++ b/miniagent/agent.py @@ -852,7 +852,8 @@ async def agent_loop(app, query, *, max_steps=10, stream=None): """Native loop shared by the Harness; messages never contain SDK objects.""" if max_steps < 1: raise ValueError("max_steps must be positive") - if app.backend is None: + backend = app.backend or app.services.get("llm") + if backend is None: raise ValueError("An LLM backend is required") if not app.messages: app.messages.append({"role": "system", "content": app.system_prompt}) @@ -860,8 +861,8 @@ async def agent_loop(app, query, *, max_steps=10, stream=None): for step in range(max_steps): await app.emit("agent.step", step=step) await app.emit("llm.request", step=step) - message = await app.backend.complete(app.messages, app.registry.schemas(), stream) - await app.emit("llm.response", usage=getattr(app.backend, "usage", {})) + message = await backend.complete(app.messages, app.registry.schemas(), stream) + await app.emit("llm.response", usage=getattr(backend, "usage", {})) app.messages.append(message) calls = message.get("tool_calls") or [] if not calls: diff --git a/miniagent/config.py b/miniagent/config.py index 2cc133d..6a4fc92 100644 --- a/miniagent/config.py +++ b/miniagent/config.py @@ -41,6 +41,7 @@ class AgentConfig: llm: LLMConfig = field(default_factory=LLMConfig) system_prompt: str = "You are a helpful AI assistant." default_tools: List[str] = field(default_factory=list) + providers: Dict[str, Any] = field(default_factory=dict) enable_reflection: bool = False reflection_system_prompt: Optional[str] = None reflection_max_iterations: int = 3 @@ -65,35 +66,37 @@ def load_config(config_path: Optional[str] = None) -> AgentConfig: # Default configuration config = AgentConfig() - # Try to get API key from environment variables with multiple fallbacks - # Priority order: LLM_API_KEY > OPENAI_API_KEY > DEEPSEEK_API_KEY > GEMINI_API_KEY - # > GOOGLE_API_KEY > ANTHROPIC_API_KEY > AZURE_OPENAI_API_KEY - env_api_key = ( - os.environ.get("LLM_API_KEY") or - os.environ.get("OPENAI_API_KEY") or - os.environ.get("DEEPSEEK_API_KEY") or - os.environ.get("GEMINI_API_KEY") or - os.environ.get("GOOGLE_API_KEY") or - os.environ.get("ANTHROPIC_API_KEY") or - os.environ.get("AZURE_OPENAI_API_KEY") - ) - - if env_api_key: - config.llm.api_key = env_api_key - - # Try to get API base URL from environment variables with multiple fallbacks - # Priority order: LLM_API_BASE > OPENAI_API_BASE > DEEPSEEK_API_BASE > ANTHROPIC_API_BASE > AZURE_OPENAI_ENDPOINT - env_api_base = ( - os.environ.get("LLM_API_BASE") or - os.environ.get("OPENAI_API_BASE") or - os.environ.get("DEEPSEEK_API_BASE") or - os.environ.get("ANTHROPIC_API_BASE") or - os.environ.get("AZURE_OPENAI_ENDPOINT") - ) - - if env_api_base: - config.llm.api_base = env_api_base - + # Explicit compatibility credentials belong to the selected endpoint. + config.llm.api_key = os.environ.get("LLM_API_KEY") + config.llm.api_base = os.environ.get("LLM_API_BASE") + model = os.environ.get("LLM_MODEL", "") + aliases = { + "openai": ("OPENAI_API_KEY", "OPENAI_API_BASE"), + "deepseek": ("DEEPSEEK_API_KEY", "DEEPSEEK_API_BASE"), + "gemini": ("GEMINI_API_KEY", "GEMINI_API_BASE"), + "anthropic": ("ANTHROPIC_API_KEY", "ANTHROPIC_API_BASE"), + "azure": ("AZURE_OPENAI_API_KEY", "AZURE_OPENAI_ENDPOINT"), + } + provider = model.partition(":")[0] if ":" in model else None + if provider is None and config.llm.api_base: + base = config.llm.api_base.lower() + provider = next((p for p in aliases if p in base), None) + if "generativelanguage.googleapis.com" in base: + provider = "gemini" + if provider is None and not config.llm.api_base: + configured = [p for p, (key, base) in aliases.items() + if os.environ.get(key) or os.environ.get(base)] + if len(configured) == 1 and not model: + provider = configured[0] + else: + provider = "openai" + if provider in aliases: + key, base = aliases[provider] + config.llm.api_key = config.llm.api_key or os.environ.get(key) + config.llm.api_base = config.llm.api_base or os.environ.get(base) + if provider == "gemini": + config.llm.api_key = config.llm.api_key or os.environ.get("GOOGLE_API_KEY") + # Try to get organization from environment variables env_organization = os.environ.get("LLM_ORGANIZATION") or os.environ.get("OPENAI_ORGANIZATION") if env_organization: diff --git a/miniagent/harness.py b/miniagent/harness.py index 4fbf2d1..6f9c350 100644 --- a/miniagent/harness.py +++ b/miniagent/harness.py @@ -45,13 +45,19 @@ def cleanup(self, callback, *args): class Harness: - def __init__(self, backend=None, *, policy=None, system_prompt="You are a helpful assistant."): + def __init__(self, backend=None, *, model=None, providers=None, api_key=None, + base_url=None, temperature=None, policy=None, + system_prompt="You are a helpful assistant."): self.services, self.events, self.plugins, self.active = {}, {}, {}, {} self.registry = Registry() self.policy = policy or Policy() self.system_prompt, self.backend = system_prompt, backend self.messages = [] self.busy = False + if model: + from .llm import llm_plugin + self.use(llm_plugin(model, providers=providers, api_key=api_key, + base_url=base_url, temperature=temperature)) def _idle(self): if self.busy: diff --git a/miniagent/llm.py b/miniagent/llm.py new file mode 100644 index 0000000..a75b3c6 --- /dev/null +++ b/miniagent/llm.py @@ -0,0 +1,117 @@ +"""Provider SDK boundary: reusable async client, plain messages and full streams.""" +import inspect +import os + +from any_llm import AnyLLM + +from .harness import Plugin + + +class LLMBackend: + def __init__(self, model, *, providers=None, api_key=None, base_url=None, + temperature=None, timeout=60, client=None): + provider, separator, model_id = model.partition(":") + if not separator: + provider, model_id = "openai", model + if not model_id: + raise ValueError("Model ID is required") + self.model, self.provider = model_id, provider + self.temperature, self.timeout, self.usage = temperature, timeout, {} + if client is not None: + self.client = client + return + custom = (providers or {}).get(provider) + if custom: + if custom.get("type") != "openai-compatible" or not custom.get("base_url"): + raise ValueError("Custom provider requires type and base_url") + env = custom.get("api_key_env") + if env and not api_key and not os.environ.get(env): + raise ValueError(f"Missing provider credential environment: {env}") + self.client = AnyLLM.create_openai_compatible( + name=provider, api_base=custom["base_url"], + api_key=api_key or (os.environ.get(env) if env else "local-no-key"), + unified_exceptions=True, max_retries=0, + ) + elif base_url: + # An explicitly configured compatibility endpoint owns its explicit key. + env = AnyLLM.get_provider_class(provider).ENV_API_KEY_NAME + key = api_key or os.environ.get(env) + if not key: + raise ValueError(f"Missing credential: {env}") + self.client = AnyLLM.create_openai_compatible( + name=provider, api_base=base_url, api_key=key, + unified_exceptions=True, max_retries=0, + ) + else: + self.client = AnyLLM.create(provider, api_key=api_key, unified_exceptions=True) + + async def complete(self, messages, tools, stream=None): + options = {"model": self.model, "messages": messages, "timeout": self.timeout, + "stream": stream is not None} + if tools: + options["tools"] = tools + if self.temperature is not None: + options["temperature"] = self.temperature + response = await self.client.acompletion(**options) + self.usage = {} + if stream is None: + self.usage = response.usage.model_dump() if response.usage else {} + return response.choices[0].message.model_dump(exclude_none=True) + content, calls, reasoning, finish = [], {}, [], None + try: + async for chunk in response: + if chunk.usage: + self.usage = chunk.usage.model_dump() + if not chunk.choices: + continue + choice = chunk.choices[0] + finish = choice.finish_reason or finish + delta = choice.delta + if delta.content: + content.append(delta.content) + result = stream(delta.content) + if inspect.isawaitable(result): + await result + if getattr(delta, "reasoning_content", None): + reasoning.append(delta.reasoning_content) + for part in delta.tool_calls or []: + call = calls.setdefault(part.index, {"id": "", "type": "function", + "function": {"name": "", "arguments": ""}}) + if part.id: + call["id"] += part.id + if part.function: + for field in ("name", "arguments"): + call["function"][field] += getattr(part.function, field) or "" + if finish not in {"stop", "tool_calls"}: + raise RuntimeError("Incomplete LLM stream; no tools executed") + result = {"role": "assistant", "content": "".join(content) or None} + if calls: + ordered = [calls[i] for i in sorted(calls)] + if any(not c["id"] or not c["function"]["name"] for c in ordered): + raise ValueError("Incomplete streamed tool call") + if len({c["id"] for c in ordered}) != len(ordered): + raise ValueError("Duplicate tool call IDs") + result["tool_calls"] = ordered + if reasoning: + result["reasoning_content"] = "".join(reasoning) + return result + finally: + close = getattr(response, "aclose", None) + if close: + await close() + + async def aclose(self): + raw = getattr(self.client, "client", None) + close = getattr(raw, "aclose", None) or getattr(raw, "close", None) + if close: + result = close() + if inspect.isawaitable(result): + await result + + +def llm_plugin(model, **options): + def setup(ctx): + backend = LLMBackend(model, **options) + ctx.cleanup(backend.aclose) + ctx.service("llm", backend) + return Plugin("llm", setup) diff --git a/pyproject.toml b/pyproject.toml index 3168953..cb8cb90 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -34,6 +34,7 @@ classifiers = [ "Topic :: Software Development :: Libraries :: Python Modules", ] dependencies = [ + "any-llm-sdk==1.33.0", "jsonschema>=4.20,<5", "distro>=1.8.0", "openai>=1.0.0", @@ -74,3 +75,4 @@ include = ["miniagent*"] [tool.pytest.ini_options] testpaths = ["tests"] +markers = ["live: opt-in real provider tests requiring explicit credentials"] diff --git a/tests/test_llm.py b/tests/test_llm.py new file mode 100644 index 0000000..04a7477 --- /dev/null +++ b/tests/test_llm.py @@ -0,0 +1,97 @@ +import asyncio +import json +from types import SimpleNamespace as NS +from unittest.mock import AsyncMock, patch + +import httpx +import pytest +from any_llm import AnyLLM + +from miniagent.llm import LLMBackend + + +def test_custom_endpoint_and_native_response(): + async def scenario(): + requests = [] + async def reply(request): + requests.append(request) + return httpx.Response(200, json={"id": "r", "object": "chat.completion", "created": 1, + "model": "test", "choices": [{"index": 0, "finish_reason": "stop", + "message": {"role": "assistant", "content": "hello"}}], + "usage": {"prompt_tokens": 2, "completion_tokens": 1, "total_tokens": 3}}) + provider = AnyLLM.create_openai_compatible("mock", "https://test.invalid/v1", api_key="test") + await provider.client.close() + from openai import AsyncOpenAI + provider.client = AsyncOpenAI(api_key="test", base_url="https://test.invalid/v1", + http_client=httpx.AsyncClient(transport=httpx.MockTransport(reply))) + backend = LLMBackend("mock:test", client=provider) + result = await backend.complete([{"role": "user", "content": "hi"}], [], None) + assert result["content"] == "hello" and backend.usage["total_tokens"] == 3 + assert requests[0].url.path == "/v1/chat/completions" + await backend.aclose() + assert provider.client.is_closed() + asyncio.run(scenario()) + + +def test_stream_multiple_tool_calls_and_close(): + async def scenario(): + closed = [] + async def chunks(): + try: + for i, args in [(0, '{"n":'), (1, '{"n":')]: + yield NS(usage=None, choices=[NS(finish_reason=None, delta=NS(content=None, + tool_calls=[NS(index=i, id=f"id{i}", function=NS(name="add", arguments=args))]))]) + for i in (0, 1): + yield NS(usage=None, choices=[NS(finish_reason=None, delta=NS(content=None, + tool_calls=[NS(index=i, id=None, function=NS(name=None, arguments="2}"))]))]) + yield NS(usage=None, choices=[NS(finish_reason="tool_calls", delta=NS(content=None, tool_calls=[]))]) + finally: + closed.append(True) + backend = LLMBackend("mock:test", client=NS(acompletion=AsyncMock(return_value=chunks()))) + result = await backend.complete([], [], lambda text: None) + assert [json.loads(c["function"]["arguments"]) for c in result["tool_calls"]] == [{"n": 2}, {"n": 2}] + assert closed + asyncio.run(scenario()) + + +def test_incomplete_stream_cannot_execute(): + async def chunks(): + yield NS(usage=None, choices=[NS(finish_reason=None, delta=NS(content="partial", tool_calls=[]))]) + async def scenario(): + backend = LLMBackend("mock:test", client=NS(acompletion=AsyncMock(return_value=chunks()))) + with pytest.raises(RuntimeError, match="Incomplete"): + await backend.complete([], [], lambda text: None) + asyncio.run(scenario()) + + +def test_custom_provider_does_not_use_openai_key(monkeypatch): + monkeypatch.setenv("OPENAI_API_KEY", "wrong") + monkeypatch.delenv("CUSTOM_KEY", raising=False) + with pytest.raises(ValueError, match="CUSTOM_KEY"): + LLMBackend("custom:test", providers={"custom": { + "type": "openai-compatible", "base_url": "https://test.invalid/v1", "api_key_env": "CUSTOM_KEY"}}) + + +def test_provider_resolution_isolated(monkeypatch): + from miniagent.config import load_config + monkeypatch.setenv("LLM_MODEL", "anthropic:test") + monkeypatch.setenv("OPENAI_API_KEY", "wrong") + for key in ("LLM_API_KEY", "ANTHROPIC_API_KEY", "LLM_API_BASE"): + monkeypatch.delenv(key, raising=False) + assert load_config().llm.api_key is None + + +@pytest.mark.live +def test_live_provider(): + import os + model = os.environ.get("MINIAGENT_TEST_MODEL") + if not model: + pytest.skip("Set MINIAGENT_TEST_MODEL and provider credentials for a live smoke test") + async def scenario(): + backend = LLMBackend(model) + try: + result = await backend.complete([{"role": "user", "content": "Say hello."}], []) + assert result.get("content") + finally: + await backend.aclose() + asyncio.run(scenario())