Các công cụ và gọi hàm LangChain (phần 9)

Gọi hàm: nâng cao khả năng LLM (tiếp tục)

Thực thi gọi hàm trong LangChain

1. Sử dụng hệ thống công cụ của LangChain: Bạn có thể gói các hàm của bạn như các công cụ LangChain và sử dụng chúng
với các cơ quan.

from langchain.agents import initialize_agent, Tool
# from langchain.llms import OpenAI
def get_weather(location):
return f”The weather in {location} is Summer.”
tools = [

Tool(

name=”WeatherTool”,
func=get_weather,
description=”Useful for getting weather information for a specific location”

)

]
llm = AzureOpenAI(deployment_name=”<Azure deployment name>”, model_name=”<Model name>”)
agent = initialize_agent(tools, llm, agent=”zero-shot-react-description”, verbose=True)
agent.run(“What’s the weather like in India?”)

Code này thiết lập một cơ quan LangChain với một công cụ weather. Cơ quan, hỗ trợ bởi AzureOpenAI, có thể xử lí
một truy vấn về weather trong một vị trí cụ thể bằng cách sử dụng hàm get_weather được định nghĩa. Khi được hỏi về
weather của London, nó sẽ khởi động công cụ để giành và khởi tạo tiềm tàng một trả lời liên quan đến weather.
2. Các kĩ thuật gọi hàm nâng cao
Các lời gọi hàm móc xích:
Thực thi các dòng làm việc phức tạp bằng cách móc xích nhiều lời gọi hàm cùng với nhau.

from langchain.prompts import ChatPromptTemplate
from langchain.chains import LLMChain
llm = AzureOpenAI(deployment_name=”<Azure deployment name>”, model_name=”<Model name>”)
prompt = ChatPromptTemplate.from_template(
“Given the weather: {weather}, suggest an appropriate outfit.”
)
weather_chain = LLMChain(llm=llm, prompt=prompt)
outfit_chain = LLMChain(llm=llm, prompt=ChatPromptTemplate.from_template(
“Describe the outfit: {outfit}”
))
def get_outfit_recommendation(location):

weather = get_weather(location)
outfit = weather_chain.run(weather=weather)
return outfit_chain.run(outfit=outfit)

result = get_outfit_recommendation(“India”)
result
output:
Bright colors and bold patterns are popular in Indian fashion, so don’t be afraid to embrace them!

Xích đầu tiên (weather_chain) quyết định các điều kiện weather đã cho trang phục, và xích thứ hai (outfit_chain) mô
tả trang phục trong chi tiết hơn. Hàm get_outfit_recommendation phối hợp quá trình này bằng cách lấy dữ liệu weather
, sau đó khởi tạo và tinh chỉnh một gợi ý trang phục.

Chia sẻ