Files
LangChainPractice/first_chain.ipynb

4.0 KiB

In [9]:
from langchain_ollama import ChatOllama
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.caches import InMemoryCache 
from langchain_core.globals import set_llm_cache
import textwrap

set_llm_cache(InMemoryCache())

#Initialize the language model
llm = ChatOllama(
    model="gemma4:12b-mlx",
    base_url="http://mini2.dorceus.local:11434"
)
llm2 = ChatOllama(
    model="qwen3.5:35b-mlx",
    base_url="http://studio1.dorceus.local:11434"
)

llm_with_retry = llm.with_retry(
    stop_after_attempt= 3
)
llm2_with_retry = llm2.with_retry(stop_after_attempt=3)

runner = llm_with_retry.with_fallbacks([llm2_with_retry])

#Create a prompt template
prompt = ChatPromptTemplate.from_template(
    "Write a brief, engaging paragraph about {topic}"
)

prompt2  = ChatPromptTemplate.from_template(
    "Summarize the following in one sentence : {paragraph}"
)

prompt3 = ChatPromptTemplate.from_template(
    "Suggest some side dished that goes with the following food description : {food_description}"
)

#Create the chain 
# chain = prompt | llm
# chain2 = prompt2 | llm2
# chain3 = prompt3 | llm2 

#sequential chain
# seq_chain = (
#     {
#         "paragraph" : prompt,
#         "food_description" : prompt2
#     }
#     | prompt2 
#     | prompt3 
#     | llm2
# )

seq_chain = (
    prompt
    | (lambda message : {"paragraph" : message.content})
    | prompt2 
    | (lambda message : {"food_description" : message.content})
    | prompt3 
    | runner
)

response = None
for i in range(1,5) :
    response = chain.invoke(
        {"topic": "Boeuf bourguignon"}
    )
    #print(response.content)

print("DONE")
print(textwrap.fill(response.content, 150) )

#Run the chain
# result = chain.invoke({"topic": "adobong baboy"})
# result2 = chain2.invoke({"topic": result.content})
# result3 = chain3.invoke({"food_description" : result2.content})
# print(result.content)
# print(result2.content)
# print(result3.content)

DONE
Imagine a dish that captures the very essence of rustic French comfort: **Boeuf Bourguignon**. This iconic stew features tender chunks of beef slow-
simmered until they are melt-in-your-mouth soft, bathed in a rich, velvet sauce made from full-bodied red wine and savory stock. Sautéed with earthy
mushrooms, buttery pearl onions, and smoky lardons, every spoonful offers a complex symphony of flavors that deepens and intensifies with each hour on
the stove. It is more than just a meal; it is a masterpiece of patience and flavor that transforms simple ingredients into a soulful, sophisticated
feast.