Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save luisjunco/4fb3fa1ee014e7ac7870a88028fdc350 to your computer and use it in GitHub Desktop.

Select an option

Save luisjunco/4fb3fa1ee014e7ac7870a88028fdc350 to your computer and use it in GitHub Desktop.
Exercise to practice LangChain Fundamentals (LC<0.3)

Practice: From Prompts to Chains


Iteration 1 — Prompt template + simple chain

Create a chain that translates a word into a given language.

  1. Build a PromptTemplate with two input variables, word and language.
  2. Create the chain with prompt | llm.
  3. Invoke it with word="hello" and language="Spanish", and print the result.

Iteration 2 — Multi-input chain

Create a chain that writes a short bio for a person.

  1. Build a PromptTemplate with three input variables: name, country, and hobby.
  2. Create the chain and invoke it with values of your choice.
  3. Print the result.

Iteration 3 — Sequential chain

Chain two steps together: first generate a short product name for a given item, then write a one-line slogan for that product name.

  1. Create prompt_one → generates a product name from item (e.g. "a reusable water bottle").
  2. Create prompt_two → generates a slogan from product_name.
  3. Combine both into a SimpleSequentialChain.
  4. Run it and print the final slogan.

Bonus iterations

Bonus 1: Turn Iteration 2 into a few-shot prompt. Give the model 2-3 example bios (in the format you expect) before asking it to generate a new one.

Bonus 2: Build an LLMRouterChain that routes a question to one of two destination chains: math (for math questions) or history (for history questions). Test it with one question of each type.


Solution — Iteration 1
prompt = PromptTemplate(
    input_variables=["word", "language"],
    template="Translate the word '{word}' into {language}. Only return the translation."
)

chain = prompt | llm

result = chain.invoke({"word": "hello", "language": "Spanish"})
print(result)
Solution — Iteration 2
prompt = PromptTemplate(
    input_variables=["name", "country", "hobby"],
    template="Write a short, friendly bio (2-3 sentences) for {name}, who is from {country} and enjoys {hobby} in their free time."
)

chain = prompt | llm

result = chain.invoke({"name": "Maria", "country": "Colombia", "hobby": "rock climbing"})
print(result)
Solution — Iteration 3
prompt_one = PromptTemplate(
    input_variables=["item"],
    template="Come up with a short, catchy product name for: {item}. Only return the name."
)
chain_one = LLMChain(llm=llm, prompt=prompt_one)

prompt_two = PromptTemplate(
    input_variables=["product_name"],
    template="Write a one-line slogan for a product called {product_name}."
)
chain_two = LLMChain(llm=llm, prompt=prompt_two)

overall_chain = SimpleSequentialChain(chains=[chain_one, chain_two], verbose=True)
result = overall_chain.run("a reusable water bottle")
print(result)
Solution — Bonus 1
examples = [
    {
        "name": "Liam",
        "country": "Ireland",
        "hobby": "playing guitar",
        "bio": "Liam is from Ireland. When he's not working, you'll find him playing guitar."
    },
    {
        "name": "Aiko",
        "country": "Japan",
        "hobby": "painting",
        "bio": "Aiko is from Japan. In her free time, she loves painting."
    },
    {
        "name": "Diego",
        "country": "Argentina",
        "hobby": "playing football",
        "bio": "Diego is from Argentina. He spends his weekends playing football."
    },
]

example_prompt = PromptTemplate(
    input_variables=["name", "country", "hobby", "bio"],
    template="Name: {name}\nCountry: {country}\nHobby: {hobby}\nBio: {bio}"
)

few_shot_prompt = FewShotPromptTemplate(
    examples=examples,
    example_prompt=example_prompt,
    prefix="Write a short bio following the format of the examples below.",
    suffix="Name: {name}\nCountry: {country}\nHobby: {hobby}\nBio:",
    input_variables=["name", "country", "hobby"]
)

chain = few_shot_prompt | llm
result = chain.invoke({"name": "Maria", "country": "Colombia", "hobby": "rock climbing"})
print(result)
Solution — Bonus 2
from langchain.chains.router import MultiPromptChain
from langchain.chains.router.llm_router import LLMRouterChain, RouterOutputParser
from langchain.chains.router.multi_prompt_prompt import MULTI_PROMPT_ROUTER_TEMPLATE

prompt_infos = [
    {
        "name": "math",
        "description": "Good for answering math questions",
        "prompt_template": "You are a math teacher. Answer this question:\n{input}"
    },
    {
        "name": "history",
        "description": "Good for answering history questions",
        "prompt_template": "You are a history teacher. Answer this question:\n{input}"
    },
]

destination_chains = {}
for info in prompt_infos:
    prompt = PromptTemplate(template=info["prompt_template"], input_variables=["input"])
    destination_chains[info["name"]] = LLMChain(llm=llm, prompt=prompt)

destinations = [f"{p['name']}: {p['description']}" for p in prompt_infos]
destinations_str = "\n".join(destinations)

router_template = MULTI_PROMPT_ROUTER_TEMPLATE.format(destinations=destinations_str)
router_prompt = PromptTemplate(
    template=router_template,
    input_variables=["input"],
    output_parser=RouterOutputParser(),
)
router_chain = LLMRouterChain.from_llm(llm, router_prompt)

default_chain = LLMChain(llm=llm, prompt=PromptTemplate(template="{input}", input_variables=["input"]))

chain = MultiPromptChain(
    router_chain=router_chain,
    destination_chains=destination_chains,
    default_chain=default_chain,
    verbose=True,
)

print(chain.run("What is 15% of 200?"))
print(chain.run("Who was the first president of the United States?"))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment