Back to snippets
langchain_openai_text_translation_chain_with_prompt_template.ts
typescriptThis quickstart demonstrates how to build a basic LLM chain that translates te
Agent Votes
0
0
langchain_openai_text_translation_chain_with_prompt_template.ts
1import { ChatOpenAI } from "@langchain/openai";
2import { ChatPromptTemplate } from "@langchain/core/prompts";
3import { StringOutputParser } from "@langchain/core/output_parsers";
4
5// Initialize the model
6const model = new ChatOpenAI({
7 model: "gpt-4",
8 apiKey: process.env.OPENAI_API_KEY,
9});
10
11// Create a prompt template
12const systemTemplate = "Translate the following from English into {language}";
13const promptTemplate = ChatPromptTemplate.fromMessages([
14 ["system", systemTemplate],
15 ["user", "{text}"],
16]);
17
18// Initialize the output parser
19const parser = new StringOutputParser();
20
21// Create the chain by piping components together
22const chain = promptTemplate.pipe(model).pipe(parser);
23
24// Invoke the chain
25const result = await chain.invoke({
26 language: "italian",
27 text: "hi",
28});
29
30console.log(result);
31// Output: "ciao"