|
| 1 | +from typing import TYPE_CHECKING, Any, Optional |
| 2 | + |
| 3 | +import litellm |
| 4 | +import pydantic |
| 5 | + |
| 6 | +from dspy.adapters.types.base_type import Type |
| 7 | + |
| 8 | +if TYPE_CHECKING: |
| 9 | + from dspy.clients.lm import LM |
| 10 | + from dspy.signatures.signature import Signature |
| 11 | + |
| 12 | + |
| 13 | +class Reasoning(Type): |
| 14 | + """Reasoning type in DSPy. |
| 15 | +
|
| 16 | + This type is useful when you want the DSPy output to include the reasoning of the LM. We build this type so that |
| 17 | + DSPy can support the reasoning model and non-reasoning model with the same code. |
| 18 | +
|
| 19 | + This is a str-like type, you can convert a string directly to a Reasoning object, and from DSPy adapters' |
| 20 | + perspective, `Reasoning` is treated as a string. |
| 21 | + """ |
| 22 | + |
| 23 | + content: str |
| 24 | + |
| 25 | + def format(self): |
| 26 | + return f"{self.content}" |
| 27 | + |
| 28 | + @pydantic.model_validator(mode="before") |
| 29 | + @classmethod |
| 30 | + def validate_input(cls, data: Any): |
| 31 | + if isinstance(data, cls): |
| 32 | + return data |
| 33 | + |
| 34 | + if isinstance(data, str): |
| 35 | + return {"content": data} |
| 36 | + |
| 37 | + if isinstance(data, dict): |
| 38 | + if "content" not in data: |
| 39 | + raise ValueError("`content` field is required for `dspy.Reasoning`") |
| 40 | + if not isinstance(data["content"], str): |
| 41 | + raise ValueError(f"`content` field must be a string, but received type: {type(data['content'])}") |
| 42 | + return {"content": data["content"]} |
| 43 | + |
| 44 | + raise ValueError(f"Received invalid value for `dspy.Reasoning`: {data}") |
| 45 | + |
| 46 | + @classmethod |
| 47 | + def adapt_to_native_lm_feature( |
| 48 | + cls, |
| 49 | + signature: type["Signature"], |
| 50 | + field_name: str, |
| 51 | + lm: "LM", |
| 52 | + lm_kwargs: dict[str, Any], |
| 53 | + ) -> type["Signature"]: |
| 54 | + if "reasoning_effort" in lm_kwargs: |
| 55 | + # `lm_kwargs` overrides `lm.kwargs`. |
| 56 | + reasoning_effort = lm_kwargs["reasoning_effort"] |
| 57 | + elif "reasoning_effort" in lm.kwargs: |
| 58 | + reasoning_effort = lm.kwargs["reasoning_effort"] |
| 59 | + else: |
| 60 | + # Turn on the native reasoning explicitly if Reasoning field is present in the signature and no explicit |
| 61 | + # reasoning effort is set in `lm_kwargs` or `lm.kwargs`. |
| 62 | + reasoning_effort = "low" |
| 63 | + |
| 64 | + if reasoning_effort is None or not litellm.supports_reasoning(lm.model): |
| 65 | + # If users explicitly set `reasoning_effort` to None or the LM doesn't support reasoning, we don't enable |
| 66 | + # native reasoning. |
| 67 | + return signature |
| 68 | + |
| 69 | + if "gpt-5" in lm.model and lm.model_type == "chat": |
| 70 | + # There is a caveat of Litellm as 1.79.0 that when using the chat completion API on GPT-5 family models, |
| 71 | + # the reasoning content is not available in the response. As a workaround, we don't enable the native |
| 72 | + # reasoning feature for GPT-5 family models when using the chat completion API. |
| 73 | + # Litellm issue: https://github.com/BerriAI/litellm/issues/14748 |
| 74 | + return signature |
| 75 | + |
| 76 | + lm_kwargs["reasoning_effort"] = reasoning_effort |
| 77 | + # Delete the reasoning field from the signature to use the native reasoning feature. |
| 78 | + return signature.delete(field_name) |
| 79 | + |
| 80 | + @classmethod |
| 81 | + def parse_lm_response(cls, response: str | dict[str, Any]) -> Optional["Reasoning"]: |
| 82 | + """Parse the LM response into a Reasoning object.""" |
| 83 | + if "reasoning_content" in response: |
| 84 | + return Reasoning(content=response["reasoning_content"]) |
| 85 | + return None |
| 86 | + |
| 87 | + @classmethod |
| 88 | + def parse_stream_chunk(cls, chunk) -> str | None: |
| 89 | + """ |
| 90 | + Parse a stream chunk into reasoning content if available. |
| 91 | +
|
| 92 | + Args: |
| 93 | + chunk: A stream chunk from the LM. |
| 94 | +
|
| 95 | + Returns: |
| 96 | + The reasoning content (str) if available, None otherwise. |
| 97 | + """ |
| 98 | + try: |
| 99 | + if choices := getattr(chunk, "choices", None): |
| 100 | + return getattr(choices[0].delta, "reasoning_content", None) |
| 101 | + except Exception: |
| 102 | + return None |
| 103 | + |
| 104 | + @classmethod |
| 105 | + def is_streamable(cls) -> bool: |
| 106 | + return True |
| 107 | + |
| 108 | + def __repr__(self) -> str: |
| 109 | + return f"{self.content!r}" |
| 110 | + |
| 111 | + def __str__(self) -> str: |
| 112 | + return self.content |
| 113 | + |
| 114 | + def __eq__(self, other: object) -> bool: |
| 115 | + if isinstance(other, Reasoning): |
| 116 | + return self.content == other.content |
| 117 | + if isinstance(other, str): |
| 118 | + return self.content == other |
0 commit comments