Code
import dspy
def init() -> None:
= dspy.LM("gemini/gemini-1.5-flash")
lm =lm, docstring_parsing=False) dspy.configure(lm
dspy
is a powerful library for building and chaining language model (LM) pipelines. In this article, we’ll explore how to use dspy
to transform concise answers into Mexican slang and further into “fresa” teen girl slang. We’ll also demonstrate how to summarize these transformed answers while maintaining the tone and style.
dspy
?dspy
simplifies the process of building and chaining LM pipelines. It allows you to define custom modules and signatures, making it easy to create complex workflows.
Here are some key features:
dspy
Before diving into the code, let’s set up dspy
with a language model.
In this example, we’ll use the gemini/gemini-1.5-flash
model.
pip install dspy
import dspy
def init() -> None:
= dspy.LM("gemini/gemini-1.5-flash")
lm =lm, docstring_parsing=False) dspy.configure(lm
Signatures define the input and output fields for your LM tasks. Here, we define four signatures:
Please note that doc-strings in
dspy
are used as prompts to, so we will avoid using doc-strings in ourdspy.Signatures
class QA(dspy.Signature):
str = dspy.InputField(desc="question")
question: str = dspy.OutputField(desc="answer")
answer:
class Mexicanize(dspy.Signature):
str = dspy.InputField(desc="The input answer to be Mexicanized.")
answer: str = dspy.OutputField(
mexicanized_answer: ="The output answer in Mexican slang, with a lot of examples and explanation."
desc
)
class Frezea(dspy.Signature):
str = dspy.InputField(
phrase: ="The phrase, that will be converted to a teenager fresa girl slang."
desc
)str = dspy.OutputField(
fresa_phrase: ='The phrase, with a slang of a young "fresa" teen girl with some '
desc"spelling mistakes and some numbers used as letters, but not more than 30%."
)
class Resumen(dspy.Signature):
str = dspy.InputField(desc="El texto a resumir")
texto: str = dspy.OutputField(
resumen: ="Un resumen del texto, que mantiene el tono,"
desc"gramatica y la ortografia (aunque sea mala)."
"El resumen ha de ser mucho mas corto que el texto original, al menos la mitad."
"El resumen debe parecer como si lo escribio una niña fresa mexicana, con 13"
"años, contendra errores ortograficos y algunas letras seran numeros"
)
Custom modules allow you to chain multiple signatures together. Here, we define two modules:
class MexicanizeAnswer(dspy.Module):
def __init__(self) -> None:
super().__init__()
self.qa = dspy.ChainOfThought(QA)
self.mexicanize = dspy.ChainOfThought(Mexicanize)
def forward(self, question: str) -> str:
= self.qa(question=question).answer
answer = self.mexicanize(answer=answer).mexicanized_answer
mexicanized return mexicanized
class FresaAnswer(dspy.Module):
def __init__(self, summarized=False) -> None:
super().__init__()
self.qa = dspy.ChainOfThought(QA)
self.mexicanize = dspy.ChainOfThought(Mexicanize)
self.frezea = dspy.ChainOfThought(Frezea)
if summarized:
self.summary = dspy.ChainOfThought(Resumen)
else:
self.summary = None
def forward(self, question: str) -> str:
= self.qa(question=question).answer
answer = self.mexicanize(answer=answer).mexicanized_answer
mexicanized = self.frezea(phrase=mexicanized).fresa_phrase
frezeada if self.summary:
return self.summary(texto=frezeada).resumen
return frezeada
Now that we’ve defined our modules, let’s use them to transform answers.
def fresea(question: str, summarized=False) -> None:
= FresaAnswer(summarized=summarized)
qa = qa(question=question)
answer print(f"Q: {question}")
print(f"A: {answer}")
def mexican_response(question: str = "How many states are in Argentina?") -> None:
= MexicanizeAnswer()
qa = qa(question=question)
answer print(f"Q: {question}")
print(f"A: {answer}")
def main():
init()
mexican_response()print("===========================================================================")
"Cuantos pandas hay en el mundo?")
mexican_response(print("===========================================================================")
fresea("Was there life before the third generation starts? If not, why"
"does our DNA is overycomplex since the begining? Reflect on the idea."
)print("===========================================================================")
fresea("Was there life before the third generation starts? If not, why"
"does our DNA is overycomplex since the begining? Reflect on the idea.",
=True,
summarized
)
if __name__ == "__main__":
main()
Q: How many states are in Argentina?
A: ¡Ay, wey, 24! Eso me recuerda a... ¿24 horas sin chelas? ¡Ni de broma, carnal! O tal vez... ¡24 tacos al pastor, órale! Eso sí que es una fiesta. O, si eres bien fresa, 24 horas en un spa... ¡qué flojera! Depende del contexto, ¿no? Pero 24, en sí, no tiene un equivalente "naco" o "chido" directo. Es más como el número de horas en un día, o la edad de alguien... ¡chingón!
(Translation: Oh man, 24! That reminds me of... 24 hours without beer? No way, dude! Or maybe... 24 al pastor tacos, let's go! That's a party. Or, if you're really fancy, 24 hours at a spa... so boring! It depends on the context, right? But 24 itself doesn't have a direct "ghetto" or "cool" equivalent. It's more like the number of hours in a day, or someone's age... awesome!)
===========================================================================
Q: Cuantos pandas hay en el mundo?
A: ¡Órale! Se calcula que andan como unos 1,800 pandas gigantes en la mera naturaleza, ¿sabes? Y luego, unos cuantos cientos más en el "cuidadito," o sea, en cautiverio. En total, pues, andamos hablando de unos 2,000 o 2,100 pandas en el mundo, más o menos. Pero, ¡ey!, eso es un cálculo, ¿eh? Puede que haya uno que otro más o menos, ni quien lo sepa con exactitud. ¡Esos pandas son muy escurridizos! Como encontrar un cinco pesos en la bolsa de un borracho.
===========================================================================
Q: Was there life before the third generation starts? If not, whydoes our DNA is overycomplex since the begining? Reflect on the idea.
A: ¡No manches! ¿Q onda con esa idea d q la vida empezó asta la 3ra generación? ¡Eso está bien loko! Como si antes no ubier4 nada, ¿no? Es como decir q un árbol gigante salió d la nada, sin semillita ni na. La neta, la vida, desde el principio, ha sido un rollo bien largo. El ADN, aunq se ve bien complejo ahorita, no empezó así d enredado. Fue como una bola d estambre q se fue haciendo mas grande poko a poko, ¿m entiendes? A través d millones d años, ¡ay, wey!, fue evolucionando, como cuando te haces experta en algo, poko a poko, con práctica y to. La complejidad q vemos ahora es el resultado d un buen d tiempo y cambios, ¡un chingo d evolución, carnal! Así q, olvídate d esa idea d q la vida empezó d repente, ¡eso no tiene caso!
===========================================================================
Q: Was there life before the third generation starts? If not, whydoes our DNA is overycomplex since the begining? Reflect on the idea.
A: ¡OMG! Esa idea d q la vida empezó en la 3ra generación está bien loka! Es como si un árbol gigante apareciera así, d la nada. La vida, desde el principio, ha sido un mega rollo. El ADN empezó chikito, como una bolita d estambre, y se fue haciendo más grande con el tiempo. Evolucionó, como cuando te haces experta en algo, ¡poco a poko! La complejidad d ahora es por muchísimos años d evolución. ¡Olvídate d q la vida empezó d repente, wey! Eso no tiene sentido. :P
dspy
is a versatile tool for building and chaining LM pipelines. By defining custom signatures and modules, you can create complex workflows like transforming answers into Mexican slang and “fresa” teen girl slang.
The examples provided in this article demonstrate how to use dspy
to achieve these transformations, with optional summarization to maintain the tone and style.
Whether you’re working on language transformation tasks or other LM-based applications, dspy
offers the flexibility and power to build robust and reusable pipelines.