Các bộ phận và tích hợp nâng cao LangChain (phần 58)

LangChain Expression Language (LCEL) (tiếp tục)

Ví dụ 6: Xích nâng cao LCEL

from langchain.prompts import ChatPromptTemplate
from langchain.schema.runnable import RunnablePassthrough
from langchain.chat_models import ChatOpenAI
from langchain.schema.output_parser import StrOutputParser
# Define the prompt template
prompt_template = ChatPromptTemplate.from_template(

“Answer the question based on the context: {context_a} {context_b} Question: {question}”

)
# Initialize the model and output parser
model = ChatOpenAI()
output_parser = StrOutputParser()
# Build the chain
chain = (

{

“context_a”: lambda x: x[“retriever_a”],
“context_b”: lambda x: x[“retriever_b”],
“question”: RunnablePassthrough()

}

| prompt_template
| model
| output_parser

)
# Example inputs
inputs = {

“question”: “What are the benefits of using LangChain?”,
“retriever_a”: “LangChain enables modular workflows and easy integration with APIs.”,
“retriever_b”: “LangChain supports complex applications like question answering and chatbots.”

}
# Execute the chain
result = chain.invoke(inputs)
print(result)
Output:
LangChain offers benefits such as modular workflows, easy API integration, and support for building complex applications like chatbots and question-
answering systems.

Code này minh họa một xích LangChain Expression Language (LCE) cái kết hợp nhiều cái giành bối cảnh với
một mẫu prompt, một LLM, và một cái duyệt đầu ra để khởi tạo một trả lời bối cảnh cho một câu hỏi đã cho.
Xích lắp ghép động các bối cảnh từ 2 cái giành và xử lí chúng qua một dòng ống của các bộ phận.

Chia sẻ