Skip to content

armgit / dspy

Public Imported from GitHub
0

DSPy: The framework for programming—not prompting—language models

Python

Support OpenAI response api in LM (#8692)

TomuHirata9029c3b75027
diff --git a/dspy/clients/base_lm.py b/dspy/clients/base_lm.py
index c0550b28e..31be5e3be 100644
--- a/dspy/clients/base_lm.py
+++ b/dspy/clients/base_lm.py
@@ -51,19 +51,10 @@ class BaseLM:
def _process_lm_response(self, response, prompt, messages, **kwargs):
merged_kwargs = {**self.kwargs, **kwargs}
- outputs = []
- for c in response.choices:
- output = {}
- output["text"] = c.message.content if hasattr(c, "message") else c["text"]
- if merged_kwargs.get("logprobs"):
- output["logprobs"] = c.logprobs if hasattr(c, "logprobs") else c["logprobs"]
- if hasattr(c, "message") and getattr(c.message, "tool_calls", None):
- output["tool_calls"] = c.message.tool_calls
- outputs.append(output)
-
- if all(len(output) == 1 for output in outputs):
- # Return a list if every output only has "text" key
- outputs = [output["text"] for output in outputs]
+ if self.model_type == "responses":
+ outputs = self._process_response(response)
+ else:
+ outputs = self._process_completion(response, merged_kwargs)
if settings.disable_history:
return outputs
@@ -163,6 +154,56 @@ class BaseLM:
module.history.pop(0)
module.history.append(entry)
+ def _process_completion(self, response, merged_kwargs):
+ """Process the response of OpenAI chat completion API and extract outputs.
+
+ Args:
+ response: The OpenAI chat completion response
+ https://platform.openai.com/docs/api-reference/chat/object
+ merged_kwargs: Merged kwargs from self.kwargs and method kwargs
+
+ Returns:
+ List of processed outputs
+ """
+ outputs = []
+ for c in response.choices:
+ output = {}
+ output["text"] = c.message.content if hasattr(c, "message") else c["text"]
+ if merged_kwargs.get("logprobs"):
+ output["logprobs"] = c.logprobs if hasattr(c, "logprobs") else c["logprobs"]
+ if hasattr(c, "message") and getattr(c.message, "tool_calls", None):
+ output["tool_calls"] = c.message.tool_calls
+ outputs.append(output)
+
+ if all(len(output) == 1 for output in outputs):
+ # Return a list if every output only has "text" key
+ outputs = [output["text"] for output in outputs]
+
+ return outputs
+
+ def _process_response(self, response):
+ """Process the response of OpenAI Response API and extract outputs.
+
+ Args:
+ response: OpenAI Response API response
+ https://platform.openai.com/docs/api-reference/responses/object
+
+ Returns:
+ List of processed outputs
+ """
+ outputs = []
+ tool_calls = []
+ for output_item in response.output:
+ if output_item.type == "message":
+ for content_item in output_item.content:
+ outputs.append(content_item.text)
+ elif output_item.type == "function_call":
+ tool_calls.append(output_item.model_dump())
+
+ if tool_calls:
+ outputs.append({"tool_calls": tool_calls})
+ return outputs
+
def inspect_history(n: int = 1):
"""The global history shared across all LMs."""
diff --git a/dspy/clients/lm.py b/dspy/clients/lm.py
index efa5f4941..fc790ee1e 100644
--- a/dspy/clients/lm.py
+++ b/dspy/clients/lm.py
@@ -29,7 +29,7 @@ class LM(BaseLM):
def __init__(
self,
model: str,
- model_type: Literal["chat", "text"] = "chat",
+ model_type: Literal["chat", "text", "responses"] = "chat",
temperature: float = 0.0,
max_tokens: int = 4000,
cache: bool = True,
@@ -122,7 +122,12 @@ class LM(BaseLM):
messages = messages or [{"role": "user", "content": prompt}]
kwargs = {**self.kwargs, **kwargs}
- completion = litellm_completion if self.model_type == "chat" else litellm_text_completion
+ if self.model_type == "chat":
+ completion = litellm_completion
+ elif self.model_type == "text":
+ completion = litellm_text_completion
+ elif self.model_type == "responses":
+ completion = litellm_responses_completion
completion, litellm_cache_args = self._get_cached_completion_fn(completion, cache, enable_memory_cache)
results = completion(
@@ -131,14 +136,7 @@ class LM(BaseLM):
cache=litellm_cache_args,
)
- if any(c.finish_reason == "length" for c in results["choices"]):
- logger.warning(
- f"LM response was truncated due to exceeding max_tokens={self.kwargs['max_tokens']}. "
- "You can inspect the latest LM interactions with `dspy.inspect_history()`. "
- "To avoid truncation, consider passing a larger max_tokens when setting up dspy.LM. "
- f"You may also consider increasing the temperature (currently {self.kwargs['temperature']}) "
- " if the reason for truncation is repetition."
- )
+ self._check_truncation(results)
if not getattr(results, "cache_hit", False) and dspy.settings.usage_tracker and hasattr(results, "usage"):
settings.usage_tracker.add_usage(self.model, dict(results.usage))
@@ -152,7 +150,12 @@ class LM(BaseLM):
messages = messages or [{"role": "user", "content": prompt}]
kwargs = {**self.kwargs, **kwargs}
- completion = alitellm_completion if self.model_type == "chat" else alitellm_text_completion
+ if self.model_type == "chat":
+ completion = alitellm_completion
+ elif self.model_type == "text":
+ completion = alitellm_text_completion
+ elif self.model_type == "responses":
+ completion = alitellm_responses_completion
completion, litellm_cache_args = self._get_cached_completion_fn(completion, cache, enable_memory_cache)
results = await completion(
@@ -161,14 +164,7 @@ class LM(BaseLM):
cache=litellm_cache_args,
)
- if any(c.finish_reason == "length" for c in results["choices"]):
- logger.warning(
- f"LM response was truncated due to exceeding max_tokens={self.kwargs['max_tokens']}. "
- "You can inspect the latest LM interactions with `dspy.inspect_history()`. "
- "To avoid truncation, consider passing a larger max_tokens when setting up dspy.LM. "
- f"You may also consider increasing the temperature (currently {self.kwargs['temperature']}) "
- " if the reason for truncation is repetition."
- )
+ self._check_truncation(results)
if not getattr(results, "cache_hit", False) and dspy.settings.usage_tracker and hasattr(results, "usage"):
settings.usage_tracker.add_usage(self.model, dict(results.usage))
@@ -258,6 +254,16 @@ class LM(BaseLM):
]
return {key: getattr(self, key) for key in state_keys} | self.kwargs
+ def _check_truncation(self, results):
+ if self.model_type != "responses" and any(c.finish_reason == "length" for c in results["choices"]):
+ logger.warning(
+ f"LM response was truncated due to exceeding max_tokens={self.kwargs['max_tokens']}. "
+ "You can inspect the latest LM interactions with `dspy.inspect_history()`. "
+ "To avoid truncation, consider passing a larger max_tokens when setting up dspy.LM. "
+ f"You may also consider increasing the temperature (currently {self.kwargs['temperature']}) "
+ " if the reason for truncation is repetition."
+ )
+
def _get_stream_completion_fn(
request: dict[str, Any],
@@ -381,3 +387,38 @@ async def alitellm_text_completion(request: dict[str, Any], num_retries: int, ca
retry_strategy="exponential_backoff_retry",
**request,
)
+
+def litellm_responses_completion(request: dict[str, Any], num_retries: int, cache: dict[str, Any] | None = None):
+ cache = cache or {"no-cache": True, "no-store": True}
+ request = _convert_chat_request_to_responses_request(request)
+
+ return litellm.responses(
+ cache=cache,
+ num_retries=num_retries,
+ retry_strategy="exponential_backoff_retry",
+ **request,
+ )
+
+
+async def alitellm_responses_completion(request: dict[str, Any], num_retries: int, cache: dict[str, Any] | None = None):
+ cache = cache or {"no-cache": True, "no-store": True}
+ request = _convert_chat_request_to_responses_request(request)
+
+ return await litellm.aresponses(
+ cache=cache,
+ num_retries=num_retries,
+ retry_strategy="exponential_backoff_retry",
+ **request,
+ )
+
+def _convert_chat_request_to_responses_request(request: dict[str, Any]):
+ if "messages" in request:
+ content_blocks = []
+ for msg in request.pop("messages"):
+ c = msg.get("content")
+ if isinstance(c, str):
+ content_blocks.append({"type": "input_text", "text": c})
+ elif isinstance(c, list):
+ content_blocks.extend(c)
+ request["input"] = [{"role": msg.get("role", "user"), "content": content_blocks}]
+ return request
diff --git a/tests/clients/test_lm.py b/tests/clients/test_lm.py
index 1385c990c..56818e0e7 100644
--- a/tests/clients/test_lm.py
+++ b/tests/clients/test_lm.py
@@ -1,3 +1,4 @@
+import json
import time
from unittest import mock
from unittest.mock import patch
@@ -5,6 +6,7 @@ from unittest.mock import patch
import litellm
import pydantic
import pytest
+from litellm.types.llms.openai import ResponseAPIUsage, ResponsesAPIResponse
from litellm.utils import Choices, Message, ModelResponse
from openai import RateLimitError
@@ -12,6 +14,33 @@ import dspy
from dspy.utils.usage_tracker import track_usage
+def make_response(output_blocks):
+ return ResponsesAPIResponse(
+ id="resp_1",
+ created_at=0.0,
+ error=None,
+ incomplete_details=None,
+ instructions=None,
+ model="openai/dspy-test-model",
+ object="response",
+ output=output_blocks,
+ metadata = {},
+ parallel_tool_calls=False,
+ temperature=1.0,
+ tool_choice="auto",
+ tools=[],
+ top_p=1.0,
+ max_output_tokens=None,
+ previous_response_id=None,
+ reasoning=None,
+ status="completed",
+ text=None,
+ truncation="disabled",
+ usage=ResponseAPIUsage(input_tokens=1, output_tokens=1, total_tokens=2),
+ user=None,
+ )
+
+
def test_chat_lms_can_be_queried(litellm_test_server):
api_base, _ = litellm_test_server
expected_response = ["Hi!"]
@@ -409,3 +438,66 @@ def test_disable_history():
choices=[Choices(message=Message(content="test answer"))],
model="openai/gpt-4o-mini",
)
+
+def test_responses_api(litellm_test_server):
+ api_base, _ = litellm_test_server
+ expected_text = "This is a test answer from responses API."
+
+ api_response = make_response(
+ output_blocks=[
+ {
+ "id": "msg_1",
+ "type": "message",
+ "role": "assistant",
+ "status": "completed",
+ "content": [
+ {"type": "output_text", "text": expected_text, "annotations": []}
+ ],
+ }
+ ]
+ )
+
+ with mock.patch("litellm.responses", autospec=True, return_value=api_response) as dspy_responses:
+ lm = dspy.LM(
+ model="openai/dspy-test-model",
+ api_base=api_base,
+ api_key="fakekey",
+ model_type="responses",
+ cache=False,
+ cache_in_memory=False,
+ )
+ assert lm("openai query") == [expected_text]
+
+ dspy_responses.assert_called_once()
+ assert dspy_responses.call_args.kwargs["model"] == "openai/dspy-test-model"
+
+
+def test_responses_api_tool_calls(litellm_test_server):
+ api_base, _ = litellm_test_server
+ expected_tool_call = {
+ "type": "function_call",
+ "name": "get_weather",
+ "arguments": json.dumps({"city": "Paris"}),
+ "call_id": "call_1",
+ "status": "completed",
+ "id": "call_1",
+ }
+ expected_response = [{"tool_calls": [expected_tool_call]}]
+
+ api_response = make_response(
+ output_blocks=[expected_tool_call],
+ )
+
+ with mock.patch("litellm.responses", autospec=True, return_value=api_response) as dspy_responses:
+ lm = dspy.LM(
+ model="openai/dspy-test-model",
+ api_base=api_base,
+ api_key="fakekey",
+ model_type="responses",
+ cache=False,
+ cache_in_memory=False,
+ )
+ assert lm("openai query") == expected_response
+
+ dspy_responses.assert_called_once()
+ assert dspy_responses.call_args.kwargs["model"] == "openai/dspy-test-model"