AI Hints
Home›LangChain Tutorial›Rewriting and Extraction
LangChain · Lesson 112 of 120

Translation and Rewriting

Changing style.

⏱ 2 min read▶ Video at 2:07:31🎓 Free
Watch this lesson in the LangChain courseWatch on YouTube ↗Full LangChain course

Models are excellent at changing how text sounds, while keeping what it says. Simpler words for children. A formal tone for a letter. Or a different language altogether.

Translation and Rewriting
From the video: Translation and Rewriting
  • Keep the meaning
  • Change the style
  • Or the language

One chain, many styles

The prompt has two slots, the audience, and the text. One chain handles every rewrite. We take one sentence from the returns policy, and batch it for three audiences. A child, a formal letter, and a French speaking customer. Run it. The same facts appear in three very different styles.

rewrite_styles.pypython
from langchain.chat_models import init_chat_model
from langchain_core.output_parsers import StrOutputParser
from langchain_core.prompts import ChatPromptTemplate

model = init_chat_model("google_genai:gemini-flash-lite-latest", temperature=0)
prompt = ChatPromptTemplate.from_template("Rewrite this for {audience}. One sentence.\n\n{text}")
chain = prompt | model | StrOutputParser()

text = "Refunds go back to the original payment method within 5 working days."
audiences = ["a seven-year-old", "a formal letter", "a French-speaking customer, in French"]
jobs = [{"audience": a, "text": text} for a in audiences]
for job, result in zip(jobs, chain.batch(jobs)):
    print(f"{job['audience']}:\n  {result.strip()}")
Output
a seven-year-old:
  You will get your money back the exact same way you paid within five school days.
a formal letter:
  Please be advised that refunds will be credited to the original method of payment
  within five business days.
a French-speaking customer, in French:
  Le remboursement sera effectué sur le mode de paiement d'origine dans un délai de 5
  jours ouvrés.

Rewriting tips

Say who the audience is, rather than just, make it simpler. Ask the model to keep every fact, like numbers and dates. For translation, name the language, and the tone. And check important translations with a native speaker before you publish them.

keyvalue
Namethe audience
Keepevery fact
Translatelanguage + tone
Checkimportant text

Summary

A single prompt with an audience slot rewrites text for anyone, in any language. Next, turning messy text into neat rows of data.

Key takeaways
  • {audience} slot
  • chain.batch
  • Same facts, new style
Next up: Data from Tables — text to rows