The agent engineering platform.
Python agentsaiai-agentsanthropicchatgptdeepagentsenterpriseframeworkgeminigenerative-ailangchainlanggraphllmmultiagentopen-sourceopenaipydanticpythonragtypescript
fix(perplexity): preserve Agent API search results (#41349)
Ant White57f2d8bb9d9f
diff --git a/libs/partners/perplexity/langchain_perplexity/chat_models.py b/libs/partners/perplexity/langchain_perplexity/chat_models.pyindex e717c96f42..145ff3ac64 100644--- a/libs/partners/perplexity/langchain_perplexity/chat_models.py+++ b/libs/partners/perplexity/langchain_perplexity/chat_models.py@@ -413,10 +413,17 @@ def _convert_responses_to_chat_result(response: Any) -> ChatResult:content = _extract_responses_text(response)tool_calls: list[dict[str, Any]] = []+ additional_kwargs: dict[str, Any] = {}output = _get_attr(response, "output", None) or []for item in output:item_type = _get_attr(item, "type", None)- if item_type == "function_call":+ if item_type == "search_results":+ if results := _get_attr(item, "results", None):+ additional_kwargs.setdefault("search_results", []).extend(+ result.model_dump() if isinstance(result, BaseModel) else result+ for result in results+ )+ elif item_type == "function_call":raw_args = _get_attr(item, "arguments", "") or ""try:parsed_args = json.loads(raw_args) if raw_args else {}@@ -442,7 +449,6 @@ def _convert_responses_to_chat_result(response: Any) -> ChatResult:usage_metadata = _convert_responses_usage(_get_attr(response, "usage", None))- additional_kwargs: dict[str, Any] = {}for key in ("citations","images",@@ -453,7 +459,7 @@ def _convert_responses_to_chat_result(response: Any) -> ChatResult:):value = _get_attr(response, key, None)if value:- additional_kwargs[key] = value+ additional_kwargs.setdefault(key, value)response_metadata: dict[str, Any] = {}for key in ("id", "model", "status", "object"):@@ -504,7 +510,8 @@ def _convert_responses_stream_event_to_chunk() -> ChatGenerationChunk | None:"""Convert a Responses API streaming event to a `ChatGenerationChunk`.- Handles `response.output_text.delta` (text chunk), `response.output_item.done`+ Handles `response.reasoning.search_results` (source metadata),+ `response.output_text.delta` (text chunk), `response.output_item.done`carrying a `function_call` (surfaced as a tool-call chunk), `response.completed`(final usage + metadata), and `response.failed` / `response.error`(raises `PerplexityResponsesStreamError`). Returns `None` for any other@@ -512,6 +519,22 @@ def _convert_responses_stream_event_to_chunk(diagnosable without flooding logs."""event_type = _get_attr(event, "type", None)+ if event_type == "response.reasoning.search_results":+ if results := _get_attr(event, "results", None):+ return ChatGenerationChunk(+ message=AIMessageChunk(+ content="",+ additional_kwargs={+ "search_results": [+ result.model_dump()+ if isinstance(result, BaseModel)+ else result+ for result in results+ ]+ },+ )+ )+ return Noneif event_type == "response.output_text.delta":delta = _get_attr(event, "delta", "") or ""return ChatGenerationChunk(message=AIMessageChunk(content=delta))diff --git a/libs/partners/perplexity/tests/unit_tests/test_chat_models_responses.py b/libs/partners/perplexity/tests/unit_tests/test_chat_models_responses.pyindex 6fa32d3189..80d4e6aa98 100644--- a/libs/partners/perplexity/tests/unit_tests/test_chat_models_responses.py+++ b/libs/partners/perplexity/tests/unit_tests/test_chat_models_responses.py@@ -3,11 +3,13 @@from __future__ import annotationsimport json+from collections.abc import AsyncIteratorfrom typing import Anyfrom unittest.mock import AsyncMock, MagicMockimport pytestfrom langchain_core.messages import AIMessage, AIMessageChunk+from perplexity.types.shared.search_result import SearchResultfrom langchain_perplexity import ChatPerplexityfrom langchain_perplexity.chat_models import (@@ -35,6 +37,73 @@ def _make_event(event_type: str, **attrs: Any) -> MagicMock:return obj+def agent_search_results() -> list[dict[str, Any]]:+ return [+ {+ "id": 1,+ "url": "https://example.com/menu",+ "title": "Menu",+ "snippet": "Set menu costs £45.",+ "date": None,+ "last_updated": None,+ "source": None,+ },+ {+ "id": 2,+ "url": "https://example.com/faq",+ "title": "FAQ",+ "snippet": "Minimum two people.",+ "date": None,+ "last_updated": None,+ "source": None,+ },+ ]++[email protected](params=["dict", "sdk"])+def agent_search_response(+ agent_search_results: list[dict[str, Any]], request: pytest.FixtureRequest+) -> dict[str, Any]:+ results = (+ [SearchResult(**result) for result in agent_search_results]+ if request.param == "sdk"+ else agent_search_results+ )+ return {+ "id": "resp_search",+ "status": "completed",+ "output": [+ {"type": "search_results", "results": []},+ {"type": "search_results", "results": results[:1]},+ {"type": "search_results", "results": results[1:]},+ {+ "type": "message",+ "content": [{"type": "output_text", "text": "Set menu [1][2]."}],+ },+ ],+ }+++def agent_search_events(+ agent_search_response: dict[str, Any],+) -> list[dict[str, Any]]:+ return [+ {"type": "response.reasoning.search_results", "results": []},+ {+ "type": "response.reasoning.search_results",+ "results": agent_search_response["output"][1]["results"],+ },+ {"type": "response.output_text.delta", "delta": "Set menu [1][2]."},+ {+ "type": "response.reasoning.search_results",+ "results": agent_search_response["output"][2]["results"],+ },+ {"type": "response.completed", "response": agent_search_response},+ ]++# ---------------------------------------------------------------------------# Module-level _use_responses_api helper# ---------------------------------------------------------------------------@@ -115,6 +184,43 @@ def _stub_responses_response(text: str = "ok") -> MagicMock:)[email protected]("top_level_results", [False, True])+def test_invoke_serializes_agent_search_results(+ agent_search_response: dict[str, Any],+ agent_search_results: list[dict[str, Any]],+ top_level_results: bool,+) -> None:+ if top_level_results:+ agent_search_response["search_results"] = agent_search_results[:1]+ llm = ChatPerplexity(api_key="test", use_responses_api=True)+ llm.client = MagicMock()+ llm.client.responses.create.return_value = _make_response_obj(+ **agent_search_response+ )++ message = llm.invoke("What is on the set menu?")++ assert message.content == "Set menu [1][2]."+ assert message.additional_kwargs["search_results"] == agent_search_results+++async def test_ainvoke_serializes_agent_search_results(+ agent_search_response: dict[str, Any],+ agent_search_results: list[dict[str, Any]],+) -> None:+ llm = ChatPerplexity(api_key="test", use_responses_api=True)+ llm.async_client = MagicMock()+ llm.async_client.responses.create = AsyncMock(+ return_value=_make_response_obj(**agent_search_response)+ )++ message = await llm.ainvoke("What is on the set menu?")++ assert message.content == "Set menu [1][2]."+ assert message.additional_kwargs["search_results"] == agent_search_results++def test_invoke_routes_to_responses_when_builtin_tool_in_payload() -> None:llm = ChatPerplexity(model="sonar-pro", api_key="test")llm.client = MagicMock()@@ -547,6 +653,45 @@ async def test_astream_yields_text_chunks_and_final_usage() -> None:assert final_usage["output_tokens"] == 9+def test_stream_preserves_agent_search_results_without_duplicates(+ agent_search_events: list[dict[str, Any]],+ agent_search_results: list[dict[str, Any]],+) -> None:+ llm = ChatPerplexity(api_key="test", use_responses_api=True)+ llm.client = MagicMock()+ llm.client.responses.create.return_value = iter(agent_search_events)++ chunks = list(llm.stream("What is on the set menu?"))+ message = chunks[0]+ for chunk in chunks[1:]:+ message += chunk++ assert message.content == "Set menu [1][2]."+ assert message.additional_kwargs["search_results"] == agent_search_results+++async def test_astream_preserves_agent_search_results_without_duplicates(+ agent_search_events: list[dict[str, Any]],+ agent_search_results: list[dict[str, Any]],+) -> None:+ async def events() -> AsyncIterator[dict[str, Any]]:+ for event in agent_search_events:+ yield event++ llm = ChatPerplexity(api_key="test", use_responses_api=True)+ llm.async_client = MagicMock()+ llm.async_client.responses.create = AsyncMock(return_value=events())++ chunks = [chunk async for chunk in llm.astream("What is on the set menu?")]+ message = chunks[0]+ for chunk in chunks[1:]:+ message += chunk++ assert message.content == "Set menu [1][2]."+ assert message.additional_kwargs["search_results"] == agent_search_results++# ---------------------------------------------------------------------------# Auto-detection: input/include/instructions/previous_response_id + mixed tools# ---------------------------------------------------------------------------