test_websocket_api.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711
  1. import json
  2. import asyncio
  3. import logging
  4. from collections.abc import AsyncIterator
  5. from pathlib import Path
  6. import httpx
  7. import pytest
  8. from fastapi.testclient import TestClient
  9. from pydantic import ValidationError
  10. from agent_lab.application.contracts import AgentParams, DebugRunRequest, EventAgentParams
  11. from agent_lab.application.queues import RuntimeQueues
  12. from agent_lab.application.runtime import DebugRuntime
  13. from agent_lab.domain.events import ToolCallEvent
  14. from agent_lab.domain.messages import ChatMessage, StreamItem
  15. from agent_lab.infrastructure.chat_client import OpenAICompatibleChatClient
  16. from agent_lab.presentation.web import create_app
  17. class FakeRuntime:
  18. def __init__(self) -> None:
  19. self.requests: list[DebugRunRequest] = []
  20. async def run(self, request: DebugRunRequest) -> AsyncIterator[dict]:
  21. self.requests.append(request)
  22. yield {"type": "session_started"}
  23. yield {"type": "message_delta", "content": "hello"}
  24. yield {"type": "done"}
  25. class QueueAwareRuntime:
  26. def __init__(self) -> None:
  27. self.requests: list[DebugRunRequest] = []
  28. self.queues: RuntimeQueues | None = None
  29. self.task: asyncio.Task | None = None
  30. def start(self, request: DebugRunRequest) -> RuntimeQueues:
  31. self.requests.append(request)
  32. self.queues = RuntimeQueues()
  33. self.task = asyncio.create_task(self._run())
  34. return self.queues
  35. async def _run(self) -> None:
  36. assert self.queues is not None
  37. await self.queues.output.put({"type": "session_started"})
  38. message = await self.queues.input.get()
  39. await self.queues.output.put(
  40. {"type": "message_delta", "content": message.content}
  41. )
  42. await self.queues.output.put({"type": "done"})
  43. async def aclose(self) -> None:
  44. if self.task is not None and not self.task.done():
  45. self.task.cancel()
  46. await asyncio.gather(self.task, return_exceptions=True)
  47. def _request_payload() -> dict:
  48. return {
  49. "user_message": "debug this",
  50. "system_prompts": ["You are a debugger."],
  51. "pre_messages": [{"role": "user", "content": "previous turn"}],
  52. "chat_agent": {
  53. "model": "fake-model",
  54. "temperature": 0.1,
  55. "max_tokens": 200,
  56. },
  57. "event_agent": {
  58. "enabled_tools": ["handoff_note"],
  59. "max_event_loops": 2,
  60. },
  61. }
  62. def _event_tool_call_from_tools(
  63. tools: list[dict],
  64. messages: list[ChatMessage],
  65. ) -> StreamItem:
  66. tool_name = tools[0]["function"]["name"]
  67. content = ""
  68. for role in ("assistant", "user"):
  69. content = next(
  70. (
  71. message.content
  72. for message in reversed(messages)
  73. if message.role == role and message.content.strip()
  74. ),
  75. "",
  76. )
  77. if content:
  78. break
  79. arguments = {
  80. "message": content,
  81. "query": content,
  82. "title": content,
  83. }
  84. return StreamItem.event(
  85. ToolCallEvent(
  86. id="event_agent_call_1",
  87. name=tool_name,
  88. arguments=arguments,
  89. raw_arguments=json.dumps(arguments),
  90. )
  91. )
  92. def test_agent_params_defaults_include_extra_body_and_event_agent_defaults_to_one_round():
  93. chat_params = AgentParams()
  94. event_params = EventAgentParams()
  95. assert chat_params.extra_body == {
  96. "thinking": {"type": "disabled"},
  97. "enable_search": False,
  98. "search_options": {"forced_search": False},
  99. }
  100. assert event_params.extra_body == chat_params.extra_body
  101. assert event_params.max_event_loops == 1
  102. assert event_params.system_prompt == ""
  103. def test_health_returns_ok():
  104. app = create_app(runtime_factory=FakeRuntime)
  105. client = TestClient(app)
  106. response = client.get("/health")
  107. assert response.status_code == 200
  108. assert response.json() == {"status": "ok"}
  109. def test_api_tools_returns_handoff_note_metadata():
  110. app = create_app(runtime_factory=FakeRuntime)
  111. client = TestClient(app)
  112. response = client.get("/api/tools")
  113. assert response.status_code == 200
  114. tools = response.json()
  115. assert [tool["name"] for tool in tools] == [
  116. "handoff_note",
  117. "mock_search",
  118. "mock_ticket",
  119. ]
  120. assert tools[0]["parameters"]["required"] == ["message"]
  121. def test_websocket_debug_streams_runtime_messages():
  122. runtime = FakeRuntime()
  123. app = create_app(runtime_factory=lambda: runtime)
  124. client = TestClient(app)
  125. with client.websocket_connect("/ws/debug") as websocket:
  126. websocket.send_json(_request_payload())
  127. assert websocket.receive_json() == {"type": "session_started"}
  128. assert websocket.receive_json() == {
  129. "type": "message_delta",
  130. "content": "hello",
  131. }
  132. assert websocket.receive_json() == {"type": "done"}
  133. assert runtime.requests[0].user_message == "debug this"
  134. assert runtime.requests[0].pre_messages[0].content == "previous turn"
  135. def test_websocket_debug_logs_session_lifecycle(caplog):
  136. runtime = FakeRuntime()
  137. app = create_app(runtime_factory=lambda: runtime)
  138. client = TestClient(app)
  139. with caplog.at_level(logging.INFO, logger="agent_lab.presentation.web"):
  140. with client.websocket_connect("/ws/debug") as websocket:
  141. websocket.send_json(_request_payload())
  142. assert websocket.receive_json() == {"type": "session_started"}
  143. assert websocket.receive_json() == {
  144. "type": "message_delta",
  145. "content": "hello",
  146. }
  147. assert websocket.receive_json() == {"type": "done"}
  148. assert "websocket session accepted" in caplog.text
  149. assert "websocket request accepted" in caplog.text
  150. assert "websocket session closed" in caplog.text
  151. def test_websocket_debug_enqueues_user_messages_during_running_session():
  152. runtime = QueueAwareRuntime()
  153. app = create_app(runtime_factory=lambda: runtime)
  154. client = TestClient(app)
  155. with client.websocket_connect("/ws/debug") as websocket:
  156. websocket.send_json(_request_payload())
  157. assert websocket.receive_json() == {"type": "session_started"}
  158. websocket.send_json({"type": "user_message", "content": "follow-up"})
  159. assert websocket.receive_json() == {
  160. "type": "message_delta",
  161. "content": "follow-up",
  162. }
  163. assert websocket.receive_json() == {"type": "done"}
  164. assert runtime.requests[0].user_message == "debug this"
  165. def test_websocket_debug_sends_error_for_invalid_request():
  166. app = create_app(runtime_factory=FakeRuntime)
  167. client = TestClient(app)
  168. with client.websocket_connect("/ws/debug") as websocket:
  169. websocket.send_json({"chat_agent": {"model": "fake-model"}})
  170. message = websocket.receive_json()
  171. assert message["type"] == "error"
  172. assert "user_message" in message["message"]
  173. def test_debug_run_request_rejects_invalid_pre_message_role():
  174. payload = _request_payload()
  175. payload["pre_messages"] = [{"role": "developer", "content": "invalid"}]
  176. with pytest.raises(ValidationError) as exc_info:
  177. DebugRunRequest.model_validate(payload)
  178. assert "role" in str(exc_info.value)
  179. def test_debug_run_request_rejects_tool_pre_messages():
  180. payload = _request_payload()
  181. payload["pre_messages"] = [
  182. {
  183. "role": "tool",
  184. "content": "orphan result",
  185. "tool_call_id": "call_1",
  186. }
  187. ]
  188. with pytest.raises(ValidationError, match="pre_messages cannot include tool messages"):
  189. DebugRunRequest.model_validate(payload)
  190. def test_chat_message_allows_internal_tool_replies():
  191. message = ChatMessage(
  192. role="tool",
  193. content='{"message":"handled"}',
  194. name="handoff_note",
  195. tool_call_id="call_1",
  196. )
  197. assert message.role == "tool"
  198. assert message.tool_call_id == "call_1"
  199. class HistoryCapturingChatClient:
  200. def __init__(self) -> None:
  201. self.calls = 0
  202. self.second_call_messages: list[ChatMessage] = []
  203. async def stream_chat(
  204. self,
  205. messages: list[ChatMessage],
  206. tools: list[dict],
  207. params: AgentParams,
  208. ) -> AsyncIterator[StreamItem]:
  209. if tools:
  210. yield _event_tool_call_from_tools(tools, messages)
  211. return
  212. self.calls += 1
  213. if self.calls == 1:
  214. yield StreamItem.message_delta("Need event help.")
  215. yield StreamItem.event(
  216. ToolCallEvent(
  217. id="call_1",
  218. name="handoff_note",
  219. arguments={},
  220. raw_arguments="{}",
  221. )
  222. )
  223. return
  224. self.second_call_messages = list(messages)
  225. yield StreamItem.message_delta("Final answer.")
  226. @pytest.mark.asyncio
  227. async def test_runtime_appends_event_summary_without_tool_reply_history():
  228. request = DebugRunRequest(
  229. user_message="debug this",
  230. system_prompts=["You are a debugger."],
  231. pre_messages=[],
  232. chat_agent=AgentParams(model="fake-model", temperature=0.1, max_tokens=200),
  233. event_agent=EventAgentParams(enabled_tools=["handoff_note"], max_event_loops=2),
  234. )
  235. client = HistoryCapturingChatClient()
  236. runtime = DebugRuntime(client)
  237. outputs = [message async for message in runtime.run(request)]
  238. assert client.calls == 2
  239. assert [message.role for message in client.second_call_messages] == [
  240. "system",
  241. "system",
  242. "user",
  243. "assistant",
  244. "user",
  245. ]
  246. assert "Available events:" in client.second_call_messages[1].content
  247. assert client.second_call_messages[3].content == "Need event help."
  248. assert not any(message.role == "tool" for message in client.second_call_messages)
  249. assert client.second_call_messages[4].content.startswith("EventAgent results:\n")
  250. assert client.second_call_messages[4].name == "event_agent"
  251. assert outputs[-1] == {"type": "done"}
  252. @pytest.mark.asyncio
  253. async def test_openai_chat_client_streams_sse_chunks_through_parser():
  254. requests: list[httpx.Request] = []
  255. def handler(request: httpx.Request) -> httpx.Response:
  256. requests.append(request)
  257. payload = json.loads(request.content)
  258. assert payload["stream"] is True
  259. assert payload["model"] == "model-x"
  260. assert payload["messages"] == [{"role": "user", "content": "hi"}]
  261. assert payload["tools"][0]["function"]["name"] == "handoff_note"
  262. assert payload["tool_choice"] == {
  263. "type": "function",
  264. "function": {"name": "handoff_note"},
  265. }
  266. assert payload["temperature"] == 0.3
  267. assert payload["max_tokens"] == 50
  268. assert request.headers["authorization"] == "Bearer test-key"
  269. return httpx.Response(
  270. 200,
  271. content=(
  272. b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n'
  273. b"data: [DONE]\n\n"
  274. ),
  275. )
  276. async with httpx.AsyncClient(
  277. transport=httpx.MockTransport(handler),
  278. base_url="https://llm.test/v1",
  279. ) as http_client:
  280. client = OpenAICompatibleChatClient(
  281. api_key="test-key",
  282. base_url="https://llm.test/v1",
  283. default_model="default-model",
  284. request_timeout_seconds=5,
  285. http_client=http_client,
  286. )
  287. items = [
  288. item
  289. async for item in client.stream_chat(
  290. messages=[ChatMessage(role="user", content="hi")],
  291. tools=[
  292. {
  293. "type": "function",
  294. "function": {"name": "handoff_note", "parameters": {}},
  295. }
  296. ],
  297. params=AgentParams(model="model-x", temperature=0.3, max_tokens=50),
  298. )
  299. ]
  300. assert requests[0].url.path == "/v1/chat/completions"
  301. assert [item.content for item in items] == ["hi"]
  302. @pytest.mark.asyncio
  303. async def test_openai_chat_client_uses_default_model_when_request_model_is_blank():
  304. captured_payloads: list[dict] = []
  305. def handler(request: httpx.Request) -> httpx.Response:
  306. captured_payloads.append(json.loads(request.content))
  307. return httpx.Response(
  308. 200,
  309. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  310. )
  311. async with httpx.AsyncClient(
  312. transport=httpx.MockTransport(handler),
  313. base_url="https://llm.test/v1",
  314. ) as http_client:
  315. client = OpenAICompatibleChatClient(
  316. api_key="",
  317. base_url="https://llm.test/v1",
  318. default_model="provider-default",
  319. request_timeout_seconds=5,
  320. http_client=http_client,
  321. )
  322. [
  323. item
  324. async for item in client.stream_chat(
  325. messages=[ChatMessage(role="user", content="hi")],
  326. tools=[],
  327. params=AgentParams(model=" ", temperature=0.3, max_tokens=50),
  328. )
  329. ]
  330. assert captured_payloads[0]["model"] == "provider-default"
  331. @pytest.mark.asyncio
  332. async def test_openai_chat_client_rejects_internal_tool_messages_before_network():
  333. network_called = False
  334. def handler(request: httpx.Request) -> httpx.Response:
  335. nonlocal network_called
  336. network_called = True
  337. return httpx.Response(
  338. 200,
  339. content=b'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}\n\n',
  340. )
  341. async with httpx.AsyncClient(
  342. transport=httpx.MockTransport(handler),
  343. base_url="https://llm.test/v1",
  344. ) as http_client:
  345. client = OpenAICompatibleChatClient(
  346. api_key="",
  347. base_url="https://llm.test/v1",
  348. default_model="provider-default",
  349. request_timeout_seconds=5,
  350. http_client=http_client,
  351. )
  352. with pytest.raises(ValueError, match="tool messages are internal"):
  353. [
  354. item
  355. async for item in client.stream_chat(
  356. messages=[
  357. ChatMessage(
  358. role="tool",
  359. content="internal tool result",
  360. tool_call_id="call_1",
  361. )
  362. ],
  363. tools=[],
  364. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  365. )
  366. ]
  367. assert network_called is False
  368. def test_static_pre_message_role_selector_does_not_offer_tool():
  369. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  370. assert '<option value="tool">tool</option>' not in html
  371. def test_static_tools_ui_is_dynamic_and_not_hardcoded_to_handoff_note_checkbox():
  372. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  373. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  374. assert 'id="tool-handoff-note"' not in html
  375. assert "#tool-handoff-note" not in js
  376. assert 'id="tool-list"' in html
  377. assert '"/api/tools"' in js
  378. assert "fetch" in js
  379. def test_static_workspace_snapshot_controls_are_available_outside_agent_config():
  380. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  381. chat_dialog_start = html.index('<dialog id="chat-config-dialog"')
  382. event_dialog_start = html.index('<dialog id="event-config-dialog"')
  383. chat_dialog_html = html[chat_dialog_start:event_dialog_start]
  384. sidebar_html = html[:chat_dialog_start]
  385. assert 'id="open-prompt-config"' not in html
  386. assert '<dialog id="prompt-dialog"' not in html
  387. assert 'id="workspace-snapshot-name"' in sidebar_html
  388. assert 'id="saved-workspace-snapshots"' in sidebar_html
  389. assert 'id="save-workspace-snapshot"' in sidebar_html
  390. assert 'id="load-workspace-snapshot"' in sidebar_html
  391. assert 'id="delete-workspace-snapshot"' in sidebar_html
  392. assert 'id="workspace-snapshot-name"' not in chat_dialog_html
  393. assert 'id="saved-workspace-snapshots"' not in chat_dialog_html
  394. assert 'id="save-workspace-snapshot"' not in chat_dialog_html
  395. assert 'id="system-prompts"' in chat_dialog_html
  396. assert 'id="pre-messages"' in chat_dialog_html
  397. def test_static_chat_agent_prompt_is_a_single_sortable_list_with_event_instructions():
  398. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  399. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  400. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  401. assert 'id="chat-system-prompt"' not in html
  402. assert 'id="chat-event-prompt-preview"' not in html
  403. assert 'class="prompt-list stack"' in html
  404. assert 'class="prompt-item"' in html
  405. assert 'data-prompt-role="system"' in html
  406. assert "prompt-type" in html
  407. assert "function buildAvailableEventsPrompt(" in js
  408. assert "Available events:" in js
  409. assert "function updateEventPromptItem(" in js
  410. assert "function createSystemPrompt(" in js
  411. assert "function movePromptItem(" in js
  412. assert 'draggable = true' in js
  413. assert "dataset.promptRole" in js
  414. assert "prompt-title" in js
  415. assert "delete-system-prompt" in js
  416. assert 'prompt_kind: "event_agent_system"' in js
  417. assert "system_prompts: collectSystemPrompts()" in js
  418. assert 'system_prompt: ""' in js
  419. assert ".prompt-item" in css
  420. assert ".prompt-item.dragging" in css
  421. assert ".prompt-meta" in css
  422. assert ".prompt-type" in css
  423. assert ".prompt-actions button" in css
  424. assert "#open-prompt-config" not in js
  425. assert "promptDialog" not in js
  426. def test_static_app_script_is_versioned_and_click_binding_is_guarded():
  427. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  428. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  429. assert '<script src="/static/app.js?v=' in html
  430. assert "function bindClick(" in js
  431. assert 'bindClick("#open-chat-config-panel", openChatConfig)' in js
  432. assert 'bindClick("#open-event-config-panel", openEventConfig)' in js
  433. def test_static_agent_config_controls_are_aligned_for_chat_and_event_agents():
  434. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  435. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  436. assert '<dialog id="chat-config-dialog"' in html
  437. assert '<dialog id="event-config-dialog"' in html
  438. assert html.count('id="open-chat-config-panel"') == 1
  439. assert html.count('id="open-event-config-panel"') == 1
  440. assert 'id="open-chat-config"' not in html
  441. assert 'id="open-event-config"' not in html
  442. assert '#open-chat-config"' not in js
  443. assert '#open-event-config"' not in js
  444. assert '#open-chat-config-panel"' in js
  445. assert '#open-event-config-panel"' in js
  446. assert 'id="close-chat-config"' in html
  447. assert 'id="close-event-config"' in html
  448. assert "chatConfigDialog.showModal()" in js
  449. assert "eventConfigDialog.showModal()" in js
  450. assert "chatConfigDialog.close()" in js
  451. assert "eventConfigDialog.close()" in js
  452. for control_id in [
  453. "model",
  454. "temperature",
  455. "max-tokens",
  456. "chat-thinking-disabled",
  457. "chat-enable-search",
  458. "chat-forced-search",
  459. "event-model",
  460. "event-temperature",
  461. "event-max-tokens",
  462. "event-system-prompt",
  463. "event-thinking-disabled",
  464. "event-enable-search",
  465. "event-forced-search",
  466. ]:
  467. assert f'id="{control_id}"' in html
  468. assert 'extra_body: buildExtraBody("chat")' in js
  469. assert 'extra_body: buildExtraBody("event")' in js
  470. assert 'system_prompt: ""' in js
  471. assert 'system_prompt: document.querySelector("#event-system-prompt")' in js
  472. def test_static_tools_ui_shows_tool_metadata_and_selection_actions():
  473. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  474. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  475. assert 'id="tool-count"' in html
  476. assert 'id="select-all-tools"' in html
  477. assert 'id="clear-tools"' in html
  478. assert "tool-card" in js
  479. assert "tool-description" in js
  480. assert "tool-required" in js
  481. assert "function updateToolCount()" in js
  482. def test_static_app_handles_audit_messages():
  483. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  484. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  485. assert 'message.type === "audit"' in js
  486. assert 'appendLog("audit"' in js
  487. assert ".audit" in css
  488. def test_static_app_shows_wait_state_and_immediate_user_echo():
  489. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  490. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  491. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  492. assert 'id="run-button"' in html
  493. assert 'const runButton = document.querySelector("#run-button")' in js
  494. assert 'appendLog("user", submittedMessage)' in js
  495. assert 'statusEl.textContent = "Waiting for first token"' in js
  496. assert "function startElapsedTimer()" in js
  497. assert "function stopElapsedTimer()" in js
  498. assert "function setRunState(" in js
  499. assert "if (firstTokenAt) {\n hasBackendRoundStats = true;" in js
  500. assert "hasBackendRoundStats && firstTokenAt" in js
  501. assert ".user" in css
  502. def test_static_workspace_snapshot_uses_stable_storage_hooks():
  503. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  504. assert "agent-lab.workspace-snapshots.v1" in js
  505. assert "agent-lab.prompt-sets.v1" in js
  506. assert "function saveWorkspaceSnapshot()" in js
  507. assert "function loadWorkspaceSnapshot()" in js
  508. assert "function deleteWorkspaceSnapshot()" in js
  509. assert "function buildWorkspaceSnapshot()" in js
  510. assert "prompt_items: buildPromptItems()" in js
  511. assert "enabled_tools: selectedTools()" in js
  512. assert "extra_body: buildExtraBody(\"chat\")" in js
  513. assert "extra_body: buildExtraBody(\"event\")" in js
  514. def test_static_app_handles_backend_round_stats_messages():
  515. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  516. assert 'message.type === "round_stats"' in js
  517. assert "function updateRoundStats(" in js
  518. assert "#stat-ttft" in js
  519. assert "#stat-elapsed" in js
  520. @pytest.mark.asyncio
  521. async def test_openai_chat_client_omits_stream_options_when_usage_disabled():
  522. captured_payloads: list[dict] = []
  523. def handler(request: httpx.Request) -> httpx.Response:
  524. captured_payloads.append(json.loads(request.content))
  525. return httpx.Response(
  526. 200,
  527. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  528. )
  529. async with httpx.AsyncClient(
  530. transport=httpx.MockTransport(handler),
  531. base_url="https://llm.test/v1",
  532. ) as http_client:
  533. client = OpenAICompatibleChatClient(
  534. api_key="",
  535. base_url="https://llm.test/v1",
  536. default_model="provider-default",
  537. request_timeout_seconds=5,
  538. include_usage=False,
  539. http_client=http_client,
  540. )
  541. [
  542. item
  543. async for item in client.stream_chat(
  544. messages=[ChatMessage(role="user", content="hi")],
  545. tools=[],
  546. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  547. )
  548. ]
  549. assert "stream_options" not in captured_payloads[0]
  550. @pytest.mark.asyncio
  551. async def test_openai_chat_client_merges_agent_extra_body_into_payload():
  552. captured_payloads: list[dict] = []
  553. def handler(request: httpx.Request) -> httpx.Response:
  554. captured_payloads.append(json.loads(request.content))
  555. return httpx.Response(
  556. 200,
  557. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  558. )
  559. async with httpx.AsyncClient(
  560. transport=httpx.MockTransport(handler),
  561. base_url="https://llm.test/v1",
  562. ) as http_client:
  563. client = OpenAICompatibleChatClient(
  564. api_key="",
  565. base_url="https://llm.test/v1",
  566. default_model="provider-default",
  567. request_timeout_seconds=5,
  568. http_client=http_client,
  569. )
  570. [
  571. item
  572. async for item in client.stream_chat(
  573. messages=[ChatMessage(role="user", content="hi")],
  574. tools=[],
  575. params=AgentParams(
  576. model="provider-default",
  577. temperature=0.3,
  578. max_tokens=50,
  579. extra_body={
  580. "thinking": {"type": "disabled"},
  581. "enable_search": False,
  582. "search_options": {"forced_search": False},
  583. },
  584. ),
  585. )
  586. ]
  587. assert captured_payloads[0]["thinking"] == {"type": "disabled"}
  588. assert captured_payloads[0]["enable_search"] is False
  589. assert captured_payloads[0]["search_options"] == {"forced_search": False}