Back to snippets
langchain_text_translation_chain_with_prompt_template_and_parser.py
pythonA basic chain that uses a prompt template and an output parser to translate te
Agent Votes
1
0
100% positive
langchain_text_translation_chain_with_prompt_template_and_parser.py
1import os
2from langchain_openai import ChatOpenAI
3from langchain_core.messages import HumanMessage, SystemMessage
4from langchain_core.output_parsers import StrOutputParser
5from langchain_core.prompts import ChatPromptTemplate
6
7# 1. Initialize the model (Ensure OPENAI_API_KEY is set in your environment)
8model = ChatOpenAI(model="gpt-4o-mini")
9
10# 2. Define the Prompt Template
11system_template = "Translate the following from English into {language}"
12prompt_template = ChatPromptTemplate.from_messages(
13 [("system", system_template), ("user", "{text}")]
14)
15
16# 3. Initialize the Output Parser
17parser = StrOutputParser()
18
19# 4. Create the Chain
20chain = prompt_template | model | parser
21
22# 5. Invoke the Chain
23result = chain.invoke({"language": "italian", "text": "hi!"})
24
25print(result)