Skip to content

The agent engineering platform.

feat(groq): support built-in tools in message content (#33459)

ccurme961f965f0cba
diff --git a/libs/core/langchain_core/messages/block_translators/groq.py b/libs/core/langchain_core/messages/block_translators/groq.py
index 958de52280..33f1921ddc 100644
--- a/libs/core/langchain_core/messages/block_translators/groq.py
+++ b/libs/core/langchain_core/messages/block_translators/groq.py
@@ -1,39 +1,135 @@
"""Derivations of standard content blocks from Groq content."""
-import warnings
+import json
+import re
+from typing import Any
from langchain_core.messages import AIMessage, AIMessageChunk
from langchain_core.messages import content as types
+from langchain_core.messages.base import _extract_reasoning_from_additional_kwargs
-WARNED = False
+def _populate_extras(
+ standard_block: types.ContentBlock, block: dict[str, Any], known_fields: set[str]
+) -> types.ContentBlock:
+ """Mutate a block, populating extras."""
+ if standard_block.get("type") == "non_standard":
+ return standard_block
-def translate_content(message: AIMessage) -> list[types.ContentBlock]: # noqa: ARG001
- """Derive standard content blocks from a message with Groq content."""
- global WARNED # noqa: PLW0603
- if not WARNED:
- warning_message = (
- "Content block standardization is not yet fully supported for Groq."
+ for key, value in block.items():
+ if key not in known_fields:
+ if "extras" not in standard_block:
+ # Below type-ignores are because mypy thinks a non-standard block can
+ # get here, although we exclude them above.
+ standard_block["extras"] = {} # type: ignore[typeddict-unknown-key]
+ standard_block["extras"][key] = value # type: ignore[typeddict-item]
+
+ return standard_block
+
+
+def _parse_code_json(s: str) -> dict:
+ """Extract Python code from Groq built-in tool content.
+
+ Extracts the value of the 'code' field from a string of the form:
+ {"code": some_arbitrary_text_with_unescaped_quotes}
+
+ As Groq may not escape quotes in the executed tools, e.g.:
+ ```
+ '{"code": "import math; print("The square root of 101 is: "); print(math.sqrt(101))"}'
+ ```
+ """ # noqa: E501
+ m = re.fullmatch(r'\s*\{\s*"code"\s*:\s*"(.*)"\s*\}\s*', s, flags=re.DOTALL)
+ if not m:
+ msg = (
+ "Could not extract Python code from Groq tool arguments. "
+ "Expected a JSON object with a 'code' field."
)
- warnings.warn(warning_message, stacklevel=2)
- WARNED = True
- raise NotImplementedError
+ raise ValueError(msg)
+ return {"code": m.group(1)}
+
+
+def _convert_to_v1_from_groq(message: AIMessage) -> list[types.ContentBlock]:
+ """Convert groq message content to v1 format."""
+ content_blocks: list[types.ContentBlock] = []
+ if reasoning_block := _extract_reasoning_from_additional_kwargs(message):
+ content_blocks.append(reasoning_block)
-def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]: # noqa: ARG001
- """Derive standard content blocks from a message chunk with Groq content."""
- global WARNED # noqa: PLW0603
- if not WARNED:
- warning_message = (
- "Content block standardization is not yet fully supported for Groq."
+ if executed_tools := message.additional_kwargs.get("executed_tools"):
+ for idx, executed_tool in enumerate(executed_tools):
+ args: dict[str, Any] | None = None
+ if arguments := executed_tool.get("arguments"):
+ try:
+ args = json.loads(arguments)
+ except json.JSONDecodeError:
+ if executed_tool.get("type") == "python":
+ try:
+ args = _parse_code_json(arguments)
+ except ValueError:
+ continue
+ elif (
+ executed_tool.get("type") == "function"
+ and executed_tool.get("name") == "python"
+ ):
+ # GPT-OSS
+ args = {"code": arguments}
+ else:
+ continue
+ if isinstance(args, dict):
+ name = ""
+ if executed_tool.get("type") == "search":
+ name = "web_search"
+ elif executed_tool.get("type") == "python" or (
+ executed_tool.get("type") == "function"
+ and executed_tool.get("name") == "python"
+ ):
+ name = "code_interpreter"
+ server_tool_call: types.ServerToolCall = {
+ "type": "server_tool_call",
+ "name": name,
+ "id": str(idx),
+ "args": args,
+ }
+ content_blocks.append(server_tool_call)
+ if tool_output := executed_tool.get("output"):
+ tool_result: types.ServerToolResult = {
+ "type": "server_tool_result",
+ "tool_call_id": str(idx),
+ "output": tool_output,
+ "status": "success",
+ }
+ known_fields = {"type", "arguments", "index", "output"}
+ _populate_extras(tool_result, executed_tool, known_fields)
+ content_blocks.append(tool_result)
+
+ if isinstance(message.content, str) and message.content:
+ content_blocks.append({"type": "text", "text": message.content})
+
+ for tool_call in message.tool_calls:
+ content_blocks.append( # noqa: PERF401
+ {
+ "type": "tool_call",
+ "name": tool_call["name"],
+ "args": tool_call["args"],
+ "id": tool_call.get("id"),
+ }
)
- warnings.warn(warning_message, stacklevel=2)
- WARNED = True
- raise NotImplementedError
+
+ return content_blocks
+
+
+def translate_content(message: AIMessage) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message with groq content."""
+ return _convert_to_v1_from_groq(message)
+
+
+def translate_content_chunk(message: AIMessageChunk) -> list[types.ContentBlock]:
+ """Derive standard content blocks from a message chunk with groq content."""
+ return _convert_to_v1_from_groq(message)
def _register_groq_translator() -> None:
- """Register the Groq translator with the central registry.
+ """Register the groq translator with the central registry.
Run automatically when the module is imported.
"""
diff --git a/libs/core/tests/unit_tests/messages/test_ai.py b/libs/core/tests/unit_tests/messages/test_ai.py
index d18a1e9b0a..a65033f82c 100644
--- a/libs/core/tests/unit_tests/messages/test_ai.py
+++ b/libs/core/tests/unit_tests/messages/test_ai.py
@@ -486,8 +486,10 @@ def test_provider_warns() -> None:
# implemented.
# This test should be removed when all major providers support content block
# standardization.
- message = AIMessage("Hello.", response_metadata={"model_provider": "groq"})
- with pytest.warns(match="not yet fully supported for Groq"):
+ message = AIMessage(
+ "Hello.", response_metadata={"model_provider": "google_vertexai"}
+ )
+ with pytest.warns(match="not yet fully supported for Google VertexAI"):
content_blocks = message.content_blocks
assert content_blocks == [{"type": "text", "text": "Hello."}]
diff --git a/libs/partners/groq/langchain_groq/_compat.py b/libs/partners/groq/langchain_groq/_compat.py
new file mode 100644
index 0000000000..adc4f79eac
--- /dev/null
+++ b/libs/partners/groq/langchain_groq/_compat.py
@@ -0,0 +1,71 @@
+from __future__ import annotations
+
+import json
+from typing import Any, cast
+
+from langchain_core.messages import content as types
+
+
+def _convert_from_v1_to_groq(
+ content: list[types.ContentBlock],
+ model_provider: str | None,
+) -> tuple[list[dict[str, Any] | str], dict]:
+ new_content: list = []
+ new_additional_kwargs: dict = {}
+ for i, block in enumerate(content):
+ if block["type"] == "text":
+ new_content.append({"text": block.get("text", ""), "type": "text"})
+
+ elif (
+ block["type"] == "reasoning"
+ and (reasoning := block.get("reasoning"))
+ and model_provider == "groq"
+ ):
+ new_additional_kwargs["reasoning_content"] = reasoning
+
+ elif block["type"] == "server_tool_call" and model_provider == "groq":
+ new_block = {}
+ if "args" in block:
+ new_block["arguments"] = json.dumps(block["args"])
+ if idx := block.get("extras", {}).get("index"):
+ new_block["index"] = idx
+ if block.get("name") == "web_search":
+ new_block["type"] = "search"
+ elif block.get("name") == "code_interpreter":
+ new_block["type"] = "python"
+ else:
+ new_block["type"] = ""
+
+ if i < len(content) - 1 and content[i + 1]["type"] == "server_tool_result":
+ result = cast("types.ServerToolResult", content[i + 1])
+ for k, v in result.get("extras", {}).items():
+ new_block[k] = v # noqa: PERF403
+ if "output" in result:
+ new_block["output"] = result["output"]
+
+ if "executed_tools" not in new_additional_kwargs:
+ new_additional_kwargs["executed_tools"] = []
+ new_additional_kwargs["executed_tools"].append(new_block)
+ elif block["type"] == "server_tool_result":
+ continue
+
+ elif (
+ block["type"] == "non_standard"
+ and "value" in block
+ and model_provider == "groq"
+ ):
+ new_content.append(block["value"])
+ else:
+ new_content.append(block)
+
+ # For consistency with v0 payloads, we cast single text blocks to str
+ if (
+ len(new_content) == 1
+ and isinstance(new_content[0], dict)
+ and new_content[0].get("type") == "text"
+ and (text_content := new_content[0].get("text"))
+ and isinstance(text_content, str)
+ ):
+ return text_content, new_additional_kwargs
+
+ return new_content, new_additional_kwargs
diff --git a/libs/partners/groq/langchain_groq/chat_models.py b/libs/partners/groq/langchain_groq/chat_models.py
index 64c72fbdd8..29ba2184ef 100644
--- a/libs/partners/groq/langchain_groq/chat_models.py
+++ b/libs/partners/groq/langchain_groq/chat_models.py
@@ -57,6 +57,7 @@ from langchain_core.utils.pydantic import is_basemodel_subclass
from pydantic import BaseModel, ConfigDict, Field, SecretStr, model_validator
from typing_extensions import Self
+from langchain_groq._compat import _convert_from_v1_to_groq
from langchain_groq.version import __version__
@@ -1187,6 +1188,17 @@ def _convert_message_to_dict(message: BaseMessage) -> dict:
elif isinstance(message, HumanMessage):
message_dict = {"role": "user", "content": message.content}
elif isinstance(message, AIMessage):
+ # Translate v1 content
+ if message.response_metadata.get("output_version") == "v1":
+ new_content, new_additional_kwargs = _convert_from_v1_to_groq(
+ message.content_blocks, message.response_metadata.get("model_provider")
+ )
+ message = message.model_copy(
+ update={
+ "content": new_content,
+ "additional_kwargs": new_additional_kwargs,
+ }
+ )
message_dict = {"role": "assistant", "content": message.content}
# If content is a list of content blocks, filter out tool_call blocks
@@ -1268,6 +1280,22 @@ def _convert_chunk_to_message_chunk(
if role == "assistant" or default_class == AIMessageChunk:
if reasoning := _dict.get("reasoning"):
additional_kwargs["reasoning_content"] = reasoning
+ if executed_tools := _dict.get("executed_tools"):
+ additional_kwargs["executed_tools"] = []
+ for executed_tool in executed_tools:
+ if executed_tool.get("output"):
+ # Tool output duplicates query and other server tool call data
+ additional_kwargs["executed_tools"].append(
+ {
+ k: executed_tool[k]
+ for k in ("index", "output")
+ if k in executed_tool
+ }
+ )
+ else:
+ additional_kwargs["executed_tools"].append(
+ {k: executed_tool[k] for k in executed_tool if k != "output"}
+ )
if usage := (chunk.get("x_groq") or {}).get("usage"):
input_tokens = usage.get("prompt_tokens", 0)
output_tokens = usage.get("completion_tokens", 0)
@@ -1282,6 +1310,7 @@ def _convert_chunk_to_message_chunk(
content=content,
additional_kwargs=additional_kwargs,
usage_metadata=usage_metadata, # type: ignore[arg-type]
+ response_metadata={"model_provider": "groq"},
)
if role == "system" or default_class == SystemMessageChunk:
return SystemMessageChunk(content=content)
@@ -1313,6 +1342,8 @@ def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
additional_kwargs: dict = {}
if reasoning := _dict.get("reasoning"):
additional_kwargs["reasoning_content"] = reasoning
+ if executed_tools := _dict.get("executed_tools"):
+ additional_kwargs["executed_tools"] = executed_tools
if function_call := _dict.get("function_call"):
additional_kwargs["function_call"] = dict(function_call)
tool_calls = []
@@ -1332,6 +1363,7 @@ def _convert_dict_to_message(_dict: Mapping[str, Any]) -> BaseMessage:
additional_kwargs=additional_kwargs,
tool_calls=tool_calls,
invalid_tool_calls=invalid_tool_calls,
+ response_metadata={"model_provider": "groq"},
)
if role == "system":
return SystemMessage(content=_dict.get("content", ""))
diff --git a/libs/partners/groq/tests/cassettes/test_web_search.yaml.gz b/libs/partners/groq/tests/cassettes/test_web_search.yaml.gz
new file mode 100644
index 0000000000..bcda783276
Binary files /dev/null and b/libs/partners/groq/tests/cassettes/test_web_search.yaml.gz differ
diff --git a/libs/partners/groq/tests/conftest.py b/libs/partners/groq/tests/conftest.py
new file mode 100644
index 0000000000..ba705a7d5d
--- /dev/null
+++ b/libs/partners/groq/tests/conftest.py
@@ -0,0 +1,37 @@
+from typing import Any
+
+import pytest
+from langchain_tests.conftest import CustomPersister, CustomSerializer
+from langchain_tests.conftest import (
+ _base_vcr_config as _base_vcr_config, # noqa: PLC0414
+)
+from vcr import VCR # type: ignore[import-untyped]
+
+
+def remove_request_headers(request: Any) -> Any:
+ for k in request.headers:
+ request.headers[k] = "**REDACTED**"
+ return request
+
+
+def remove_response_headers(response: dict) -> dict:
+ for k in response["headers"]:
+ response["headers"][k] = "**REDACTED**"
+ return response
+
+
[email protected](scope="session")
+def vcr_config(_base_vcr_config: dict) -> dict: # noqa: F811
+ """Extend the default configuration coming from langchain_tests."""
+ config = _base_vcr_config.copy()
+ config["before_record_request"] = remove_request_headers
+ config["before_record_response"] = remove_response_headers
+ config["serializer"] = "yaml.gz"
+ config["path_transformer"] = VCR.ensure_suffix(".yaml.gz")
+
+ return config
+
+
+def pytest_recording_configure(config: dict, vcr: VCR) -> None:
+ vcr.register_persister(CustomPersister())
+ vcr.register_serializer("yaml.gz", CustomSerializer())
diff --git a/libs/partners/groq/tests/integration_tests/test_chat_models.py b/libs/partners/groq/tests/integration_tests/test_chat_models.py
index 2e25e7ae62..32c2af8182 100644
--- a/libs/partners/groq/tests/integration_tests/test_chat_models.py
+++ b/libs/partners/groq/tests/integration_tests/test_chat_models.py
@@ -665,6 +665,146 @@ async def test_setting_service_tier_request_async() -> None:
assert response.response_metadata.get("service_tier") == "on_demand"
+def test_web_search() -> None:
+ llm = ChatGroq(model="groq/compound")
+ input_message = {
+ "role": "user",
+ "content": "Search for the weather in Boston today.",
+ }
+ full: AIMessageChunk | None = None
+ for chunk in llm.stream([input_message]):
+ full = chunk if full is None else full + chunk
+ assert isinstance(full, AIMessageChunk)
+ assert full.additional_kwargs["reasoning_content"]
+ assert full.additional_kwargs["executed_tools"]
+ assert [block["type"] for block in full.content_blocks] == [
+ "reasoning",
+ "server_tool_call",
+ "server_tool_result",
+ "text",
+ ]
+
+ next_message = {
+ "role": "user",
+ "content": "Now search for the weather in San Francisco.",
+ }
+ response = llm.invoke([input_message, full, next_message])
+ assert [block["type"] for block in response.content_blocks] == [
+ "reasoning",
+ "server_tool_call",
+ "server_tool_result",
+ "text",
+ ]
+
+
[email protected]_cassette("test_web_search.yaml.gz")
+def test_web_search_v1() -> None:
+ llm = ChatGroq(model="groq/compound", output_version="v1")
+ input_message = {
+ "role": "user",
+ "content": "Search for the weather in Boston today.",
+ }
+ full: AIMessageChunk | None = None
+ for chunk in llm.stream([input_message]):
+ full = chunk if full is None else full + chunk
+ assert isinstance(full, AIMessageChunk)
+ assert full.additional_kwargs["reasoning_content"]
+ assert full.additional_kwargs["executed_tools"]
+ assert [block["type"] for block in full.content_blocks] == [
+ "reasoning",
+ "server_tool_call",
+ "server_tool_result",
+ "reasoning",
+ "text",
+ ]
+
+ next_message = {
+ "role": "user",
+ "content": "Now search for the weather in San Francisco.",
+ }
+ response = llm.invoke([input_message, full, next_message])
+ assert [block["type"] for block in response.content_blocks] == [
+ "reasoning",
+ "server_tool_call",
+ "server_tool_result",
+ "text",
+ ]
+
+
+def test_code_interpreter() -> None:
+ llm = ChatGroq(model="groq/compound-mini")
+ input_message = {
+ "role": "user",
+ "content": (
+ "Calculate the square root of 101 and show me the Python code you used."
+ ),
+ }
+ full: AIMessageChunk | None = None
+ for chunk in llm.stream([input_message]):
+ full = chunk if full is None else full + chunk
+ assert isinstance(full, AIMessageChunk)
+ assert full.additional_kwargs["reasoning_content"]
+ assert full.additional_kwargs["executed_tools"]
+ assert [block["type"] for block in full.content_blocks] == [
+ "reasoning",
+ "server_tool_call",
+ "server_tool_result",
+ "text",
+ ]
+
+ next_message = {
+ "role": "user",
+ "content": "Now do the same for 102.",
+ }
+ response = llm.invoke([input_message, full, next_message])
+ assert [block["type"] for block in response.content_blocks] == [
+ "reasoning",
+ "server_tool_call",
+ "server_tool_result",
+ "text",
+ ]
+
+
[email protected]_cassette("test_code_interpreter.yaml.gz")
+def test_code_interpreter_v1() -> None:
+ llm = ChatGroq(model="groq/compound-mini", output_version="v1")
+ input_message = {
+ "role": "user",
+ "content": (
+ "Calculate the square root of 101 and show me the Python code you used."
+ ),
+ }
+ full: AIMessageChunk | None = None
+ for chunk in llm.stream([input_message]):
+ full = chunk if full is None else full + chunk
+ assert isinstance(full, AIMessageChunk)
+ assert full.additional_kwargs["reasoning_content"]
+ assert full.additional_kwargs["executed_tools"]
+ assert [block["type"] for block in full.content_blocks] == [
+ "reasoning",
+ "server_tool_call",
+ "server_tool_result",
+ "reasoning",
+ "text",
+ ]
+
+ next_message = {
+ "role": "user",
+ "content": "Now do the same for 102.",
+ }
+ response = llm.invoke([input_message, full, next_message])
+ assert [block["type"] for block in response.content_blocks] == [
+ "reasoning",
+ "server_tool_call",
+ "server_tool_result",
+ "text",
+ ]
+
+
# Groq does not currently support N > 1
# @pytest.mark.scheduled
# def test_chat_multiple_completions() -> None:
diff --git a/libs/partners/groq/tests/unit_tests/test_chat_models.py b/libs/partners/groq/tests/unit_tests/test_chat_models.py
index eec86d508a..bb43ae9557 100644
--- a/libs/partners/groq/tests/unit_tests/test_chat_models.py
+++ b/libs/partners/groq/tests/unit_tests/test_chat_models.py
@@ -54,7 +54,9 @@ def test__convert_dict_to_message_human() -> None:
def test__convert_dict_to_message_ai() -> None:
message = {"role": "assistant", "content": "foo"}
result = _convert_dict_to_message(message)
- expected_output = AIMessage(content="foo")
+ expected_output = AIMessage(
+ content="foo", response_metadata={"model_provider": "groq"}
+ )
assert result == expected_output
@@ -80,6 +82,7 @@ def test__convert_dict_to_message_tool_call() -> None:
type="tool_call",
)
],
+ response_metadata={"model_provider": "groq"},
)
assert result == expected_output
@@ -124,6 +127,7 @@ def test__convert_dict_to_message_tool_call() -> None:
type="tool_call",
),
],
+ response_metadata={"model_provider": "groq"},
)
assert result == expected_output