(Nhấp vào hình ảnh trên để xem video bài học này)
Siêu nhận thức trong các Tác Nhân AI
Chào mừng bạn đến với bài học về siêu nhận thức trong các tác nhân AI! Chương này được thiết kế dành cho người mới bắt đầu tò mò về cách các tác nhân AI có thể suy nghĩ về chính quá trình suy nghĩ của họ. Khi kết thúc bài học này, bạn sẽ hiểu các khái niệm chính và được trang bị các ví dụ thực tiễn để áp dụng siêu nhận thức trong thiết kế tác nhân AI.
Sau khi hoàn thành bài học này, bạn sẽ có khả năng:
Siêu nhận thức đề cập đến các quá trình nhận thức bậc cao liên quan đến việc suy nghĩ về chính suy nghĩ của bản thân. Đối với các tác nhân AI, điều này có nghĩa là có khả năng đánh giá và điều chỉnh hành động dựa trên sự tự nhận thức và kinh nghiệm trong quá khứ. Siêu nhận thức, hay “suy nghĩ về việc suy nghĩ,” là một khái niệm quan trọng trong phát triển các hệ thống AI có tính tác nhân. Nó liên quan đến việc các hệ thống AI nhận thức được các quá trình nội tại của chính mình và có khả năng giám sát, điều chỉnh, và thích nghi hành vi của mình cho phù hợp. Giống như khi chúng ta đọc tình hình hoặc nhìn nhận một vấn đề. Sự tự nhận thức này có thể giúp các hệ thống AI đưa ra quyết định tốt hơn, nhận diện lỗi, và cải thiện hiệu suất theo thời gian — liên kết trở lại với kiểm tra Turing và cuộc tranh luận liệu AI có sẽ chiếm ưu thế.
Trong bối cảnh các hệ thống AI có tính tác nhân, siêu nhận thức có thể giúp giải quyết một số thách thức, chẳng hạn như:
Siêu nhận thức, hay “suy nghĩ về việc suy nghĩ,” là một quá trình nhận thức bậc cao bao gồm sự tự nhận thức và tự điều chỉnh các quá trình nhận thức của chính mình. Trong lĩnh vực AI, siêu nhận thức giúp các tác nhân đánh giá và điều chỉnh chiến lược và hành động, dẫn đến khả năng giải quyết vấn đề và ra quyết định được cải thiện. Bằng việc hiểu siêu nhận thức, bạn có thể thiết kế các tác nhân AI không chỉ thông minh hơn mà còn linh hoạt và hiệu quả hơn. Trong siêu nhận thức thật sự, bạn sẽ thấy AI lý luận rõ ràng về chính lập luận của nó.
Ví dụ: “Tôi ưu tiên các chuyến bay rẻ hơn vì… Có thể tôi đang bỏ lỡ các chuyến bay thẳng, vậy nên tôi sẽ kiểm tra lại.” Theo dõi cách hoặc lý do tại sao nó chọn một tuyến đường nhất định.
Siêu nhận thức đóng vai trò then chốt trong thiết kế tác nhân AI vì nhiều lý do:

Trước khi đi vào các quá trình siêu nhận thức, điều cần thiết là hiểu các thành phần cơ bản của một tác nhân AI. Một tác nhân AI điển hình bao gồm:
Các thành phần này hoạt động cùng nhau để tạo thành một “đơn vị chuyên môn” có thể thực hiện các nhiệm vụ cụ thể.
Ví dụ: Hãy xem xét một đại lý du lịch, một dịch vụ tác nhân không chỉ lập kế hoạch kỳ nghỉ mà còn điều chỉnh hành trình dựa trên dữ liệu thời gian thực và kinh nghiệm hành trình khách hàng trước.
Hãy tưởng tượng bạn đang thiết kế một dịch vụ đại lý du lịch được hỗ trợ bởi AI. Tác nhân này, “Đại lý Du lịch,” hỗ trợ người dùng lên kế hoạch kỳ nghỉ. Để tích hợp siêu nhận thức, Đại lý Du lịch cần đánh giá và điều chỉnh hành động dựa trên tự nhận thức và kinh nghiệm trong quá khứ. Dưới đây là cách siêu nhận thức có thể đóng vai trò:
Nhiệm vụ hiện tại là giúp người dùng lên kế hoạch chuyến đi đến Paris.
Đại lý Du lịch sử dụng siêu nhận thức để đánh giá hiệu suất và rút kinh nghiệm từ quá khứ. Ví dụ:
Dưới đây là ví dụ đơn giản về mã của Đại lý Du lịch khi tích hợp siêu nhận thức:
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
self.experience_data = []
def gather_preferences(self, preferences):
self.user_preferences = preferences
def retrieve_information(self):
# Tìm kiếm chuyến bay, khách sạn và điểm tham quan dựa trên sở thích
flights = search_flights(self.user_preferences)
hotels = search_hotels(self.user_preferences)
attractions = search_attractions(self.user_preferences)
return flights, hotels, attractions
def generate_recommendations(self):
flights, hotels, attractions = self.retrieve_information()
itinerary = create_itinerary(flights, hotels, attractions)
return itinerary
def adjust_based_on_feedback(self, feedback):
self.experience_data.append(feedback)
# Phân tích phản hồi và điều chỉnh các đề xuất trong tương lai
self.user_preferences = adjust_preferences(self.user_preferences, feedback)
# Ví dụ sử dụng
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
itinerary = travel_agent.generate_recommendations()
print("Suggested Itinerary:", itinerary)
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
travel_agent.adjust_based_on_feedback(feedback)
Bằng việc áp dụng siêu nhận thức, Đại lý Du lịch có thể cung cấp các khuyến nghị du lịch cá nhân hóa và chính xác hơn, nâng cao trải nghiệm tổng thể của người dùng.
Lập kế hoạch là thành phần quan trọng trong hành vi của tác nhân AI. Nó liên quan đến việc phác thảo các bước cần thiết để đạt được mục tiêu, cân nhắc trạng thái hiện tại, tài nguyên và các chướng ngại có thể gặp.
Ví dụ: Dưới đây là các bước Đại lý Du lịch cần thực hiện để hỗ trợ người dùng lập kế hoạch chuyến đi hiệu quả:
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
self.experience_data = []
def gather_preferences(self, preferences):
self.user_preferences = preferences
def retrieve_information(self):
flights = search_flights(self.user_preferences)
hotels = search_hotels(self.user_preferences)
attractions = search_attractions(self.user_preferences)
return flights, hotels, attractions
def generate_recommendations(self):
flights, hotels, attractions = self.retrieve_information()
itinerary = create_itinerary(flights, hotels, attractions)
return itinerary
def adjust_based_on_feedback(self, feedback):
self.experience_data.append(feedback)
self.user_preferences = adjust_preferences(self.user_preferences, feedback)
# Ví dụ sử dụng trong một yêu cầu booing
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
itinerary = travel_agent.generate_recommendations()
print("Suggested Itinerary:", itinerary)
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
travel_agent.adjust_based_on_feedback(feedback)
Trước tiên, hãy bắt đầu bằng việc hiểu sự khác biệt giữa Công cụ RAG và Tải ngữ cảnh dự phòng

RAG kết hợp hệ thống truy xuất với mô hình sinh. Khi có truy vấn, hệ thống truy xuất lấy các tài liệu hoặc dữ liệu liên quan từ nguồn bên ngoài, và thông tin này được dùng để bổ sung đầu vào cho mô hình sinh. Điều này giúp mô hình tạo ra các phản hồi chính xác và phù hợp với ngữ cảnh hơn.
Trong hệ thống RAG, tác nhân truy xuất thông tin liên quan từ cơ sở tri thức và sử dụng nó để tạo phản hồi hoặc hành động thích hợp.
Cách tiếp cận RAG Sửa lỗi tập trung vào việc sử dụng kỹ thuật RAG để sửa các lỗi và nâng cao độ chính xác của các tác nhân AI. Điều này bao gồm:
Hãy xem xét một tác nhân tìm kiếm lấy thông tin từ web để trả lời truy vấn người dùng. Cách tiếp cận RAG Sửa lỗi có thể bao gồm:
RAG Sửa lỗi (Retrieval-Augmented Generation) tăng cường khả năng truy xuất và tạo thông tin của AI trong khi sửa các sai lệch. Hãy xem Đại lý Du lịch có thể dùng cách tiếp cận RAG Sửa lỗi để cung cấp các đề xuất du lịch chính xác và phù hợp hơn như thế nào.
Việc này bao gồm:
Ví dụ:
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
Ví dụ:
flights = search_flights(preferences)
hotels = search_hotels(preferences)
attractions = search_attractions(preferences)
Ví dụ:
itinerary = create_itinerary(flights, hotels, attractions)
print("Suggested Itinerary:", itinerary)
Ví dụ:
feedback = {
"liked": ["Louvre Museum"],
"disliked": ["Eiffel Tower (too crowded)"]
}
Ví dụ:
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
Ví dụ:
new_attractions = search_attractions(preferences)
new_itinerary = create_itinerary(flights, hotels, new_attractions)
print("Updated Itinerary:", new_itinerary)
Ví dụ:
def adjust_preferences(preferences, feedback):
if "liked" in feedback:
preferences["favorites"] = feedback["liked"]
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
return preferences
preferences = adjust_preferences(preferences, feedback)
Dưới đây là ví dụ mã Python đơn giản tích hợp cách tiếp cận RAG Sửa lỗi trong Đại lý Du lịch:
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
self.experience_data = []
def gather_preferences(self, preferences):
self.user_preferences = preferences
def retrieve_information(self):
flights = search_flights(self.user_preferences)
hotels = search_hotels(self.user_preferences)
attractions = search_attractions(self.user_preferences)
return flights, hotels, attractions
def generate_recommendations(self):
flights, hotels, attractions = self.retrieve_information()
itinerary = create_itinerary(flights, hotels, attractions)
return itinerary
def adjust_based_on_feedback(self, feedback):
self.experience_data.append(feedback)
self.user_preferences = adjust_preferences(self.user_preferences, feedback)
new_itinerary = self.generate_recommendations()
return new_itinerary
# Ví dụ sử dụng
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
itinerary = travel_agent.generate_recommendations()
print("Suggested Itinerary:", itinerary)
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
new_itinerary = travel_agent.adjust_based_on_feedback(feedback)
print("Updated Itinerary:", new_itinerary)
Tải Trước Ngữ Cảnh liên quan đến việc tải thông tin ngữ cảnh hoặc thông tin nền liên quan vào mô hình trước khi xử lý một truy vấn. Điều này có nghĩa là mô hình có quyền truy cập vào thông tin này ngay từ đầu, giúp nó tạo ra các phản hồi có cơ sở hơn mà không cần phải truy xuất thêm dữ liệu trong quá trình xử lý.
Dưới đây là ví dụ đơn giản về cách tải trước ngữ cảnh có thể trông như thế nào cho ứng dụng đại lý du lịch viết bằng Python:
class TravelAgent:
def __init__(self):
# Tải trước các điểm đến phổ biến và thông tin của chúng
self.context = {
"Paris": {"country": "France", "currency": "Euro", "language": "French", "attractions": ["Eiffel Tower", "Louvre Museum"]},
"Tokyo": {"country": "Japan", "currency": "Yen", "language": "Japanese", "attractions": ["Tokyo Tower", "Shibuya Crossing"]},
"New York": {"country": "USA", "currency": "Dollar", "language": "English", "attractions": ["Statue of Liberty", "Times Square"]},
"Sydney": {"country": "Australia", "currency": "Dollar", "language": "English", "attractions": ["Sydney Opera House", "Bondi Beach"]}
}
def get_destination_info(self, destination):
# Lấy thông tin điểm đến từ ngữ cảnh đã tải trước
info = self.context.get(destination)
if info:
return f"{destination}:\nCountry: {info['country']}\nCurrency: {info['currency']}\nLanguage: {info['language']}\nAttractions: {', '.join(info['attractions'])}"
else:
return f"Sorry, we don't have information on {destination}."
# Ví dụ sử dụng
travel_agent = TravelAgent()
print(travel_agent.get_destination_info("Paris"))
print(travel_agent.get_destination_info("Tokyo"))
Khởi tạo (phương thức __init__): Lớp TravelAgent tải trước một từ điển chứa thông tin về các điểm đến phổ biến như Paris, Tokyo, New York và Sydney. Từ điển này bao gồm các chi tiết như quốc gia, tiền tệ, ngôn ngữ và các điểm thu hút chính của mỗi điểm đến.
Lấy Thông Tin (phương thức get_destination_info): Khi người dùng truy vấn về một điểm đến cụ thể, phương thức get_destination_info sẽ truy xuất thông tin liên quan từ từ điển ngữ cảnh đã tải trước.
Bằng cách tải trước ngữ cảnh, ứng dụng đại lý du lịch có thể phản hồi nhanh các truy vấn của người dùng mà không cần phải truy xuất thông tin này từ nguồn bên ngoài trong thời gian thực. Điều này giúp ứng dụng trở nên hiệu quả và phản hồi nhanh hơn.
Khởi tạo một kế hoạch với một mục tiêu liên quan đến việc bắt đầu với một mục tiêu rõ ràng hoặc kết quả dự kiến trong tâm trí. Bằng cách xác định mục tiêu này ngay từ đầu, mô hình có thể sử dụng nó như một nguyên tắc hướng dẫn trong suốt quá trình lặp lại. Điều này giúp đảm bảo mỗi vòng lặp tiến gần hơn đến việc đạt được kết quả mong muốn, làm cho quá trình hiệu quả và tập trung hơn.
Dưới đây là ví dụ về cách bạn có thể khởi tạo một kế hoạch du lịch với một mục tiêu trước khi lặp lại cho một đại lý du lịch viết bằng Python:
Một đại lý du lịch muốn lên kế hoạch kỳ nghỉ tùy chỉnh cho khách hàng. Mục tiêu là tạo ra một lịch trình du lịch tối đa hóa sự hài lòng của khách hàng dựa trên sở thích và ngân sách của họ.
class TravelAgent:
def __init__(self, destinations):
self.destinations = destinations
def bootstrap_plan(self, preferences, budget):
plan = []
total_cost = 0
for destination in self.destinations:
if total_cost + destination['cost'] <= budget and self.match_preferences(destination, preferences):
plan.append(destination)
total_cost += destination['cost']
return plan
def match_preferences(self, destination, preferences):
for key, value in preferences.items():
if destination.get(key) != value:
return False
return True
def iterate_plan(self, plan, preferences, budget):
for i in range(len(plan)):
for destination in self.destinations:
if destination not in plan and self.match_preferences(destination, preferences) and self.calculate_cost(plan, destination) <= budget:
plan[i] = destination
break
return plan
def calculate_cost(self, plan, new_destination):
return sum(destination['cost'] for destination in plan) + new_destination['cost']
# Ví dụ sử dụng
destinations = [
{"name": "Paris", "cost": 1000, "activity": "sightseeing"},
{"name": "Tokyo", "cost": 1200, "activity": "shopping"},
{"name": "New York", "cost": 900, "activity": "sightseeing"},
{"name": "Sydney", "cost": 1100, "activity": "beach"},
]
preferences = {"activity": "sightseeing"}
budget = 2000
travel_agent = TravelAgent(destinations)
initial_plan = travel_agent.bootstrap_plan(preferences, budget)
print("Initial Plan:", initial_plan)
refined_plan = travel_agent.iterate_plan(initial_plan, preferences, budget)
print("Refined Plan:", refined_plan)
Khởi tạo (phương thức __init__): Lớp TravelAgent được khởi tạo với một danh sách các điểm đến tiềm năng, mỗi điểm có các thuộc tính như tên, chi phí và loại hoạt động.
Khởi Tạo Kế Hoạch (phương thức bootstrap_plan): Phương thức này tạo một kế hoạch du lịch ban đầu dựa trên sở thích và ngân sách của khách hàng. Nó lặp qua danh sách điểm đến và thêm chúng vào kế hoạch nếu chúng phù hợp với sở thích của khách hàng và phù hợp trong ngân sách.
So khớp Sở Thích (phương thức match_preferences): Phương thức này kiểm tra xem điểm đến có phù hợp với sở thích của khách hàng hay không.
Lặp lại Kế Hoạch (phương thức iterate_plan): Phương thức này tinh chỉnh kế hoạch ban đầu bằng cách cố gắng thay thế từng điểm đến trong kế hoạch bằng một lựa chọn phù hợp hơn, xem xét sở thích và giới hạn ngân sách của khách hàng.
Tính Toán Chi Phí (phương thức calculate_cost): Phương thức này tính tổng chi phí của kế hoạch hiện tại, bao gồm cả điểm đến mới tiềm năng.
Bằng cách khởi tạo kế hoạch với mục tiêu rõ ràng (ví dụ: tối đa hóa sự hài lòng của khách hàng) và lặp lại để tinh chỉnh kế hoạch, đại lý du lịch có thể tạo ra lịch trình du lịch tùy chỉnh và tối ưu cho khách hàng. Phương pháp này đảm bảo kế hoạch du lịch phù hợp với sở thích và ngân sách của khách hàng ngay từ đầu và cải thiện qua mỗi vòng lặp.
Các Mô Hình Ngôn Ngữ Lớn (LLMs) có thể được sử dụng để xếp hạng lại và chấm điểm bằng cách đánh giá sự liên quan và chất lượng của các tài liệu được truy xuất hoặc các phản hồi được tạo ra. Dưới đây là cách nó hoạt động:
Truy xuất: Bước truy xuất ban đầu lấy một tập hợp các tài liệu hoặc phản hồi ứng viên dựa trên truy vấn.
Xếp hạng lại: LLM đánh giá các ứng viên này và sắp xếp lại chúng dựa trên mức độ liên quan và chất lượng. Bước này đảm bảo thông tin liên quan và chất lượng nhất được hiển thị đầu tiên.
Chấm điểm: LLM gán điểm cho từng ứng viên, phản ánh mức độ liên quan và chất lượng của chúng. Điều này giúp chọn ra phản hồi hoặc tài liệu tốt nhất cho người dùng.
Nhờ sử dụng LLM để xếp hạng lại và chấm điểm, hệ thống có thể cung cấp thông tin chính xác hơn và liên quan hơn theo ngữ cảnh, cải thiện trải nghiệm người dùng tổng thể.
Dưới đây là ví dụ về cách một đại lý du lịch có thể sử dụng Mô Hình Ngôn Ngữ Lớn (LLM) để xếp hạng lại và chấm điểm các điểm đến du lịch dựa trên sở thích của người dùng bằng Python:
Một đại lý du lịch muốn giới thiệu các điểm đến du lịch tốt nhất cho khách hàng dựa trên sở thích của họ. LLM sẽ giúp xếp hạng lại và chấm điểm các điểm đến để đảm bảo các lựa chọn phù hợp nhất được trình bày.
Dưới đây là cách bạn có thể cập nhật ví dụ trước để sử dụng Dịch vụ Azure OpenAI:
import requests
import json
class TravelAgent:
def __init__(self, destinations):
self.destinations = destinations
def get_recommendations(self, preferences, api_key, endpoint):
# Tạo một prompt cho Azure OpenAI
prompt = self.generate_prompt(preferences)
# Định nghĩa header và payload cho yêu cầu
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
payload = {
"prompt": prompt,
"max_tokens": 150,
"temperature": 0.7
}
# Gọi API Azure OpenAI để lấy danh sách điểm đến được xếp hạng lại và chấm điểm
response = requests.post(endpoint, headers=headers, json=payload)
response_data = response.json()
# Trích xuất và trả về các đề xuất
recommendations = response_data['choices'][0]['text'].strip().split('\n')
return recommendations
def generate_prompt(self, preferences):
prompt = "Here are the travel destinations ranked and scored based on the following user preferences:\n"
for key, value in preferences.items():
prompt += f"{key}: {value}\n"
prompt += "\nDestinations:\n"
for destination in self.destinations:
prompt += f"- {destination['name']}: {destination['description']}\n"
return prompt
# Ví dụ sử dụng
destinations = [
{"name": "Paris", "description": "City of lights, known for its art, fashion, and culture."},
{"name": "Tokyo", "description": "Vibrant city, famous for its modernity and traditional temples."},
{"name": "New York", "description": "The city that never sleeps, with iconic landmarks and diverse culture."},
{"name": "Sydney", "description": "Beautiful harbour city, known for its opera house and stunning beaches."},
]
preferences = {"activity": "sightseeing", "culture": "diverse"}
api_key = 'your_azure_openai_api_key'
endpoint = 'https://your-endpoint.com/openai/deployments/your-deployment-name/completions?api-version=2022-12-01'
travel_agent = TravelAgent(destinations)
recommendations = travel_agent.get_recommendations(preferences, api_key, endpoint)
print("Recommended Destinations:")
for rec in recommendations:
print(rec)
Khởi tạo: Lớp TravelAgent được khởi tạo với danh sách các điểm đến du lịch tiềm năng, mỗi điểm có các thuộc tính như tên và mô tả.
Lấy Gợi Ý (get_recommendations method): Phương thức này tạo một prompt cho dịch vụ Azure OpenAI dựa trên sở thích của người dùng và thực hiện yêu cầu HTTP POST tới API Azure OpenAI để nhận các điểm đến đã được xếp hạng lại và chấm điểm.
Tạo Prompt (generate_prompt method): Phương thức này xây dựng một prompt cho Azure OpenAI, bao gồm sở thích của người dùng và danh sách điểm đến. Prompt này hướng dẫn mô hình xếp hạng lại và chấm điểm các điểm đến dựa trên các sở thích được cung cấp.
Gọi API: Thư viện requests được sử dụng để thực hiện yêu cầu HTTP POST tới điểm cuối API của Azure OpenAI. Phản hồi chứa các điểm đến đã được xếp hạng lại và chấm điểm.
Ví dụ Sử Dụng: Đại lý du lịch thu thập sở thích người dùng (ví dụ: quan tâm đến tham quan và văn hóa đa dạng) và sử dụng dịch vụ Azure OpenAI để lấy các gợi ý đã được xếp hạng lại và chấm điểm cho các điểm đến du lịch.
Hãy chắc chắn thay thế your_azure_openai_api_key bằng khóa API Azure OpenAI thực tế của bạn và https://your-endpoint.com/... bằng URL điểm cuối thực của triển khai Azure OpenAI của bạn.
Bằng cách sử dụng LLM để xếp hạng lại và chấm điểm, đại lý du lịch có thể cung cấp các đề xuất du lịch cá nhân hóa và liên quan hơn cho khách hàng, nâng cao trải nghiệm tổng thể của họ.
Retrieval-Augmented Generation (RAG) có thể vừa là một kỹ thuật đề xuất vừa là một công cụ trong phát triển các đại lý AI. Hiểu rõ sự khác biệt giữa hai cái này sẽ giúp bạn tận dụng RAG hiệu quả hơn trong dự án của mình.
Nó là gì?
Cách nó hoạt động:
Ví dụ trong Đại lý Du lịch:
Nó là gì?
Cách nó hoạt động:
Ví dụ trong Đại lý Du lịch:
| Khía cạnh | Kỹ thuật Đề xuất | Công cụ |
|---|---|---|
| Thủ công vs Tự động | Tạo prompt thủ công cho mỗi truy vấn. | Quá trình tự động cho truy xuất và tạo ra. |
| Kiểm soát | Cung cấp nhiều kiểm soát hơn đối với quá trình truy xuất. | Đơn giản hóa và tự động hóa truy xuất và tạo ra. |
| Linh hoạt | Cho phép tùy chỉnh prompt dựa trên nhu cầu cụ thể. | Hiệu quả hơn cho các triển khai quy mô lớn. |
| Phức tạp | Yêu cầu tạo và điều chỉnh prompt. | Dễ tích hợp trong kiến trúc đại lý AI. |
Ví dụ về Kỹ thuật Đề xuất:
def search_museums_in_paris():
prompt = "Find top museums in Paris"
search_results = search_web(prompt)
return search_results
museums = search_museums_in_paris()
print("Top Museums in Paris:", museums)
Ví dụ về Công cụ:
class Travel_Agent:
def __init__(self):
self.rag_tool = RAGTool()
def get_museums_in_paris(self):
user_input = "I want to visit museums in Paris."
response = self.rag_tool.retrieve_and_generate(user_input)
return response
travel_agent = Travel_Agent()
museums = travel_agent.get_museums_in_paris()
print("Top Museums in Paris:", museums)
Đánh giá mức độ liên quan là một khía cạnh then chốt trong hiệu suất của đại lý AI. Nó đảm bảo rằng thông tin được truy xuất và tạo ra bởi đại lý là phù hợp, chính xác và hữu ích cho người dùng. Hãy cùng khám phá cách đánh giá mức độ liên quan trong đại lý AI, bao gồm các ví dụ và kỹ thuật thực tế.
Ví dụ:
def relevance_score(item, query):
score = 0
if item['category'] in query['interests']:
score += 1
if item['price'] <= query['budget']:
score += 1
if item['location'] == query['destination']:
score += 1
return score
Ví dụ:
def filter_and_rank(items, query):
ranked_items = sorted(items, key=lambda item: relevance_score(item, query), reverse=True)
return ranked_items[:10] # Trả về 10 mục phù hợp hàng đầu
Ví dụ:
def process_query(query):
# Sử dụng NLP để trích xuất thông tin chính từ truy vấn của người dùng
processed_query = nlp(query)
return processed_query
Ví dụ:
def adjust_based_on_feedback(feedback, items):
for item in items:
if item['name'] in feedback['liked']:
item['relevance'] += 1
if item['name'] in feedback['disliked']:
item['relevance'] -= 1
return items
Dưới đây là ví dụ thực tế về cách Đại lý Du lịch có thể đánh giá mức độ liên quan của các đề xuất du lịch:
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
self.experience_data = []
def gather_preferences(self, preferences):
self.user_preferences = preferences
def retrieve_information(self):
flights = search_flights(self.user_preferences)
hotels = search_hotels(self.user_preferences)
attractions = search_attractions(self.user_preferences)
return flights, hotels, attractions
def generate_recommendations(self):
flights, hotels, attractions = self.retrieve_information()
ranked_hotels = self.filter_and_rank(hotels, self.user_preferences)
itinerary = create_itinerary(flights, ranked_hotels, attractions)
return itinerary
def filter_and_rank(self, items, query):
ranked_items = sorted(items, key=lambda item: self.relevance_score(item, query), reverse=True)
return ranked_items[:10] # Trả về 10 mục liên quan hàng đầu
def relevance_score(self, item, query):
score = 0
if item['category'] in query['interests']:
score += 1
if item['price'] <= query['budget']:
score += 1
if item['location'] == query['destination']:
score += 1
return score
def adjust_based_on_feedback(self, feedback, items):
for item in items:
if item['name'] in feedback['liked']:
item['relevance'] += 1
if item['name'] in feedback['disliked']:
item['relevance'] -= 1
return items
# Ví dụ sử dụng
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
itinerary = travel_agent.generate_recommendations()
print("Suggested Itinerary:", itinerary)
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
updated_items = travel_agent.adjust_based_on_feedback(feedback, itinerary['hotels'])
print("Updated Itinerary with Feedback:", updated_items)
Tìm kiếm có mục đích liên quan đến việc hiểu và diễn giải mục đích hoặc mục tiêu đằng sau truy vấn của người dùng để truy xuất và tạo ra thông tin phù hợp và hữu ích nhất. Cách tiếp cận này vượt ra ngoài việc chỉ khớp từ khóa và tập trung vào việc nắm bắt nhu cầu thực tế và ngữ cảnh của người dùng.
Hãy lấy Đại lý Du lịch làm ví dụ để xem cách tìm kiếm có mục đích có thể được triển khai.
Thu thập Sở thích Người dùng
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
Hiểu Ý định Người dùng
def identify_intent(query):
if "book" in query or "purchase" in query:
return "transactional"
elif "website" in query or "official" in query:
return "navigational"
else:
return "informational"
Nhận thức Ngữ cảnh
def analyze_context(query, user_history):
# Kết hợp truy vấn hiện tại với lịch sử người dùng để hiểu ngữ cảnh
context = {
"current_query": query,
"user_history": user_history
}
return context
Tìm kiếm và Cá nhân hóa Kết quả
def search_with_intent(query, preferences, user_history):
intent = identify_intent(query)
context = analyze_context(query, user_history)
if intent == "informational":
search_results = search_information(query, preferences)
elif intent == "navigational":
search_results = search_navigation(query)
elif intent == "transactional":
search_results = search_transaction(query, preferences)
personalized_results = personalize_results(search_results, user_history)
return personalized_results
def search_information(query, preferences):
# Ví dụ về logic tìm kiếm cho ý định thông tin
results = search_web(f"best {preferences['interests']} in {preferences['destination']}")
return results
def search_navigation(query):
# Ví dụ về logic tìm kiếm cho ý định điều hướng
results = search_web(query)
return results
def search_transaction(query, preferences):
# Ví dụ về logic tìm kiếm cho ý định giao dịch
results = search_web(f"book {query} to {preferences['destination']}")
return results
def personalize_results(results, user_history):
# Ví dụ về logic cá nhân hóa
personalized = [result for result in results if result not in user_history]
return personalized[:10] # Trả về 10 kết quả cá nhân hóa hàng đầu
Ví dụ Sử dụng
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
user_history = ["Louvre Museum website", "Book flight to Paris"]
query = "best museums in Paris"
results = search_with_intent(query, preferences, user_history)
print("Search Results:", results)
Các tác nhân tạo mã code sử dụng mô hình trí tuệ nhân tạo để viết và thực thi mã, giải quyết các vấn đề phức tạp và tự động hóa các tác vụ.
Các tác nhân tạo mã code sử dụng các mô hình AI sinh để viết và chạy mã. Những tác nhân này có thể giải quyết các vấn đề phức tạp, tự động hóa công việc và cung cấp những thông tin giá trị bằng cách tạo ra và thực thi mã trong nhiều ngôn ngữ lập trình khác nhau.
Hãy tưởng tượng bạn đang thiết kế một tác nhân tạo mã code. Dưới đây là cách nó có thể hoạt động:
Trong ví dụ này, chúng ta sẽ thiết kế một tác nhân tạo mã code, Đại lý Du lịch, để hỗ trợ người dùng lập kế hoạch du lịch bằng cách tạo và thực thi mã. Tác nhân này có thể xử lý các tác vụ như lấy các tùy chọn du lịch, lọc kết quả, và biên soạn hành trình sử dụng AI sinh.
Thu thập Tùy chọn của Người dùng
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
Tạo Mã để Lấy Dữ liệu
def generate_code_to_fetch_data(preferences):
# Ví dụ: Tạo mã để tìm kiếm chuyến bay dựa trên sở thích của người dùng
code = f"""
def search_flights():
import requests
response = requests.get('https://api.example.com/flights', params={preferences})
return response.json()
"""
return code
def generate_code_to_fetch_hotels(preferences):
# Ví dụ: Tạo mã để tìm kiếm khách sạn
code = f"""
def search_hotels():
import requests
response = requests.get('https://api.example.com/hotels', params={preferences})
return response.json()
"""
return code
Thực thi Mã được Tạo
def execute_code(code):
# Thực thi mã đã tạo bằng exec
exec(code)
result = locals()
return result
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
flight_code = generate_code_to_fetch_data(preferences)
hotel_code = generate_code_to_fetch_hotels(preferences)
flights = execute_code(flight_code)
hotels = execute_code(hotel_code)
print("Flight Options:", flights)
print("Hotel Options:", hotels)
Tạo Hành trình
def generate_itinerary(flights, hotels, attractions):
itinerary = {
"flights": flights,
"hotels": hotels,
"attractions": attractions
}
return itinerary
attractions = search_attractions(preferences)
itinerary = generate_itinerary(flights, hotels, attractions)
print("Suggested Itinerary:", itinerary)
Điều chỉnh Dựa trên Phản hồi
def adjust_based_on_feedback(feedback, preferences):
# Điều chỉnh tùy chọn dựa trên phản hồi của người dùng
if "liked" in feedback:
preferences["favorites"] = feedback["liked"]
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
return preferences
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
updated_preferences = adjust_based_on_feedback(feedback, preferences)
# Tạo lại và thực thi mã với tùy chọn đã cập nhật
updated_flight_code = generate_code_to_fetch_data(updated_preferences)
updated_hotel_code = generate_code_to_fetch_hotels(updated_preferences)
updated_flights = execute_code(updated_flight_code)
updated_hotels = execute_code(updated_hotel_code)
updated_itinerary = generate_itinerary(updated_flights, updated_hotels, attractions)
print("Updated Itinerary:", updated_itinerary)
Dựa trên cấu trúc bảng có thể nâng cao quá trình tạo truy vấn bằng cách tận dụng nhận thức môi trường và khả năng lập luận.
Đây là một ví dụ về cách làm điều này:
Dưới đây là ví dụ mã Python cập nhật kết hợp các khái niệm này:
def adjust_based_on_feedback(feedback, preferences, schema):
# Điều chỉnh sở thích dựa trên phản hồi của người dùng
if "liked" in feedback:
preferences["favorites"] = feedback["liked"]
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
# Lý luận dựa trên sơ đồ để điều chỉnh các sở thích liên quan khác
for field in schema:
if field in preferences:
preferences[field] = adjust_based_on_environment(feedback, field, schema)
return preferences
def adjust_based_on_environment(feedback, field, schema):
# Logic tùy chỉnh để điều chỉnh sở thích dựa trên sơ đồ và phản hồi
if field in feedback["liked"]:
return schema[field]["positive_adjustment"]
elif field in feedback["disliked"]:
return schema[field]["negative_adjustment"]
return schema[field]["default"]
def generate_code_to_fetch_data(preferences):
# Tạo mã để lấy dữ liệu chuyến bay dựa trên sở thích đã cập nhật
return f"fetch_flights(preferences={preferences})"
def generate_code_to_fetch_hotels(preferences):
# Tạo mã để lấy dữ liệu khách sạn dựa trên sở thích đã cập nhật
return f"fetch_hotels(preferences={preferences})"
def execute_code(code):
# Mô phỏng việc thực thi mã và trả về dữ liệu giả
return {"data": f"Executed: {code}"}
def generate_itinerary(flights, hotels, attractions):
# Tạo lịch trình dựa trên chuyến bay, khách sạn và điểm tham quan
return {"flights": flights, "hotels": hotels, "attractions": attractions}
# Ví dụ về sơ đồ
schema = {
"favorites": {"positive_adjustment": "increase", "negative_adjustment": "decrease", "default": "neutral"},
"avoid": {"positive_adjustment": "decrease", "negative_adjustment": "increase", "default": "neutral"}
}
# Ví dụ về cách sử dụng
preferences = {"favorites": "sightseeing", "avoid": "crowded places"}
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
updated_preferences = adjust_based_on_feedback(feedback, preferences, schema)
# Tạo lại và thực thi mã với sở thích đã cập nhật
updated_flight_code = generate_code_to_fetch_data(updated_preferences)
updated_hotel_code = generate_code_to_fetch_hotels(updated_preferences)
updated_flights = execute_code(updated_flight_code)
updated_hotels = execute_code(updated_hotel_code)
updated_itinerary = generate_itinerary(updated_flights, updated_hotels, feedback["liked"])
print("Updated Itinerary:", updated_itinerary)
schema định nghĩa cách tùy chọn được điều chỉnh dựa trên phản hồi. Nó bao gồm các trường như favorites và avoid, với các điều chỉnh tương ứng.adjust_based_on_feedback): Phương thức này điều chỉnh tùy chọn dựa trên phản hồi và cấu trúc.adjust_based_on_environment): Phương thức này tùy chỉnh các điều chỉnh dựa trên cấu trúc và phản hồi.Bằng cách làm cho hệ thống nhận thức về môi trường và lập luận dựa trên cấu trúc, nó có thể tạo các truy vấn chính xác và phù hợp hơn, dẫn đến các đề xuất du lịch tốt hơn và trải nghiệm người dùng cá nhân hóa hơn.
SQL (Ngôn ngữ Truy vấn Có cấu trúc) là công cụ mạnh mẽ để tương tác với cơ sở dữ liệu. Khi được sử dụng như một phần trong phương pháp Retrieval-Augmented Generation (RAG), SQL có thể truy xuất dữ liệu phù hợp từ cơ sở dữ liệu để thông báo và tạo các phản hồi hoặc hành động trong các tác nhân AI. Hãy khám phá cách SQL có thể được dùng như kỹ thuật RAG trong bối cảnh Đại lý Du lịch.
Ví dụ: Một tác nhân phân tích dữ liệu:
Thu thập Tùy chọn Người dùng
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
Tạo Truy vấn SQL
def generate_sql_query(table, preferences):
query = f"SELECT * FROM {table} WHERE "
conditions = []
for key, value in preferences.items():
conditions.append(f"{key}='{value}'")
query += " AND ".join(conditions)
return query
Thực thi Truy vấn SQL
import sqlite3
def execute_sql_query(query, database="travel.db"):
connection = sqlite3.connect(database)
cursor = connection.cursor()
cursor.execute(query)
results = cursor.fetchall()
connection.close()
return results
Tạo Đề xuất
def generate_recommendations(preferences):
flight_query = generate_sql_query("flights", preferences)
hotel_query = generate_sql_query("hotels", preferences)
attraction_query = generate_sql_query("attractions", preferences)
flights = execute_sql_query(flight_query)
hotels = execute_sql_query(hotel_query)
attractions = execute_sql_query(attraction_query)
itinerary = {
"flights": flights,
"hotels": hotels,
"attractions": attractions
}
return itinerary
travel_agent = Travel_Agent()
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
travel_agent.gather_preferences(preferences)
itinerary = generate_recommendations(preferences)
print("Suggested Itinerary:", itinerary)
Truy vấn chuyến bay
SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate';
Truy vấn khách sạn
SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate';
Truy vấn điểm tham quan
SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine';
Bằng cách tận dụng SQL như một phần của kỹ thuật Retrieval-Augmented Generation (RAG), các tác nhân AI như Đại lý Du lịch có thể truy xuất và sử dụng dữ liệu phù hợp một cách động để cung cấp các đề xuất chính xác và cá nhân hóa.
Để minh họa một triển khai của metacognition, hãy tạo một tác nhân đơn giản phản ánh quá trình ra quyết định của mình trong khi giải quyết một vấn đề. Trong ví dụ này, chúng ta sẽ xây dựng một hệ thống mà tác nhân cố gắng tối ưu hóa lựa chọn khách sạn, nhưng sau đó đánh giá lý luận riêng và điều chỉnh chiến lược khi mắc lỗi hoặc lựa chọn chưa tối ưu.
Chúng ta sẽ mô phỏng điều này bằng ví dụ cơ bản, nơi tác nhân chọn khách sạn dựa trên sự kết hợp giữa giá và chất lượng, nhưng sẽ “phản ánh” các quyết định và điều chỉnh cho phù hợp.
Đây là một ví dụ:
class HotelRecommendationAgent:
def __init__(self):
self.previous_choices = [] # Lưu trữ các khách sạn đã chọn trước đó
self.corrected_choices = [] # Lưu trữ các lựa chọn đã được chỉnh sửa
self.recommendation_strategies = ['cheapest', 'highest_quality'] # Các chiến lược có sẵn
def recommend_hotel(self, hotels, strategy):
"""
Recommend a hotel based on the chosen strategy.
The strategy can either be 'cheapest' or 'highest_quality'.
"""
if strategy == 'cheapest':
recommended = min(hotels, key=lambda x: x['price'])
elif strategy == 'highest_quality':
recommended = max(hotels, key=lambda x: x['quality'])
else:
recommended = None
self.previous_choices.append((strategy, recommended))
return recommended
def reflect_on_choice(self):
"""
Reflect on the last choice made and decide if the agent should adjust its strategy.
The agent considers if the previous choice led to a poor outcome.
"""
if not self.previous_choices:
return "No choices made yet."
last_choice_strategy, last_choice = self.previous_choices[-1]
# Giả sử chúng ta có một số phản hồi từ người dùng cho biết liệu lựa chọn cuối cùng có tốt hay không
user_feedback = self.get_user_feedback(last_choice)
if user_feedback == "bad":
# Điều chỉnh chiến lược nếu lựa chọn trước đó không thoả đáng
new_strategy = 'highest_quality' if last_choice_strategy == 'cheapest' else 'cheapest'
self.corrected_choices.append((new_strategy, last_choice))
return f"Reflecting on choice. Adjusting strategy to {new_strategy}."
else:
return "The choice was good. No need to adjust."
def get_user_feedback(self, hotel):
"""
Simulate user feedback based on hotel attributes.
For simplicity, assume if the hotel is too cheap, the feedback is "bad".
If the hotel has quality less than 7, feedback is "bad".
"""
if hotel['price'] < 100 or hotel['quality'] < 7:
return "bad"
return "good"
# Mô phỏng một danh sách các khách sạn (giá cả và chất lượng)
hotels = [
{'name': 'Budget Inn', 'price': 80, 'quality': 6},
{'name': 'Comfort Suites', 'price': 120, 'quality': 8},
{'name': 'Luxury Stay', 'price': 200, 'quality': 9}
]
# Tạo một đại lý
agent = HotelRecommendationAgent()
# Bước 1: Đại lý gợi ý một khách sạn sử dụng chiến lược "rẻ nhất"
recommended_hotel = agent.recommend_hotel(hotels, 'cheapest')
print(f"Recommended hotel (cheapest): {recommended_hotel['name']}")
# Bước 2: Đại lý suy ngẫm về lựa chọn và điều chỉnh chiến lược nếu cần thiết
reflection_result = agent.reflect_on_choice()
print(reflection_result)
# Bước 3: Đại lý gợi ý lại, lần này sử dụng chiến lược đã được điều chỉnh
adjusted_recommendation = agent.recommend_hotel(hotels, 'highest_quality')
print(f"Adjusted hotel recommendation (highest_quality): {adjusted_recommendation['name']}")
Điểm mấu chốt ở đây là khả năng của tác nhân để:
Đây là dạng đơn giản của metacognition khi hệ thống có khả năng điều chỉnh quy trình lý luận dựa trên phản hồi nội bộ.
Metacognition là công cụ mạnh mẽ có thể tăng đáng kể khả năng của các tác nhân AI. Bằng cách tích hợp các quy trình metacognitive, bạn có thể thiết kế các tác nhân thông minh hơn, thích nghi tốt hơn, và hiệu quả hơn. Hãy sử dụng các tài nguyên bổ sung để khám phá sâu hơn thế giới thú vị của metacognition trong các tác nhân AI.
Tham gia Microsoft Foundry Discord để gặp gỡ các học viên khác, tham dự giờ làm việc và được giải đáp các câu hỏi về Tác nhân AI.
Tuyên bố miễn trừ trách nhiệm: Tài liệu này đã được dịch bằng dịch vụ dịch thuật AI Co-op Translator. Mặc dù chúng tôi cố gắng đảm bảo độ chính xác, xin lưu ý rằng bản dịch tự động có thể chứa lỗi hoặc sai sót. Tài liệu gốc bằng ngôn ngữ gốc nên được coi là nguồn tin chính thức. Đối với thông tin quan trọng, nên sử dụng dịch vụ dịch thuật chuyên nghiệp bởi con người. Chúng tôi không chịu trách nhiệm về bất kỳ hiểu lầm hoặc giải thích sai nào phát sinh từ việc sử dụng bản dịch này.