From 42e0a5dd5b037b8da6c626070d673babd82f2093 Mon Sep 17 00:00:00 2001 From: YueGuobin Date: Tue, 3 Nov 2026 23:57:07 +0800 Subject: [PATCH] fix(copilot): bound LLM requests with a timeout and one retry A field log showed one request stayed silent for 604s (the OpenAI SDK default timeout), then the SDK retried on a fresh connection and got 200 OK in under a second. The abort signal did not cancel the in-flight HTTP call, so the turn could look hung for ten minutes. - set timeout (default 120s, request_timeout in the LLM config wins), max_retries=1 and stream_usage=True for the providers that accept them (openai, deepseek, anthropic, xai). ollama and google-genai reject these kwargs, so they keep the old behavior. - log the elapsed time of each LLM call. A slow first token or an SDK retry now shows up in the log line. - add request_timeout to the LLM config schemas and docs (JSON column, no migration). - tests: cover the defaults, the override, invalid values, provider filtering and the title model. --- .../implemented/llm-model-configs.md | 2 + .../agent/gns3_copilot/agent/gns3_copilot.py | 9 ++- .../agent/gns3_copilot/agent/model_factory.py | 34 ++++++++ .../schemas/controller/llm_model_configs.py | 36 +++++++++ tests/agent/test_model_factory.py | 77 +++++++++++++++++++ 5 files changed, 156 insertions(+), 2 deletions(-) create mode 100644 tests/agent/test_model_factory.py diff --git a/docs/gns3-copilot/implemented/llm-model-configs.md b/docs/gns3-copilot/implemented/llm-model-configs.md index 15d02f98e..d686457c2 100644 --- a/docs/gns3-copilot/implemented/llm-model-configs.md +++ b/docs/gns3-copilot/implemented/llm-model-configs.md @@ -226,6 +226,7 @@ For a complete list of LangChain-supported providers, see: https://python.langch | `context_strategy` | string | Context trimming strategy: "conservative" (60%), "balanced" (75%), "aggressive" (85%). Default: "balanced" | | `copilot_mode` | string | GNS3-Copilot mode: "teaching_assistant" (diagnostics only, default) or "lab_automation_assistant" (full configuration access) | | `max_steps` | integer | Step budget of one copilot turn, as the LangGraph recursion limit (1 LLM call + 1 tool run = 2 steps). Defaults: 25 teaching_assistant, 50 lab_automation_assistant, 100 troubleshooting_injection | +| `request_timeout` | number | LLM request timeout in seconds (openai/deepseek/anthropic/xai). Default 120. A silent connection fails fast instead of waiting for the SDK default of 600s | | `is_default` | boolean | Set as default (default: false) | **Important Notes:** @@ -255,6 +256,7 @@ For a complete list of LangChain-supported providers, see: https://python.langch | `is_default` | boolean (optional) | Default flag | | `copilot_mode` | string (optional) | GNS3-Copilot mode: "teaching_assistant" or "lab_automation_assistant" | | `max_steps` | integer (optional) | Step budget of one copilot turn (LangGraph recursion limit). Leave empty for the per-mode default | +| `request_timeout` | number (optional) | LLM request timeout in seconds. Leave empty for the 120s default | | `expected_version` | integer (optional) | **Optimistic locking version** | **Note:** When using `expected_version`, the API will verify the version hasn't changed since you read the data. If it has, you'll receive a 409 Conflict error. diff --git a/gns3server/agent/gns3_copilot/agent/gns3_copilot.py b/gns3server/agent/gns3_copilot/agent/gns3_copilot.py index aa610f742..c27443962 100644 --- a/gns3server/agent/gns3_copilot/agent/gns3_copilot.py +++ b/gns3server/agent/gns3_copilot/agent/gns3_copilot.py @@ -49,6 +49,7 @@ Copilot Modes: import json import logging import operator +import time from datetime import datetime from typing import Annotated, Literal @@ -463,8 +464,11 @@ def llm_call(state: dict, config: RunnableConfig | None = None): if budget_exhausted: prepared_messages = [*prepared_messages, SystemMessage(content=BUDGET_WRAPUP_INSTRUCTION)] - # Invoke model with prepared messages + # Invoke model with prepared messages. The elapsed time makes a slow + # first token or an SDK retry visible in the logs. + started_at = time.monotonic() response = model_to_call.invoke(prepared_messages) + elapsed_s = time.monotonic() - started_at # Add metadata with created_at timestamp to AI response if hasattr(response, "metadata"): @@ -482,8 +486,9 @@ def llm_call(state: dict, config: RunnableConfig | None = None): logger.warning("Could not add metadata to AI response") logger.info( - "LLM call completed: tool_calls=%d", + "LLM call completed: tool_calls=%d, elapsed=%.1fs", len(response.tool_calls) if hasattr(response, "tool_calls") else 0, + elapsed_s, ) return { diff --git a/gns3server/agent/gns3_copilot/agent/model_factory.py b/gns3server/agent/gns3_copilot/agent/model_factory.py index 5700b38bc..191984dad 100644 --- a/gns3server/agent/gns3_copilot/agent/model_factory.py +++ b/gns3server/agent/gns3_copilot/agent/model_factory.py @@ -38,6 +38,38 @@ from langchain.chat_models import init_chat_model logger = logging.getLogger(__name__) +# Request controls for providers whose chat models accept the OpenAI-style +# parameters. Others (ollama, google-genai, ...) reject unknown kwargs at +# construction time, so the parameters are added only where they work. +_REQUEST_CONTROL_PROVIDERS = frozenset({"openai", "deepseek", "anthropic", "xai"}) + +# Without a timeout a wedged connection waits for the SDK default of 600s +# (seen in the field: one request stayed silent for 10 minutes, then the +# SDK retried on a fresh connection and got 200 OK in under a second). +# 120s is long enough for a slow first token and short enough to fail fast. +DEFAULT_REQUEST_TIMEOUT_S = 120.0 +DEFAULT_MAX_RETRIES = 1 + + +def _request_controls(llm_config: Optional[dict[str, Any]]) -> dict[str, Any]: + """Build timeout/retry/usage kwargs for the chat model. + + ``request_timeout`` in the LLM model config overrides the default. + ``stream_usage`` keeps usage_metadata available when the model streams + (astream_events makes it stream even with streaming=False). + """ + config = llm_config or {} + if config.get("provider") not in _REQUEST_CONTROL_PROVIDERS: + return {} + timeout = config.get("request_timeout", DEFAULT_REQUEST_TIMEOUT_S) + try: + timeout = float(timeout) + except (TypeError, ValueError): + timeout = DEFAULT_REQUEST_TIMEOUT_S + if timeout <= 0: + timeout = DEFAULT_REQUEST_TIMEOUT_S + return {"timeout": timeout, "max_retries": DEFAULT_MAX_RETRIES, "stream_usage": True} + def _load_llm_config( llm_config: Optional[dict[str, Any]] = None, @@ -117,6 +149,7 @@ def create_base_model( "temperature": config_vars["temperature"], "configurable_fields": "any", "config_prefix": "foo", + **_request_controls(llm_config), } # Disable DeepSeek thinking mode to avoid reasoning_content handling issues @@ -184,6 +217,7 @@ def create_title_model( "temperature": "1.0", # Higher temperature for more creative titles "configurable_fields": "any", "config_prefix": "foo", + **_request_controls(llm_config), } # Disable DeepSeek thinking mode to avoid reasoning_content handling issues diff --git a/gns3server/schemas/controller/llm_model_configs.py b/gns3server/schemas/controller/llm_model_configs.py index 80dacbc98..1ff96d339 100644 --- a/gns3server/schemas/controller/llm_model_configs.py +++ b/gns3server/schemas/controller/llm_model_configs.py @@ -63,6 +63,15 @@ class LLMModelConfigData(BaseModel): "50 lab_automation_assistant, 100 troubleshooting_injection" ), ) + request_timeout: Optional[float] = Field( + None, + gt=0, + le=3600, + description=( + "LLM request timeout in seconds (openai/deepseek/anthropic/xai providers). " + "Default 120. A silent connection fails fast instead of waiting 600s" + ), + ) # Allow extra fields for extensibility # Ensure all fields are included in serialization, even if None @@ -102,6 +111,15 @@ class LLMModelConfigCreate(BaseModel): "50 lab_automation_assistant, 100 troubleshooting_injection" ), ) + request_timeout: Optional[float] = Field( + None, + gt=0, + le=3600, + description=( + "LLM request timeout in seconds (openai/deepseek/anthropic/xai providers). " + "Default 120. A silent connection fails fast instead of waiting 600s" + ), + ) # Allow extra config fields model_config = ConfigDict(extra="allow") @@ -142,6 +160,15 @@ class LLMModelConfigUpdate(BaseModel): "50 lab_automation_assistant, 100 troubleshooting_injection" ), ) + request_timeout: Optional[float] = Field( + None, + gt=0, + le=3600, + description=( + "LLM request timeout in seconds (openai/deepseek/anthropic/xai providers). " + "Default 120. A silent connection fails fast instead of waiting 600s" + ), + ) # Allow extra config fields model_config = ConfigDict(extra="allow") @@ -189,6 +216,15 @@ class LLMModelConfigDataWithoutSecret(BaseModel): "50 lab_automation_assistant, 100 troubleshooting_injection" ), ) + request_timeout: Optional[float] = Field( + None, + gt=0, + le=3600, + description=( + "LLM request timeout in seconds (openai/deepseek/anthropic/xai providers). " + "Default 120. A silent connection fails fast instead of waiting 600s" + ), + ) # Allow extra fields for extensibility model_config = ConfigDict(extra="allow", populate_by_name=True) diff --git a/tests/agent/test_model_factory.py b/tests/agent/test_model_factory.py new file mode 100644 index 000000000..5d9d7044d --- /dev/null +++ b/tests/agent/test_model_factory.py @@ -0,0 +1,77 @@ +""" +Tests for the model factory request controls. + +A silent provider connection used to wait for the OpenAI SDK default of +600s before the SDK retried. The factory now sets a shorter timeout and +a bounded retry count for the providers that accept them, and keeps usage +metadata in streaming mode. +""" + +from typing import Any + +import pytest + +from gns3server.agent.gns3_copilot.agent import model_factory + + +def _config(**overrides: Any) -> dict[str, Any]: + config = { + "provider": "deepseek", + "model": "deepseek-v4-flash", + "api_key": "test-key", + "base_url": "https://api.deepseek.com/v1", + "temperature": 0.3, + } + config.update(overrides) + return config + + +@pytest.fixture +def captured(monkeypatch: pytest.MonkeyPatch) -> dict[str, Any]: + """Capture the kwargs passed to init_chat_model.""" + box: dict[str, Any] = {} + + def fake_init_chat_model(**kwargs: Any) -> object: + box.update(kwargs) + return object() + + monkeypatch.setattr(model_factory, "init_chat_model", fake_init_chat_model) + return box + + +def test_base_model_gets_timeout_and_bounded_retries(captured: dict[str, Any]) -> None: + model_factory.create_base_model(_config()) + + assert captured["timeout"] == model_factory.DEFAULT_REQUEST_TIMEOUT_S + assert captured["max_retries"] == model_factory.DEFAULT_MAX_RETRIES + assert captured["stream_usage"] is True + # DeepSeek thinking stays disabled + assert captured["extra_body"] == {"thinking": {"type": "disabled"}} + + +def test_request_timeout_from_config_wins(captured: dict[str, Any]) -> None: + model_factory.create_base_model(_config(request_timeout="60")) + assert captured["timeout"] == 60.0 + + +@pytest.mark.parametrize("value", ["abc", 0, -5, None]) +def test_invalid_request_timeout_falls_back(captured: dict[str, Any], value: Any) -> None: + model_factory.create_base_model(_config(request_timeout=value)) + assert captured["timeout"] == model_factory.DEFAULT_REQUEST_TIMEOUT_S + + +def test_providers_without_request_controls_get_none(captured: dict[str, Any]) -> None: + """Ollama and google-genai reject these kwargs at construction.""" + model_factory.create_base_model(_config(provider="ollama", base_url="http://localhost:11434")) + + assert "timeout" not in captured + assert "max_retries" not in captured + assert "stream_usage" not in captured + + +def test_title_model_gets_the_same_controls(captured: dict[str, Any]) -> None: + model_factory.create_title_model(_config()) + + assert captured["timeout"] == model_factory.DEFAULT_REQUEST_TIMEOUT_S + assert captured["max_retries"] == model_factory.DEFAULT_MAX_RETRIES + assert captured["stream_usage"] is True