2024-08-03 | givkashi
在當今世界,同時處理多個任務的能力對於開發人員來說是一項至關重要的技能,尤其是在使用語言模型時。在這篇文章中,我們將逐步使用 LangChain 和 OpenAI 的 GPT-4 模型建立非同步翻譯服務。這是同時發送請求並提高應用程式效能的方法之一。
先決條件
您可以使用 pip 安裝所需的庫:
!pip install -q -U langchain langchain-openai langchain_community
程式碼
以下是建立非同步翻譯服務的完整程式碼。該服務獲取英語句子列表並將其同時翻譯成法語。
import asyncio
from langchain_openai import ChatOpenAI
from langchain.prompts import PromptTemplate
from langchain_core.runnables import RunnableSequence
# Define your LangChain components
llm = ChatOpenAI(model_name='openai/gpt-4o-mini')
template = "Translate the following English text to French: {text}"
prompt = PromptTemplate(template=template, input_variables=["text"])
# Combine them into a RunnableSequence
chain = RunnableSequence(first=prompt, last=llm)
# Define an async function to run the chain
async def run_chain(text):
return await chain.ainvoke({"text": text})
# Define a function to run multiple chains concurrently
async def run_multiple_chains(texts):
tasks = [run_chain(text) for text in texts]
results = await asyncio.gather(*tasks)
return results
# List of texts to process
texts = [
"Hello, how are you?",
"What is your name?",
"Where are you from?",
"What do you do?"
]
# Run the chains concurrently
results = asyncio.run(run_multiple_chains(texts))
# Print the results
for result in results:
print(result)
解釋
- LangChain 組件:
- ChatOpenAI:我們
ChatOpenAI
從 LangChain 初始化模型,指定 GPT-4 模型。 - PromptTemplate:我們建立一個用於將英文文字翻譯成法文的提示範本。
- RunnableSequence:我們將提示和模型組合成一個可以執行的序列。
2. 非同步執行:
- run_chain:此非同步函數針對單一文字輸入運行鏈。
- run_multiple_chains:此函數採用文字列表,並
run_chain
使用 為每個文字同時執行asyncio.gather
。
3. 輸入文字:我們定義要翻譯的英文句子清單。
4. 執行和輸出:我們同時執行鏈並列印結果。
輸出
運行程式碼後,將列印輸入文字的翻譯。以下是沒有元資料的結果:
Bonjour, comment ça va ?
Quel est votre nom ?
D'où viens-tu ? (informal) or D'où venez-vous ? (formal)
Que faites-vous ?
結論
在這篇文章中,我們使用 LangChain 和 OpenAI 的 GPT-4 模型建立了一個非同步翻譯服務。這種方法允許我們同時處理多個翻譯請求,使其高效且可擴展。透過利用LangChain強大的工具和OpenAI的先進模型,您可以輕鬆建立複雜的語言處理應用程式。