Xây dựng móc xích đầu tiên của bạn
Sau đây là một ví dụ đơn giản để minh họa khả năng của LangChain:
from langchain.chains import LLMChain
from langchain.prompts import PromptTemplate
from langchain_openai import OpenAI
# Initialize the language model
llm = OpenAI(temperature=0.7)
# Create a prompt template
prompt = PromptTemplate(
input_variables=[“topic”],
template=”Write a brief, engaging paragraph about {topic}”
)
# Create the chain
chain = llm | prompt
# Run the chain
result = chain.invoke([“artificial intelligence”])
print(result)
Output:
{‘topic’: [‘artificial intelligence’], ‘text’: ‘\n\nArtificial intelligence, also known as AI, is a rapidly growing field that is revolutionizing the way we live, work, and interact with technology. It is the development of computer systems that can perform tasks that normally require human intelligence, such as problem-solving and decision-making. AI is already being used in various industries, from self-driving cars to personalized recommendations on streaming services. While some may fear the
rise of AI, it has the potential to greatly enhance our lives and improve efficiency in many areas. The possibilities for artificial intelligence are endless, and the future is full of exciting developments in this cutting-
edge field.’}
Phương thức chain.invoke(), khi sử dụng với “LLMChain” và “PromptTemplate” giống cái này, trả về một dictionary nơi
key là tên biến đầu ra từ mẫu prompt (trong trường hợp này, “text”). Đầu ra được thể hiện bao gồm biến đầu vào “topic”
cũng trong dictionary, cái không phải là cấu trúc đầu ra tiêu chuẩn cho móc xích cơ bản này.
