Repositories / more_dspy.git
src/more_dspy/__init__.py
Clone (read-only): git clone http://git.guha-anderson.com/git/more_dspy.git
from typing import Optional
import dspy
from dspy.adapters.chat_adapter import ChatAdapter
from dspy.dsp.utils.settings import settings
from dspy.predict.predict import Predict
from dspy.utils.exceptions import AdapterParseError
from more_dspy.chat_adapter_with_trailing_instructions import ChatAdapterWithTrailingInstructions
__all__ = [
"ChatAdapterWithTrailingInstructions",
"format_prompt",
"parse_response",
]
def _get_predict(module: dspy.Module) -> Predict:
"""Extract the inner Predict module from any DSPy module."""
if isinstance(module, Predict):
return module
if hasattr(module, "predict") and isinstance(module.predict, Predict):
return module.predict
raise TypeError(f"Cannot extract a Predict module from {type(module).__name__}")
def format_prompt(module: dspy.Module, **kwargs) -> list[dict]:
"""Produce the chat messages that would be sent to the LM.
Uses the adapter from ``dspy.settings`` (falling back to ``ChatAdapter``).
No LM needs to be configured.
"""
predict = _get_predict(module)
adapter = settings.adapter or ChatAdapter()
signature = predict.signature
demos = predict.demos
return adapter.format(signature=signature, demos=demos, inputs=kwargs)
def parse_response(module: dspy.Module, response: str) -> Optional[dspy.Prediction]:
"""Parse a raw LM response string into a ``dspy.Prediction``.
Returns ``None`` if the response cannot be parsed.
"""
predict = _get_predict(module)
adapter = settings.adapter or ChatAdapter()
signature = predict.signature
try:
fields = adapter.parse(signature, response)
except (AdapterParseError, Exception):
return None
return dspy.Prediction(**fields)
def main() -> None:
print("Hello from more-dspy!")