Skip to content

"Vibe-Trading: Your Personal Trading Agent"

fix(agent): close one-shot ChatLLM clients

cgycoreye09854a3a9b1
diff --git a/agent/src/api/sessions_routes.py b/agent/src/api/sessions_routes.py
index 3c3a6bf5a..b3f5f47d6 100644
--- a/agent/src/api/sessions_routes.py
+++ b/agent/src/api/sessions_routes.py
@@ -674,15 +674,19 @@ def register_sessions_routes(app: FastAPI) -> None:
def _generate() -> str:
from src.providers.chat import ChatLLM
- response = ChatLLM().chat([{"role": "user", "content": prompt}], timeout=30)
- return (getattr(response, "content", "") or "").strip()
+ llm = ChatLLM()
+ try:
+ response = llm.chat([{"role": "user", "content": prompt}], timeout=30)
+ return (getattr(response, "content", "") or "").strip()
+ finally:
+ llm.close()
try:
raw = await asyncio.to_thread(_generate)
except Exception as exc:
raise HTTPException(status_code=502, detail=f"title generation failed: {exc}")
- title = raw.splitlines()[0].strip().strip("\"'“”「」『』").strip()
+ title = raw.splitlines()[0].strip().strip("\"'“”「」『』").strip() if raw else ""
chars = list(title)
if len(chars) > 40:
title = "".join(chars[:40])
diff --git a/agent/src/tools/image_vision_tool.py b/agent/src/tools/image_vision_tool.py
index 6b6b7940d..cc4288359 100644
--- a/agent/src/tools/image_vision_tool.py
+++ b/agent/src/tools/image_vision_tool.py
@@ -12,7 +12,6 @@ from __future__ import annotations
import base64
import json
import logging
-from pathlib import Path
from typing import Any
from src.agent.tools import BaseTool
@@ -128,14 +127,19 @@ class AnalyzeImageTool(BaseTool):
}
]
+ llm = None
try:
from src.providers.chat import ChatLLM
- response = ChatLLM().chat(messages, timeout=_VISION_TIMEOUT_S)
+ llm = ChatLLM()
+ response = llm.chat(messages, timeout=_VISION_TIMEOUT_S)
answer = (response.content or "").strip()
except Exception as exc: # noqa: BLE001 - provider errors go back to the agent
logger.warning("analyze_image failed for %s: %s", path, exc)
return _error(f"vision call failed: {type(exc).__name__}: {exc}")
+ finally:
+ if llm is not None:
+ llm.close()
if not answer:
return _error("the model returned an empty answer (provider may not support image input)")
diff --git a/agent/tests/test_goal_api.py b/agent/tests/test_goal_api.py
index c4cc7edd2..63aa19d13 100644
--- a/agent/tests/test_goal_api.py
+++ b/agent/tests/test_goal_api.py
@@ -3,10 +3,12 @@
from __future__ import annotations
from pathlib import Path
+from unittest.mock import MagicMock, patch
from fastapi.testclient import TestClient
import api_server
+from src.session.models import Message
def _client(tmp_path: Path, monkeypatch) -> TestClient:
@@ -19,12 +21,19 @@ def _client(tmp_path: Path, monkeypatch) -> TestClient:
return TestClient(api_server.app, client=("127.0.0.1", 50000))
-def _session_id(client: TestClient) -> str:
- response = client.post("/sessions", json={"title": "goal api"})
+def _session_id(client: TestClient, *, title: str = "goal api") -> str:
+ response = client.post("/sessions", json={"title": title})
assert response.status_code == 201
return response.json()["session_id"]
+def _add_user_message(session_id: str) -> None:
+ service = api_server._get_session_service()
+ service.store.append_message(
+ Message(session_id=session_id, role="user", content="Evaluate NVDA momentum.")
+ )
+
+
def test_api_goal_uses_full_default_research_checklist(tmp_path: Path, monkeypatch) -> None:
client = _client(tmp_path, monkeypatch)
sid = _session_id(client)
@@ -136,3 +145,48 @@ def test_api_can_edit_current_goal_objective(tmp_path: Path, monkeypatch) -> Non
assert payload["goal"]["goal_id"] == goal_id
assert payload["goal"]["objective"] == "Evaluate NVDA versus QQQ momentum."
assert payload["snapshot"]["claims"][0]["text"] == "Evaluate NVDA versus QQQ momentum."
+
+
+def test_auto_title_closes_chat_client(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ sid = _session_id(client, title="")
+ _add_user_message(sid)
+ response = MagicMock(content="NVDA Momentum Review")
+
+ with patch("src.providers.chat.ChatLLM") as chat_cls:
+ chat_cls.return_value.chat.return_value = response
+ result = client.post(f"/sessions/{sid}/title/auto")
+
+ assert result.status_code == 200
+ assert result.json()["title"] == "NVDA Momentum Review"
+ chat_cls.return_value.close.assert_called_once_with()
+
+
+def test_auto_title_closes_chat_client_when_model_returns_empty(
+ tmp_path: Path, monkeypatch
+) -> None:
+ client = _client(tmp_path, monkeypatch)
+ sid = _session_id(client, title="")
+ _add_user_message(sid)
+ response = MagicMock(content="")
+
+ with patch("src.providers.chat.ChatLLM") as chat_cls:
+ chat_cls.return_value.chat.return_value = response
+ result = client.post(f"/sessions/{sid}/title/auto")
+
+ assert result.status_code == 502
+ assert result.json()["detail"] == "empty title from model"
+ chat_cls.return_value.close.assert_called_once_with()
+
+
+def test_auto_title_closes_chat_client_when_provider_fails(tmp_path: Path, monkeypatch) -> None:
+ client = _client(tmp_path, monkeypatch)
+ sid = _session_id(client, title="")
+ _add_user_message(sid)
+
+ with patch("src.providers.chat.ChatLLM") as chat_cls:
+ chat_cls.return_value.chat.side_effect = RuntimeError("provider unavailable")
+ result = client.post(f"/sessions/{sid}/title/auto")
+
+ assert result.status_code == 502
+ chat_cls.return_value.close.assert_called_once_with()
diff --git a/agent/tests/test_image_vision_tool.py b/agent/tests/test_image_vision_tool.py
index 189804383..cf6ead06d 100644
--- a/agent/tests/test_image_vision_tool.py
+++ b/agent/tests/test_image_vision_tool.py
@@ -64,6 +64,7 @@ def test_happy_path_sends_data_url_and_returns_answer(tool, png_in_allowed_root)
content = messages[0]["content"]
assert content[0] == {"type": "text", "text": "What is this?"}
assert content[1]["image_url"]["url"].startswith("data:image/png;base64,")
+ chat_cls.return_value.close.assert_called_once_with()
def test_empty_model_answer_is_an_error(tool, png_in_allowed_root):
@@ -73,3 +74,13 @@ def test_empty_model_answer_is_an_error(tool, png_in_allowed_root):
chat_cls.return_value.chat.return_value = response
result = json.loads(tool.execute(path=str(png_in_allowed_root)))
assert result["ok"] is False
+ chat_cls.return_value.close.assert_called_once_with()
+
+
+def test_provider_failure_closes_chat_client(tool, png_in_allowed_root):
+ with patch("src.providers.chat.ChatLLM") as chat_cls:
+ chat_cls.return_value.chat.side_effect = RuntimeError("provider unavailable")
+ result = json.loads(tool.execute(path=str(png_in_allowed_root)))
+
+ assert result["ok"] is False
+ chat_cls.return_value.close.assert_called_once_with()