"Vibe-Trading: Your Personal Trading Agent"
Python ai-agentalgorithmic-tradingbacktestingfintechllmmcpmulti-agentpythonquantitative-financetrading
fix(providers): resolve zai streaming + base_url resolution (#758)
Haozhe Wua066e5545eb2
diff --git a/agent/src/providers/capabilities.py b/agent/src/providers/capabilities.pyindex 80c55ccf0..708e61317 100644--- a/agent/src/providers/capabilities.py+++ b/agent/src/providers/capabilities.py@@ -2,9 +2,12 @@from __future__ import annotations+import jsonimport osfrom dataclasses import dataclass, field+from functools import lru_cachefrom importlib.metadata import PackageNotFoundError, version+from pathlib import Pathfrom typing import Mapping, Optional@@ -247,6 +250,41 @@ def provider_env_names(return caps.api_key_env, caps.base_url_env+_PROVIDER_CATALOG_PATH = Path(__file__).with_name("llm_providers.json")+++@lru_cache(maxsize=1)+def _provider_default_base_urls() -> dict[str, str]:+ """Canonical ``name -> default_base_url`` map from the provider catalog.++ The catalog (``llm_providers.json``) declares each provider's canonical API+ root. Web Settings already fall back to it; this exposes the same default to+ the backend credential path so a CLI / manual-``.env`` user who sets only+ ``LANGCHAIN_PROVIDER`` + the API key still reaches the right endpoint (e.g.+ Z.ai's ``/api/coding/paas/v4``) instead of silently defaulting to+ ``api.openai.com`` and getting a 404 for a non-OpenAI model.+ """+ try:+ raw = json.loads(_PROVIDER_CATALOG_PATH.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return {}+ entries = raw if isinstance(raw, list) else raw.get("providers", [])+ result: dict[str, str] = {}+ for entry in entries:+ if not isinstance(entry, dict):+ continue+ name = str(entry.get("name", "")).strip().lower()+ url = str(entry.get("default_base_url", "")).strip()+ if name and url:+ result[name] = url+ return result+++def _provider_default_base_url(provider_name: str) -> str:+ """Return the catalog default base URL for a canonical provider name."""+ return _provider_default_base_urls().get((provider_name or "").strip().lower(), "")++def get_llm_credentials(provider: str | None,model: str | None,@@ -267,8 +305,12 @@ def get_llm_credentials(Notes:Reads dynamic env vars via ``os.getenv`` — not part of ``EnvConfig``.+ When no base URL is set in the environment, falls back to the provider+ catalog's ``default_base_url`` so a provider set without an explicit+ ``*_BASE_URL`` still hits its canonical endpoint."""- key_env, base_env = provider_env_names(provider, model)+ caps = get_provider_capabilities(provider, model)+ key_env, base_env = caps.api_key_env, caps.base_url_envif key_env is not None:api_key = os.getenv( # noqa: env-gate@@ -294,6 +336,7 @@ def get_llm_credentials(or os.getenv( # noqa: env-gate — dynamic provider URL chain"OPENAI_API_BASE", "")+ or _provider_default_base_url(caps.name))return {diff --git a/agent/src/providers/chat.py b/agent/src/providers/chat.pyindex 680871e9a..44444815b 100644--- a/agent/src/providers/chat.py+++ b/agent/src/providers/chat.py@@ -6,6 +6,7 @@ ChatLLM is designed specifically for the AgentLoop ReAct cycle.from __future__ import annotationsimport html+import loggingimport osimport refrom dataclasses import dataclass, field@@ -15,6 +16,8 @@ from src.config.accessor import get_env_configfrom src.providers.content_filter import is_content_filter_triggeredfrom src.providers.llm import build_llm+logger = logging.getLogger(__name__)+def _dedupe_finish_reason(raw: str) -> str:"""Relays (OpenRouter) emit finish_reason per chunk; AIMessageChunk.__add__@@ -114,9 +117,20 @@ class ProviderStreamError(RuntimeError):self.original = originalself.status_code: Optional[int] = getattr(original, "status_code", None)safe_message = _redact_provider_error(str(original))+ hint = ""+ lowered = safe_message.lower()+ if any(m in lowered for m in ("<!doctype html", "<html", "__next_error__")):+ # An HTML body from a JSON API almost always means the base URL+ # points at a website root, not the API root (a frequent .env+ # misconfiguration for OpenAI-compatible coding-plan gateways).+ hint = (+ " — the endpoint returned an HTML page instead of a JSON API "+ f"response; verify the {provider} base URL points at the API "+ "root (e.g. the OpenAI-compatible '/v1' path), not the site root"+ )super().__init__(f"provider_stream_error provider={provider} model={model}: "- f"{type(original).__name__}: {safe_message}"+ f"{type(original).__name__}: {safe_message}{hint}")@property@@ -147,6 +161,18 @@ def _redact_provider_error(message: str) -> str:return redacted+def _is_no_stream_chunk_error(exc: Exception) -> bool:+ """True when a provider accepted the request but streamed zero chunks.++ LangChain raises ``ValueError("No generation chunks were returned")`` when+ an OpenAI-compatible endpoint returns a non-streaming (or empty-SSE) body.+ That's a streaming-capability gap, not a provider failure — a plain+ non-streaming ``invoke`` still succeeds, so ``stream_chat`` falls back+ instead of surfacing it as a hard ``ProviderStreamError``.+ """+ return isinstance(exc, ValueError) and "no generation chunks" in str(exc).lower()++_DSML_BAR = r"(?:\|\||||)"_DSML_TAG = rf"{_DSML_BAR}\s*DSML\s*{_DSML_BAR}"_DSML_TOOL_CALLS_RE = re.compile(@@ -298,8 +324,10 @@ class ChatLLM:accumulated = Nonepending_text = ""possible_dsml_text = True+ cancelled = Falsefor chunk in llm.stream(messages, config=config):if should_cancel and should_cancel():+ cancelled = Truebreakchunk_text = _text_content(chunk.content)if chunk_text and on_text_chunk:@@ -318,12 +346,29 @@ class ChatLLM:on_reasoning_chunk(reasoning)accumulated = chunk if accumulated is None else accumulated + chunkif accumulated is None:- return LLMResponse(content="", tool_calls=[], finish_reason="stop")+ if cancelled:+ return LLMResponse(content="", tool_calls=[], finish_reason="stop")+ # Endpoint streamed nothing (no SSE support); a non-streaming+ # invoke still works — fall back rather than return empty.+ logger.warning(+ "Provider stream returned no chunks; falling back to "+ "non-streaming invoke."+ )+ return self.chat(messages, tools=tools, timeout=timeout)response = self._parse_response(accumulated)if pending_text and not (response.has_tool_calls and response.content == ""):on_text_chunk(pending_text)return responseexcept Exception as exc:+ if _is_no_stream_chunk_error(exc):+ # Provider streamed zero chunks (endpoint lacks real SSE); a+ # non-streaming invoke still returns a valid response.+ logger.warning(+ "Provider stream produced no chunks (%s); falling back to "+ "non-streaming invoke.",+ type(exc).__name__,+ )+ return self.chat(messages, tools=tools, timeout=timeout)_cfg = get_env_config()provider = _cfg.llm.langchain_provider.strip().lower() or "openai"model = self.model_name or _cfg.llm.langchain_model_name.strip() or "(unset)"diff --git a/agent/src/providers/llm.py b/agent/src/providers/llm.pyindex 1faa5dd58..3749441b2 100644--- a/agent/src/providers/llm.py+++ b/agent/src/providers/llm.py@@ -538,7 +538,8 @@ def _sync_provider_env() -> None:"""Map provider-specific env vars to OPENAI_* for ChatOpenAI.Each entry: provider_name -> (api_key_env, base_url_env).- All base URLs must be set explicitly in .env — no hardcoded defaults.+ Base URLs come from .env; when unset, ``get_llm_credentials`` falls back to+ the provider catalog's ``default_base_url`` (see ``capabilities.py``).api_key_env=None means no key required (e.g. Ollama local)."""_ensure_dotenv()diff --git a/agent/tests/test_chat_llm_streaming.py b/agent/tests/test_chat_llm_streaming.pyindex c1282f55c..01992ad87 100644--- a/agent/tests/test_chat_llm_streaming.py+++ b/agent/tests/test_chat_llm_streaming.py@@ -289,3 +289,61 @@ def test_content_filter_triggered_flag_false_on_stop() -> None:assert response.content == "text"assert response.finish_reason == "stop"assert response.content_filter_triggered is False+++# ---------------------------------------------------------------------------+# #758: no-SSE endpoints (e.g. some Z.ai coding-plan routes) stream zero+# chunks; stream_chat must fall back to a non-streaming invoke, and a bare+# base-URL misconfiguration must surface an actionable hint.+# ---------------------------------------------------------------------------+++def test_empty_stream_value_error_falls_back_to_invoke() -> None:+ """LangChain's 'No generation chunks were returned' → non-streaming invoke."""+ fake = _FakeStreamingLLM(exc=ValueError("No generation chunks were returned"))+ response = _client(fake).stream_chat([{"role": "user", "content": "hi"}])+ assert fake.invoke_called is True+ assert response.content == "fallback"+++def test_clean_zero_chunk_stream_falls_back_to_invoke() -> None:+ """A stream that ends cleanly with no chunks (and no cancel) also falls back."""+ fake = _FakeStreamingLLM(chunks=[])+ response = _client(fake).stream_chat([{"role": "user", "content": "hi"}])+ assert fake.invoke_called is True+ assert response.content == "fallback"+++def test_generic_value_error_still_raises_provider_error() -> None:+ """A ValueError that is NOT the empty-stream signal still surfaces as error."""+ fake = _FakeStreamingLLM(exc=ValueError("malformed request payload"))+ with patch.dict(+ os.environ,+ {"LANGCHAIN_PROVIDER": "zai", "LANGCHAIN_MODEL_NAME": "glm-5.1"},+ clear=True,+ ):+ with pytest.raises(ProviderStreamError):+ _client(fake).stream_chat([{"role": "user", "content": "hi"}])+ assert fake.invoke_called is False+++def test_cancelled_empty_stream_returns_empty_without_fallback() -> None:+ """A user cancel before any chunk returns empty — it must NOT invoke."""+ fake = _FakeStreamingLLM([_FakeChunk(content="ignored")])+ response = _client(fake).stream_chat(+ [{"role": "user", "content": "hi"}], should_cancel=lambda: True+ )+ assert fake.invoke_called is False+ assert response.content == ""+++def test_provider_stream_error_hints_at_base_url_on_html_body() -> None:+ """An HTML error page (site root, not API root) appends a base-URL hint."""+ original = RuntimeError(+ '<!DOCTYPE html><html id="__next_error__">404 Not Found</html>'+ )+ err = ProviderStreamError(provider="zai", model="glm-5.1", original=original)+ message = str(err)+ assert "HTML page" in message+ assert "base URL" in message+ assert "zai" in messagediff --git a/agent/tests/test_llm_provider_defaults.py b/agent/tests/test_llm_provider_defaults.pyindex c6fce35a2..e48661daa 100644--- a/agent/tests/test_llm_provider_defaults.py+++ b/agent/tests/test_llm_provider_defaults.py@@ -7,6 +7,10 @@ from pathlib import Pathimport clifrom cli.onboard import PROVIDERS as ONBOARD_PROVIDERS+from src.providers.capabilities import (+ _provider_default_base_urls,+ get_llm_credentials,+)EXPECTED_PROVIDER_DEFAULTS = {@@ -130,3 +134,43 @@ def test_siliconflow_is_available_in_both_cli_onboarding_surfaces() -> None:assert onboard.key_env == legacy["key_env"] == key_envassert onboard.base_env == legacy["base_env"] == base_envassert onboard.base_url == legacy["base_url"] == base_url+++# ---------------------------------------------------------------------------+# #758: backend credential resolution falls back to the catalog default_base_url+# when no *_BASE_URL is set, so CLI / manual-.env users reach the right endpoint.+# ---------------------------------------------------------------------------+++def test_zai_base_url_falls_back_to_catalog_default(monkeypatch) -> None:+ """With no *_BASE_URL set, zai resolves to its catalog endpoint instead of+ silently defaulting to api.openai.com (which 404s glm-5.1)."""+ for var in ("ZAI_BASE_URL", "OPENAI_BASE_URL", "OPENAI_API_BASE"):+ monkeypatch.delenv(var, raising=False)+ creds = get_llm_credentials("zai", "glm-5.1")+ assert creds["base_url"] == "https://api.z.ai/api/coding/paas/v4"+++def test_explicit_provider_base_url_overrides_catalog_default(monkeypatch) -> None:+ monkeypatch.setenv("ZAI_BASE_URL", "https://custom.example/v1")+ creds = get_llm_credentials("zai", "glm-5.1")+ assert creds["base_url"] == "https://custom.example/v1"+++def test_openai_base_url_env_overrides_catalog_default(monkeypatch) -> None:+ monkeypatch.delenv("ZAI_BASE_URL", raising=False)+ monkeypatch.setenv("OPENAI_BASE_URL", "https://proxy.example/v1")+ creds = get_llm_credentials("zai", "glm-5.1")+ assert creds["base_url"] == "https://proxy.example/v1"+++def test_credential_fallback_map_matches_provider_catalog() -> None:+ """The base-URL fallback map must stay in sync with llm_providers.json."""+ providers_path = (+ Path(__file__).resolve().parents[1] / "src" / "providers" / "llm_providers.json"+ )+ catalog = {+ item["name"]: item["default_base_url"]+ for item in json.loads(providers_path.read_text(encoding="utf-8"))+ }+ assert _provider_default_base_urls() == catalog