LangChain Expression Language (LCEL) (phần 7)

Ví dụ xích phức tạp

Trong khi joke generator đơn giản minh họa sử dụng LCEL cơ bản, các ứng dụng thế giới thực điển hình yêu
cầu xử lí dữ liệu tinh vi hơn. Hãy khám phá các mô hình tiên tiến sử dụng một ví dụ khởi tạo và phân tích
story.
Trong ví dụ này, chúng ta sẽ xây dựng một dòng làm việc nhiều giai đoạn cái minh họa làm cách nào:
1. Khởi tạo nội dung với một lời gọi LLM
2. Cung cấp nội dung đó vào một lời gọi LLM thứ hai.
3. Bảo lưu và chuyển dạng dữ liệu xuyên suốt xích.

from langchain_core.prompts import PromptTemplate
from langchain_google_genai import GoogleGenerativeAI
from langchain_core.output_parsers import StrOutputParser
# Initialize the model
llm = GoogleGenerativeAI(model=”gemini-1.5-pro”)
# First chain generates a story
story_prompt = PromptTemplate.from_template(“Write a short story about
{topic}”)
story_chain = story_prompt | llm | StrOutputParser()
# Second chain analyzes the story
analysis_prompt = PromptTemplate.from_template(
“Analyze the following story’s mood:\n{story}”
)
analysis_chain = analysis_prompt | llm | StrOutputParser()

Chúng ta có thể biên tập 2 xích này cùng với nhau. Cách tiếp cận đơn giản đầu tiên của chúng ta tạo dòng
ống story trực tiếp vào xích phân tích:

# Combine chains
story_with_analysis = story_chain | analysis_chain
# Run the combined chain
story_analysis = story_with_analysis.invoke({“topic”: “a rainy day”})
print(“\nAnalysis:”, story_analysis)

Tôi nhận một phân tích dài. Sau đây là nó bắt đầu như thế nào:

Analysis: The mood of the story is predominantly **calm, peaceful, and
subtly romantic.** There’s a sense of gentle melancholy brought on by the
rain and the quiet emptiness of the bookshop, but this is balanced by a
feeling of warmth and hope.

Chia sẻ