Các dạng móc xích LangChain (phần 7)

Định tuyến bằng tương tự ngữ nghĩa

Đôi khi, định tuyến dựa trên các mẫu định nghĩa trước có thể là không đủ. Bạn có thể định tuyến các truy vấn dựa
trên tương tự ngữ nghĩa sử dụng các embeddings và tương tự cosine.

from langchain.utils.math import cosine_similarity
from langchain_core.output_parsers import StrOutputParser
from langchain_openai import AzureOpenAIEmbeddings
# Example templates for routing by similarity
physics_template = “””You are a smart physics professor, great at answering questions about physics concisely.
When you don’t know the answer, admit that you don’t know.”””
math_template = “””You are a mathematician. You are great at breaking down complex problems and explaining step-by-step.”””
# Embed the templates for comparison
embeddings = AzureOpenAIEmbeddings(model=text-embedding-ada-002″)
prompt_templates = [physics_template, math_template]
prompt_embeddings = embeddings.embed_documents(prompt_templates)
# Function to route based on similarity
def prompt_router(input):

query_embedding = embeddings.embed_query(input[“query”])
similarity = cosine_similarity([query_embedding], prompt_embeddings)[0]
most_similar = prompt_templates[similarity.argmax()]
print(“Using MATH” if most_similar == math_template else “Using PHYSICS”)
return PromptTemplate.from_template(most_similar)

# Creating the chain
from langchain_core.runnables import RunnableLambda, RunnablePassthrough
chain = (

{“query”: RunnablePassthrough()}
| RunnableLambda(prompt_router)
| llm
| StrOutputParser()

)
Test the chain
print(chain.invoke(“What’s a black hole”))
Using PHYSICS
?
A black hole is a region in space where the gravitational force is so strong that not even light can escape from it. This occurs when a massive star collapses
print(chain.invoke(“What is chain rule in differentiation?”))
Using MATH
The chain rule in differentiation is a method used to find the derivative of a function that is composed of two or more functions.In other words, if f(x) = g(h(x)), then the derivative of f(x) is equal to g'(h(x)) * h'(x).

Code thực thi một hệ thống định tuyến thông minh sử dụng tương tự các embeddings và cosine. Nó chuyển đổi các truy
vấn người dùng thành các embeddings, so sánh chúng với các mẫu nhúng trước sử dụng tương tự cosine, và định tuyến
tới mẫu chuyên gia phù hợp nhất (math hay physics). Cái này đảm bảo các câu hỏi được trả lời bởi hồ sơ cá nhân AI
phù hợp nhất.

Chia sẻ