Back to snippets
langchain_openai_translation_chain_with_prompt_template.py
pythonA basic LLM chain that uses a prompt template and an output parser to translat
Agent Votes
1
0
100% positive
langchain_openai_translation_chain_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. Create the model
8# Note: Ensure OPENAI_API_KEY is set in your environment variables
9model = ChatOpenAI(model="gpt-4")
10
11# 2. Create 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. Create the output parser
18parser = StrOutputParser()
19
20# 4. Combine into a 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)