test_websocket_api.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679
  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["temperature"] == 0.3
  263. assert payload["max_tokens"] == 50
  264. assert request.headers["authorization"] == "Bearer test-key"
  265. return httpx.Response(
  266. 200,
  267. content=(
  268. b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n'
  269. b"data: [DONE]\n\n"
  270. ),
  271. )
  272. async with httpx.AsyncClient(
  273. transport=httpx.MockTransport(handler),
  274. base_url="https://llm.test/v1",
  275. ) as http_client:
  276. client = OpenAICompatibleChatClient(
  277. api_key="test-key",
  278. base_url="https://llm.test/v1",
  279. default_model="default-model",
  280. request_timeout_seconds=5,
  281. http_client=http_client,
  282. )
  283. items = [
  284. item
  285. async for item in client.stream_chat(
  286. messages=[ChatMessage(role="user", content="hi")],
  287. tools=[
  288. {
  289. "type": "function",
  290. "function": {"name": "handoff_note", "parameters": {}},
  291. }
  292. ],
  293. params=AgentParams(model="model-x", temperature=0.3, max_tokens=50),
  294. )
  295. ]
  296. assert requests[0].url.path == "/v1/chat/completions"
  297. assert [item.content for item in items] == ["hi"]
  298. @pytest.mark.asyncio
  299. async def test_openai_chat_client_uses_default_model_when_request_model_is_blank():
  300. captured_payloads: list[dict] = []
  301. def handler(request: httpx.Request) -> httpx.Response:
  302. captured_payloads.append(json.loads(request.content))
  303. return httpx.Response(
  304. 200,
  305. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  306. )
  307. async with httpx.AsyncClient(
  308. transport=httpx.MockTransport(handler),
  309. base_url="https://llm.test/v1",
  310. ) as http_client:
  311. client = OpenAICompatibleChatClient(
  312. api_key="",
  313. base_url="https://llm.test/v1",
  314. default_model="provider-default",
  315. request_timeout_seconds=5,
  316. http_client=http_client,
  317. )
  318. [
  319. item
  320. async for item in client.stream_chat(
  321. messages=[ChatMessage(role="user", content="hi")],
  322. tools=[],
  323. params=AgentParams(model=" ", temperature=0.3, max_tokens=50),
  324. )
  325. ]
  326. assert captured_payloads[0]["model"] == "provider-default"
  327. @pytest.mark.asyncio
  328. async def test_openai_chat_client_rejects_internal_tool_messages_before_network():
  329. network_called = False
  330. def handler(request: httpx.Request) -> httpx.Response:
  331. nonlocal network_called
  332. network_called = True
  333. return httpx.Response(
  334. 200,
  335. content=b'data: {"choices":[{"delta":{"content":"done"},"finish_reason":null}]}\n\n',
  336. )
  337. async with httpx.AsyncClient(
  338. transport=httpx.MockTransport(handler),
  339. base_url="https://llm.test/v1",
  340. ) as http_client:
  341. client = OpenAICompatibleChatClient(
  342. api_key="",
  343. base_url="https://llm.test/v1",
  344. default_model="provider-default",
  345. request_timeout_seconds=5,
  346. http_client=http_client,
  347. )
  348. with pytest.raises(ValueError, match="tool messages are internal"):
  349. [
  350. item
  351. async for item in client.stream_chat(
  352. messages=[
  353. ChatMessage(
  354. role="tool",
  355. content="internal tool result",
  356. tool_call_id="call_1",
  357. )
  358. ],
  359. tools=[],
  360. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  361. )
  362. ]
  363. assert network_called is False
  364. def test_static_pre_message_role_selector_does_not_offer_tool():
  365. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  366. assert '<option value="tool">tool</option>' not in html
  367. def test_static_tools_ui_is_dynamic_and_not_hardcoded_to_handoff_note_checkbox():
  368. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  369. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  370. assert 'id="tool-handoff-note"' not in html
  371. assert "#tool-handoff-note" not in js
  372. assert 'id="tool-list"' in html
  373. assert '"/api/tools"' in js
  374. assert "fetch" in js
  375. def test_static_prompt_workspace_controls_are_available_in_chat_agent_config():
  376. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  377. chat_dialog_start = html.index('<dialog id="chat-config-dialog"')
  378. event_dialog_start = html.index('<dialog id="event-config-dialog"')
  379. chat_dialog_html = html[chat_dialog_start:event_dialog_start]
  380. assert 'id="open-prompt-config"' not in html
  381. assert '<dialog id="prompt-dialog"' not in html
  382. assert 'id="prompt-set-name"' in html
  383. assert 'id="saved-prompt-sets"' in html
  384. assert 'id="save-prompt-set"' in html
  385. assert 'id="load-prompt-set"' in html
  386. assert 'id="delete-prompt-set"' in html
  387. assert 'id="prompt-set-name"' in chat_dialog_html
  388. assert 'id="system-prompts"' in chat_dialog_html
  389. assert 'id="pre-messages"' in chat_dialog_html
  390. def test_static_chat_agent_prompt_defaults_to_available_event_instructions():
  391. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  392. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  393. assert 'id="chat-system-prompt"' in html
  394. assert "function buildAvailableEventsPrompt(" in js
  395. assert "Available events:" in js
  396. assert "updateChatSystemPromptDefault(tools)" in js
  397. assert "#open-prompt-config" not in js
  398. assert "promptDialog" not in js
  399. def test_static_app_script_is_versioned_and_click_binding_is_guarded():
  400. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  401. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  402. assert '<script src="/static/app.js?v=' in html
  403. assert "function bindClick(" in js
  404. assert 'bindClick("#open-chat-config-panel", openChatConfig)' in js
  405. assert 'bindClick("#open-event-config-panel", openEventConfig)' in js
  406. def test_static_agent_config_controls_are_aligned_for_chat_and_event_agents():
  407. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  408. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  409. assert '<dialog id="chat-config-dialog"' in html
  410. assert '<dialog id="event-config-dialog"' in html
  411. assert html.count('id="open-chat-config-panel"') == 1
  412. assert html.count('id="open-event-config-panel"') == 1
  413. assert 'id="open-chat-config"' not in html
  414. assert 'id="open-event-config"' not in html
  415. assert '#open-chat-config"' not in js
  416. assert '#open-event-config"' not in js
  417. assert '#open-chat-config-panel"' in js
  418. assert '#open-event-config-panel"' in js
  419. assert 'id="close-chat-config"' in html
  420. assert 'id="close-event-config"' in html
  421. assert "chatConfigDialog.showModal()" in js
  422. assert "eventConfigDialog.showModal()" in js
  423. assert "chatConfigDialog.close()" in js
  424. assert "eventConfigDialog.close()" in js
  425. for control_id in [
  426. "model",
  427. "temperature",
  428. "max-tokens",
  429. "chat-system-prompt",
  430. "chat-thinking-disabled",
  431. "chat-enable-search",
  432. "chat-forced-search",
  433. "event-model",
  434. "event-temperature",
  435. "event-max-tokens",
  436. "event-system-prompt",
  437. "event-thinking-disabled",
  438. "event-enable-search",
  439. "event-forced-search",
  440. ]:
  441. assert f'id="{control_id}"' in html
  442. assert 'extra_body: buildExtraBody("chat")' in js
  443. assert 'extra_body: buildExtraBody("event")' in js
  444. assert 'system_prompt: document.querySelector("#chat-system-prompt")' in js
  445. assert 'system_prompt: document.querySelector("#event-system-prompt")' in js
  446. def test_static_tools_ui_shows_tool_metadata_and_selection_actions():
  447. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  448. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  449. assert 'id="tool-count"' in html
  450. assert 'id="select-all-tools"' in html
  451. assert 'id="clear-tools"' in html
  452. assert "tool-card" in js
  453. assert "tool-description" in js
  454. assert "tool-required" in js
  455. assert "function updateToolCount()" in js
  456. def test_static_app_handles_audit_messages():
  457. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  458. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  459. assert 'message.type === "audit"' in js
  460. assert 'appendLog("audit"' in js
  461. assert ".audit" in css
  462. def test_static_app_shows_wait_state_and_immediate_user_echo():
  463. html = Path("src/agent_lab/presentation/static/index.html").read_text()
  464. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  465. css = Path("src/agent_lab/presentation/static/styles.css").read_text()
  466. assert 'id="run-button"' in html
  467. assert 'const runButton = document.querySelector("#run-button")' in js
  468. assert 'appendLog("user", submittedMessage)' in js
  469. assert 'statusEl.textContent = "Waiting for first token"' in js
  470. assert "function startElapsedTimer()" in js
  471. assert "function stopElapsedTimer()" in js
  472. assert "function setRunState(" in js
  473. assert "if (firstTokenAt) {\n hasBackendRoundStats = true;" in js
  474. assert "hasBackendRoundStats && firstTokenAt" in js
  475. assert ".user" in css
  476. def test_static_prompt_workspace_uses_stable_storage_hooks():
  477. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  478. assert "agent-lab.prompt-sets.v1" in js
  479. assert "function savePromptSet()" in js
  480. assert "function loadPromptSet()" in js
  481. assert "function deletePromptSet()" in js
  482. def test_static_app_handles_backend_round_stats_messages():
  483. js = Path("src/agent_lab/presentation/static/app.js").read_text()
  484. assert 'message.type === "round_stats"' in js
  485. assert "function updateRoundStats(" in js
  486. assert "#stat-ttft" in js
  487. assert "#stat-elapsed" in js
  488. @pytest.mark.asyncio
  489. async def test_openai_chat_client_omits_stream_options_when_usage_disabled():
  490. captured_payloads: list[dict] = []
  491. def handler(request: httpx.Request) -> httpx.Response:
  492. captured_payloads.append(json.loads(request.content))
  493. return httpx.Response(
  494. 200,
  495. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  496. )
  497. async with httpx.AsyncClient(
  498. transport=httpx.MockTransport(handler),
  499. base_url="https://llm.test/v1",
  500. ) as http_client:
  501. client = OpenAICompatibleChatClient(
  502. api_key="",
  503. base_url="https://llm.test/v1",
  504. default_model="provider-default",
  505. request_timeout_seconds=5,
  506. include_usage=False,
  507. http_client=http_client,
  508. )
  509. [
  510. item
  511. async for item in client.stream_chat(
  512. messages=[ChatMessage(role="user", content="hi")],
  513. tools=[],
  514. params=AgentParams(model="provider-default", temperature=0.3, max_tokens=50),
  515. )
  516. ]
  517. assert "stream_options" not in captured_payloads[0]
  518. @pytest.mark.asyncio
  519. async def test_openai_chat_client_merges_agent_extra_body_into_payload():
  520. captured_payloads: list[dict] = []
  521. def handler(request: httpx.Request) -> httpx.Response:
  522. captured_payloads.append(json.loads(request.content))
  523. return httpx.Response(
  524. 200,
  525. content=b'data: {"choices":[{"delta":{"content":"hi"},"finish_reason":null}]}\n\n',
  526. )
  527. async with httpx.AsyncClient(
  528. transport=httpx.MockTransport(handler),
  529. base_url="https://llm.test/v1",
  530. ) as http_client:
  531. client = OpenAICompatibleChatClient(
  532. api_key="",
  533. base_url="https://llm.test/v1",
  534. default_model="provider-default",
  535. request_timeout_seconds=5,
  536. http_client=http_client,
  537. )
  538. [
  539. item
  540. async for item in client.stream_chat(
  541. messages=[ChatMessage(role="user", content="hi")],
  542. tools=[],
  543. params=AgentParams(
  544. model="provider-default",
  545. temperature=0.3,
  546. max_tokens=50,
  547. extra_body={
  548. "thinking": {"type": "disabled"},
  549. "enable_search": False,
  550. "search_options": {"forced_search": False},
  551. },
  552. ),
  553. )
  554. ]
  555. assert captured_payloads[0]["thinking"] == {"type": "disabled"}
  556. assert captured_payloads[0]["enable_search"] is False
  557. assert captured_payloads[0]["search_options"] == {"forced_search": False}