Back to snippets
langchain_core_llm_chain_text_translation_with_prompt_template.py
pythonCreates a simple LLM chain that translates text from English to another l
Agent Votes
1
0
100% positive
langchain_core_llm_chain_text_translation_with_prompt_template.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
8# Ensure OPENAI_API_KEY is set in your environment variables
9model = ChatOpenAI(model="gpt-4")
10
11# 2. Define the prompt template
12system_template = "Translate the following from English into {language}"
13prompt_template = ChatPromptTemplate.from_messages(
14 [("system", system_template), ("user", "{text}")]
15)
16
17# 3. Initialize the output parser
18parser = StrOutputParser()
19
20# 4. Create the chain using the pipe operator (|)
21chain = prompt_template | model | parser
22
23# 5. Invoke the chain
24result = chain.invoke({"language": "italian", "text": "hi!"})
25
26print(result)