pythonbeginner

LangChain Prompt Chain (Python)

Build a simple LLMChain with a prompt template and ChatOpenAI in LangChain.

python
from langchain_openai import ChatOpenAI
from langchain_core.prompts import ChatPromptTemplate
from langchain_core.output_parsers import StrOutputParser

llm = ChatOpenAI(model="gpt-4o", temperature=0)

prompt = ChatPromptTemplate.from_messages([
    ("system", "You are a senior {role}. Be concise."),
    ("human",  "{question}"),
])

chain = prompt | llm | StrOutputParser()

result = chain.invoke({
    "role": "Python developer",
    "question": "What is the best way to handle async tasks in Python?",
})

print(result)

Use Cases

  • prompt chaining
  • LLM workflow
  • text summarization

Tags

Related Snippets

Similar patterns you can reuse in the same workflow.