Open
test(llm): 基于 0930 打印出站完整报文 #10
test(llm): 基于 0930 打印出站完整报文 #10
Open
jaxAdd on Sep 11
Total: 4 files changed+166-2
@@ -14,10 +14,11 @@
14 14 
15from __future__ import annotations15from __future__ import annotations
16 16 
17+import json
17import re18import re
18import time19import time
19-from typing import Any, Optional20+from typing import Any, Mapping, Optional
20-from urllib.parse import quote21+from urllib.parse import quote, urlencode
21 22 
22import httpx23import httpx
23from loguru import logger24from loguru import logger
@@ -268,6 +269,7 @@ class SemanticServiceClient:
268 url = self._url(path)269 url = self._url(path)
269 started = time.perf_counter()270 started = time.perf_counter()
270 try:271 try:
272+ self._log_outbound_request(method, url, params=params, json_body=json, headers=headers)
271 if method.upper() == "GET":273 if method.upper() == "GET":
272 response = self.client.get(274 response = self.client.get(
273 url,275 url,
@@ -321,6 +323,39 @@ class SemanticServiceClient:
321 logger.error("semantic.audit method={} path={} success=false error=response_validation", method, path)323 logger.error("semantic.audit method={} path={} success=false error=response_validation", method, path)
322 raise324 raise
323 325 
326+ def _log_outbound_request(
327+ self,
328+ method: str,
329+ url: str,
330+ *,
331+ params: Any = None,
332+ json_body: dict[str, Any] | None = None,
333+ headers: Mapping[str, str] | None = None,
334+ ) -> None:
335+ """打印完整出站报文;Authorization 脱敏。控制台默认 WARNING,故打 WARNING。"""
336+ merged_headers: dict[str, str] = {}
337+ client_headers = getattr(self.client, "headers", None)
338+ if client_headers:
339+ merged_headers.update({str(key): str(value) for key, value in client_headers.items()})
340+ if headers:
341+ merged_headers.update({str(key): str(value) for key, value in headers.items()})
342+ logged_headers = _mask_request_headers(merged_headers)
343+ request_url = _request_url_with_params(url, params)
344+ if json_body is not None:
345+ try:
346+ body = json.dumps(json_body, ensure_ascii=False, default=str)
347+ except TypeError:
348+ body = str(json_body)
349+ else:
350+ body = ""
351+ logger.warning(
352+ "semantic.request method={} url={} headers={} body={}",
353+ method,
354+ request_url,
355+ logged_headers,
356+ body,
357+ )
358+ 
324 def _url(self, path: str) -> str:359 def _url(self, path: str) -> str:
325 """Build an absolute URL from a relative API path."""360 """Build an absolute URL from a relative API path."""
326 return f"{self.base_url}/{path.lstrip('/')}"361 return f"{self.base_url}/{path.lstrip('/')}"
@@ -399,6 +434,37 @@ def _response_json(response: httpx.Response) -> Any:
399 return None434 return None
400 435 
401 436 
437+def _mask_request_headers(headers: Mapping[str, Any]) -> dict[str, str]:
438+ """Return request headers with credential-bearing values redacted."""
439+ masked: dict[str, str] = {}
440+ for key, value in headers.items():
441+ name = str(key)
442+ lowered = name.lower()
443+ if lowered in {"authorization", "proxy-authorization"}:
444+ masked[name] = "Bearer ***"
445+ elif lowered in {"cookie", "x-api-key", "api-key"}:
446+ masked[name] = "***REDACTED***"
447+ else:
448+ masked[name] = str(value)
449+ return masked
450+ 
451+ 
452+def _request_url_with_params(url: str, params: Any) -> str:
453+ """Append query parameters so the logged URL matches the outbound request."""
454+ if params is None:
455+ return url
456+ if isinstance(params, dict):
457+ query = urlencode(params, doseq=True)
458+ elif isinstance(params, (list, tuple)):
459+ query = urlencode(list(params), doseq=True)
460+ else:
461+ query = str(params)
462+ if not query:
463+ return url
464+ separator = "&" if "?" in url else "?"
465+ return f"{url}{separator}{query}"
466+ 
467+ 
402def _response_headers(response: httpx.Response) -> dict[str, str]:468def _response_headers(response: httpx.Response) -> dict[str, str]:
403 """Return response headers with credential-bearing values redacted."""469 """Return response headers with credential-bearing values redacted."""
404 raw_headers = getattr(response, "headers", None)470 raw_headers = getattr(response, "headers", None)
@@ -1566,6 +1566,7 @@ class LLMClient:
1566 timeout = self._resolve_timeout(kwargs, default=DEFAULT_LLM_NON_STREAM_TIMEOUT)1566 timeout = self._resolve_timeout(kwargs, default=DEFAULT_LLM_NON_STREAM_TIMEOUT)
1567 max_attempts = self._resolve_max_attempts(kwargs)1567 max_attempts = self._resolve_max_attempts(kwargs)
1568 logger.debug("invoke.request model={} payload_keys={}", self._model, sorted(payload.keys()))1568 logger.debug("invoke.request model={} payload_keys={}", self._model, sorted(payload.keys()))
1569+ self._log_outbound_request(payload, stream=False)
1569 verify = httpx_verify()1570 verify = httpx_verify()
1570 1571 
1571 def _call() -> LLMClientMessage:1572 def _call() -> LLMClientMessage:
@@ -1591,6 +1592,7 @@ class LLMClient:
1591 timeout = self._resolve_timeout(kwargs, default=DEFAULT_LLM_NON_STREAM_TIMEOUT)1592 timeout = self._resolve_timeout(kwargs, default=DEFAULT_LLM_NON_STREAM_TIMEOUT)
1592 max_attempts = self._resolve_max_attempts(kwargs)1593 max_attempts = self._resolve_max_attempts(kwargs)
1593 logger.debug("ainvoke.request model={} payload_keys={}", self._model, sorted(payload.keys()))1594 logger.debug("ainvoke.request model={} payload_keys={}", self._model, sorted(payload.keys()))
1595+ self._log_outbound_request(payload, stream=False)
1594 verify = httpx_verify()1596 verify = httpx_verify()
1595 1597 
1596 async def _call() -> LLMClientMessage:1598 async def _call() -> LLMClientMessage:
@@ -1616,6 +1618,7 @@ class LLMClient:
1616 timeout = self._resolve_timeout(kwargs, default=DEFAULT_LLM_STREAM_TIMEOUT)1618 timeout = self._resolve_timeout(kwargs, default=DEFAULT_LLM_STREAM_TIMEOUT)
1617 max_attempts = self._resolve_max_attempts(kwargs)1619 max_attempts = self._resolve_max_attempts(kwargs)
1618 request_url = self._endpoint()1620 request_url = self._endpoint()
1621+ self._log_outbound_request(payload, stream=True)
1619 1622 
1620 for attempt in range(max_attempts + 1):1623 for attempt in range(max_attempts + 1):
1621 stream_state = _AStreamState()1624 stream_state = _AStreamState()
@@ -1894,6 +1897,23 @@ class LLMClient:
1894 """Build the ``/chat/completions`` endpoint URL from the configured api_base."""1897 """Build the ``/chat/completions`` endpoint URL from the configured api_base."""
1895 return f"{self._api_base.rstrip('/')}/chat/completions"1898 return f"{self._api_base.rstrip('/')}/chat/completions"
1896 1899 
1900+ def _log_outbound_request(self, payload: Mapping[str, Any], *, stream: bool) -> None:
1901+ """打印完整出站报文;Authorization 脱敏。控制台默认 WARNING,故打 WARNING。"""
1902+ headers = dict(self._headers())
1903+ if "Authorization" in headers:
1904+ headers["Authorization"] = "Bearer ***"
1905+ try:
1906+ body = json.dumps(payload, ensure_ascii=False, default=str)
1907+ except TypeError:
1908+ body = str(payload)
1909+ logger.warning(
1910+ "llm.request method=POST url={} stream={} headers={} body={}",
1911+ self._endpoint(),
1912+ stream,
1913+ headers,
1914+ body,
1915+ )
1916+ 
1897 def _headers(self) -> dict[str, str]:1917 def _headers(self) -> dict[str, str]:
1898 """Build the Authorization + Content-Type request headers."""1918 """Build the Authorization + Content-Type request headers."""
1899 headers = {1919 headers = {
@@ -150,6 +150,35 @@ def test_from_llm_config_missing_api_key(monkeypatch: pytest.MonkeyPatch) -> Non
150 assert "Authorization" not in client._headers()150 assert "Authorization" not in client._headers()
151 151 
152 152 
153+def test_log_outbound_request_masks_authorization(monkeypatch: pytest.MonkeyPatch) -> None:
154+ recorded: list[str] = []
155+ monkeypatch.setattr(
156+ "dataagent.core.managers.llm_manager.llm_client.logger.warning",
157+ lambda msg, *args, **kwargs: recorded.append(msg.format(*args)),
158+ )
159+ client = LLMClient(model="m", api_base="https://llm.example/v1", api_key="sk-secret")
160+ client._log_outbound_request({"model": "m", "messages": [{"role": "user", "content": "hi"}]}, stream=False)
161+ assert len(recorded) == 1
162+ assert "sk-secret" not in recorded[0]
163+ assert "Authorization': 'Bearer ***'" in recorded[0]
164+ assert '"content": "hi"' in recorded[0]
165+ 
166+ 
167+def test_log_outbound_request_empty_key_omits_authorization(monkeypatch: pytest.MonkeyPatch) -> None:
168+ recorded: list[str] = []
169+ monkeypatch.setattr(
170+ "dataagent.core.managers.llm_manager.llm_client.logger.warning",
171+ lambda msg, *args, **kwargs: recorded.append(msg.format(*args)),
172+ )
173+ client = LLMClient.from_llm_config(_make_config(base_url="https://from-yaml/v1"))
174+ assert client._api_key == "EMPTY"
175+ assert "Authorization" not in client._headers()
176+ client._log_outbound_request({"model": "m"}, stream=True)
177+ assert len(recorded) == 1
178+ assert "Authorization" not in recorded[0]
179+ assert "stream=True" in recorded[0]
180+ 
181+ 
153def test_llm_manager_create_llm_uses_llm_client(monkeypatch: pytest.MonkeyPatch) -> None:182def test_llm_manager_create_llm_uses_llm_client(monkeypatch: pytest.MonkeyPatch) -> None:
154 """LLMManager.create_llm 底层应为 LLMClient(经 LangChainChatModelAdapter 包装)。"""183 """LLMManager.create_llm 底层应为 LLMClient(经 LangChainChatModelAdapter 包装)。"""
155 monkeypatch.setenv("QWEN3_CODER_BASE_URL", "https://example.invalid/v1")184 monkeypatch.setenv("QWEN3_CODER_BASE_URL", "https://example.invalid/v1")
@@ -186,3 +186,52 @@ def test_client_uses_httpx_verify_for_semantic_layer(monkeypatch) -> None:
186 monkeypatch.setattr(semantic_client.httpx, "Client", _capturing_client)186 monkeypatch.setattr(semantic_client.httpx, "Client", _capturing_client)
187 SemanticServiceClient("http://semantic.local:41000")187 SemanticServiceClient("http://semantic.local:41000")
188 assert captured["verify"] is sentinel188 assert captured["verify"] is sentinel
189+ 
190+ 
191+def test_log_outbound_request_masks_authorization(monkeypatch: pytest.MonkeyPatch) -> None:
192+ recorded: list[str] = []
193+ monkeypatch.setattr(
194+ semantic_client.logger,
195+ "warning",
196+ lambda msg, *args, **kwargs: recorded.append(msg.format(*args)),
197+ )
198+ monkeypatch.setattr(semantic_client.httpx, "Client", lambda *a, **k: _FakeClient())
199+ client = SemanticServiceClient("http://semantic.local:41000")
200+ client._log_outbound_request(
201+ "POST",
202+ "http://semantic.local:41000/api/semantic/v1/search/basic",
203+ json_body={"query": "订单"},
204+ headers={"Authorization": "Bearer sk-secret", "Content-Type": "application/json"},
205+ )
206+ assert len(recorded) == 1
207+ assert recorded[0].startswith("semantic.request ")
208+ assert "sk-secret" not in recorded[0]
209+ assert "Authorization': 'Bearer ***'" in recorded[0]
210+ assert '"query": "订单"' in recorded[0]
211+ 
212+ 
213+def test_request_logs_full_outbound_before_send(monkeypatch: pytest.MonkeyPatch) -> None:
214+ recorded: list[str] = []
215+ fake_client = _FakeClient()
216+ monkeypatch.setattr(semantic_client.httpx, "Client", lambda *a, **k: fake_client)
217+ monkeypatch.setattr(
218+ semantic_client.logger,
219+ "warning",
220+ lambda msg, *args, **kwargs: recorded.append(msg.format(*args)),
221+ )
222+ client = SemanticServiceClient("http://semantic.local:41000")
223+ assert (
224+ client.post(
225+ "search/basic",
226+ json={"query": "订单"},
227+ headers={"Authorization": "Bearer sk-secret", "Content-Type": "application/json"},
228+ )
229+ == {"ok": True}
230+ )
231+ assert fake_client.calls
232+ assert len(recorded) == 1
233+ assert recorded[0].startswith("semantic.request method=POST")
234+ assert "search/basic" in recorded[0]
235+ assert "sk-secret" not in recorded[0]
236+ assert "Authorization': 'Bearer ***'" in recorded[0]
237+ assert '"query": "订单"' in recorded[0]