Các dạng Agents (tiếp tục)
4. Các Agents tùy chỉnh
Thiết kế cho các trường hợp sử dụng cụ thể, cho phép các tương tác logic và công cụ tùy chỉnh.
Các agents tùy chỉnh trong LangChain được thiết kế để xử lí các trường hợp sử dụng cụ thể bằng cách cung
cấp tính linh động cho các tương tác logic và công cụ tùy chỉnh. Các agents này không tích hợp trước
, các agents chung giống những cái đó tạo sử dụng các hàm tạo agent mặc định. Thay vào, chúng cho phép
bạn định nghĩa hành vi của bản thân bạn, các tương tác công cụ, và các quá trình ra quyết định dựa trên
bối cảnh ứng dụng của bạn.
from langchain.agents import initialize_agent, AgentType
from langchain.chat_models import ChatOpenAI
from langchain.tools import StructuredTool
from typing import Optional
from langchain.prompts import PromptTemplate
from langchain.schema import SystemMessage
# Define the currency conversion tool
def currency_conversion_tool(amount: float, from_currency: str, to_currency: str) -> Optional[float]:“””Convert between USD, EUR and INR currencies”””
rates = {
“USD-INR”: 83.0,
“EUR-USD”: 1.1,
“INR-USD”: 0.012,
“USD-EUR”: 0.9}
pair = f”{from_currency}-{to_currency}”
if pair in rates:return amount * rates[pair]
elif f”{to_currency}-{from_currency}” in rates:
return amount / rates[f”{to_currency}-{from_currency}”]
return None
# Create a LangChain tool with better description
currency_tool = StructuredTool.from_function(func=currency_conversion_tool,
name=”currency_converter”,
description=”””Convert amounts between currencies (USD, EUR, INR).
Args:amount (float): The amount to convert
from_currency (str): Source currency code (USD, EUR, or INR)
to_currency (str): Target currency code (USD, EUR, or INR)Returns:
float: The converted amount
“””
)
# Initialize the LLM
llm = AzureOpenAI(deployment_name=”<LLM Deployment Name>”, model_name=”<Model Name>”)
# Create system message for the agent
system_message = “””You are a helpful currency conversion assistant.
When given a currency conversion request:
1. Extract the amount, source currency, and target currency
2. Use the currency_converter tool to perform the conversion
3. Always respond with the converted amount in a clear format
4. If there’s an error, explain what went wrong
Format your response as:
{amount} {from_currency} = {converted_amount} {to_currency}”””
# Create the agent with custom configuration
agent = initialize_agent(tools=[currency_tool],
llm=llm,
agent=AgentType.STRUCTURED_CHAT_ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
system_message=system_message,
handle_parsing_errors=True)
# Example usage with error handling
def convert_currency(query: str) -> str:try:
result = agent.run(query)
return result if result else “Sorry, couldn’t perform the conversion. Please check the currency codes.”except Exception as e:
return f”Error performing conversion: {str(e)}”
# Test the conversion
query = “Convert 100 EUR to USD”
print(convert_currency(query))
> Finished chain.
110.00 USD
Code này minh họa làm cách nào sử dụng các công cụ và agents của LangChain để xây dựng một trợ lí chuyển
đổi tiền tệ. Nó định nghĩa một công cụ chuyển đổi tiền tệ tùy chỉnh, khởi tạo một agent với một dạng chat
có cấu trúc, và sử dụng một thông điệp hệ thống để hướng dẫn agent trong xử lí các truy vấn như chuyển
đổi 100 EUR sang USD.
