Transforming Answers with dspy: Mexican Slang and Fresa Teen Girl Slang

Author

Andres Monge

Published

February 25, 2025

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.

Why Use 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:

  • Custom Signatures: Define input and output fields for your LM tasks.
  • Chain of Thought: Use reasoning steps to improve the quality of outputs.
  • Modular Design: Build reusable modules for specific tasks.

Setting Up 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
Code
import dspy

def init() -> None:
    lm = dspy.LM("gemini/gemini-1.5-flash")
    dspy.configure(lm=lm, docstring_parsing=False)

Defining Signatures

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 our dspy.Signatures

  1. QA: For answering questions.
  2. Mexicanize: For transforming answers into Mexican slang.
  3. Frezea: For transforming Mexican slang into “fresa” teen girl slang.
  4. Resumen: For summarizing text in the style of a “fresa” teen girl.
Code
class QA(dspy.Signature):
    question: str = dspy.InputField(desc="question")
    answer: str = dspy.OutputField(desc="answer")

class Mexicanize(dspy.Signature):
    answer: str = dspy.InputField(desc="The input answer to be Mexicanized.")
    mexicanized_answer: str = dspy.OutputField(
        desc="The output answer in Mexican slang, with a lot of examples and explanation."
    )

class Frezea(dspy.Signature):
    phrase: str = dspy.InputField(
        desc="The phrase, that will be converted to a teenager fresa girl slang."
    )
    fresa_phrase: str = dspy.OutputField(
        desc='The phrase, with a slang of a young "fresa" teen girl with some '
        "spelling mistakes and some numbers used as letters, but not more than 30%."
    )

class Resumen(dspy.Signature):
    texto: str = dspy.InputField(desc="El texto a resumir")
    resumen: str = dspy.OutputField(
        desc="Un resumen del texto, que mantiene el tono,"
        "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"
    )

Building Custom Modules

Custom modules allow you to chain multiple signatures together. Here, we define two modules:

  1. MexicanizeAnswer: Transforms a concise answer into Mexican slang.
  2. FresaAnswer: Transforms a concise answer into “fresa” teen girl slang, with an optional summarization step.
Code
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:
        answer = self.qa(question=question).answer
        mexicanized = self.mexicanize(answer=answer).mexicanized_answer
        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:
        answer = self.qa(question=question).answer
        mexicanized = self.mexicanize(answer=answer).mexicanized_answer
        frezeada = self.frezea(phrase=mexicanized).fresa_phrase
        if self.summary:
            return self.summary(texto=frezeada).resumen
        return frezeada

Using the Modules

Now that we’ve defined our modules, let’s use them to transform answers.

Code
def fresea(question: str, summarized=False) -> None:
    qa = FresaAnswer(summarized=summarized)
    answer = qa(question=question)
    print(f"Q: {question}")
    print(f"A: {answer}")

def mexican_response(question: str = "How many states are in Argentina?") -> None:
    qa = MexicanizeAnswer()
    answer = qa(question=question)
    print(f"Q: {question}")
    print(f"A: {answer}")

def main():
    init()
    mexican_response()
    print("===========================================================================")
    mexican_response("Cuantos pandas hay en el mundo?")
    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.",
        summarized=True,
    )

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

Conclusion

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.