text
stringlengths 55
456k
| metadata
dict |
---|---|
# 元認知於人工智能代理中的應用
## 簡介
歡迎來到關於人工智能代理元認知的課程!本章節專為對人工智能代理如何思考其自身思維過程感興趣的初學者設計。在本課程結束時,您將理解關鍵概念,並能運用實際例子設計具備元認知能力的人工智能代理。
## 學習目標
完成本課程後,您將能夠:
1. 理解代理定義中推理循環的影響。
2. 使用規劃與評估技術幫助代理自我糾正。
3. 創建能夠操控代碼以完成任務的代理。
## 元認知簡介
元認知指的是涉及對自身思維過程進行思考的高階認知過程。對於人工智能代理來說,這意味著能夠基於自我意識和過去經驗評估並調整其行為。
### 什麼是元認知?
元認知,或稱“思考的思考”,是一種高階認知過程,涉及對自身認知過程的自我意識和自我調節。在人工智能領域,元認知使代理能夠評估並適應其策略和行動,從而提升問題解決和決策能力。通過理解元認知,您可以設計出更智能、更具適應性和效率的人工智能代理。
### 元認知在人工智能代理中的重要性
元認知在人工智能代理設計中具有以下幾點重要意義:

- **自我反思**:代理能夠評估自身表現並找出改進的領域。
- **適應性**:代理能夠根據過去經驗和變化的環境調整其策略。
- **錯誤糾正**:代理能夠自主檢測並糾正錯誤,從而獲得更準確的結果。
- **資源管理**:代理能夠通過規劃和評估行動來優化資源(如時間和計算能力)的使用。
## 人工智能代理的組成
在深入探討元認知過程之前,先了解人工智能代理的基本組成是很重要的。一個人工智能代理通常由以下部分組成:
- **人格**:代理的個性和特徵,定義了它如何與用戶互動。
- **工具**:代理能執行的功能和能力。
- **技能**:代理擁有的知識和專業能力。
這些組成部分共同構建了一個“專業單元”,能夠執行特定任務。
**例子**:考慮一個旅行代理,它不僅計劃您的假期,還能基於實時數據和過往客戶旅程經驗調整路徑。
### 例子:旅行代理服務中的元認知
假設您正在設計一個由人工智能驅動的旅行代理服務。該代理“旅行代理”幫助用戶規劃假期。為了融入元認知,旅行代理需要基於自我意識和過往經驗評估並調整其行動。以下是元認知可能發揮作用的方式:
#### 當前任務
幫助用戶規劃一次巴黎之旅。
#### 完成任務的步驟
1. **收集用戶偏好**:詢問用戶旅行日期、預算、興趣(如博物館、美食、購物)以及任何具體需求。
2. **檢索信息**:搜尋符合用戶偏好的航班選項、住宿、景點和餐廳。
3. **生成推薦**:提供包含航班詳情、酒店預訂和建議活動的個性化行程。
4. **根據反饋調整**:詢問用戶對推薦的反饋並進行必要調整。
#### 所需資源
- 訪問航班和酒店預訂數據庫。
- 關於巴黎景點和餐廳的信息。
- 過往互動中的用戶反饋數據。
#### 經驗與自我反思
旅行代理利用元認知評估其表現並從過去經驗中學習。例如:
1. **分析用戶反饋**:旅行代理回顧用戶反饋,以確定哪些推薦受到歡迎,哪些不受歡迎,並相應地調整未來建議。
2. **適應性**:如果用戶之前提到不喜歡擁擠的地方,旅行代理將避免在高峰時段推薦熱門旅遊景點。
3. **錯誤糾正**:如果旅行代理在過去的預訂中出現錯誤,例如推薦已滿房的酒店,它將學習在推薦之前更嚴格地檢查可用性。
#### 實用開發者示例
以下是一個簡化的示例,展示旅行代理在代碼中如何融入元認知:
```python
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):
# Search for flights, hotels, and attractions based on preferences
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)
# Analyze feedback and adjust future recommendations
self.user_preferences = adjust_preferences(self.user_preferences, feedback)
# Example usage
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)
```
#### 為什麼元認知很重要
- **自我反思**:代理能分析其表現並找出改進的領域。
- **適應性**:代理能根據反饋和變化條件調整策略。
- **錯誤糾正**:代理能自主檢測並糾正錯誤。
- **資源管理**:代理能優化資源的使用,例如時間和計算能力。
通過融入元認知,旅行代理可以提供更個性化和準確的旅行推薦,提升整體用戶體驗。
---
## 2. 代理中的規劃
規劃是人工智能代理行為的一個關鍵組成部分。它涉及考慮當前狀態、資源和可能的障礙,制定實現目標所需的步驟。
### 規劃的要素
- **當前任務**:明確定義任務。
- **完成任務的步驟**:將任務分解為可管理的步驟。
- **所需資源**:確定必要的資源。
- **經驗**:利用過去經驗指導規劃。
**例子**:以下是旅行代理有效協助用戶規劃旅行所需採取的步驟:
### 旅行代理的步驟
1. **收集用戶偏好**
- 詢問用戶有關旅行日期、預算、興趣以及任何具體需求的詳細信息。
- 例子:“您計劃什麼時候旅行?”“您的預算範圍是多少?”“您在度假時喜歡哪些活動?”
2. **檢索信息**
- 根據用戶偏好搜尋相關旅行選項。
- **航班**:尋找符合用戶預算和偏好旅行日期的可用航班。
- **住宿**:尋找符合用戶位置、價格和設施偏好的酒店或租賃物業。
- **景點和餐廳**:確定符合用戶興趣的熱門景點、活動和餐飲選擇。
3. **生成推薦**
- 將檢索到的信息編輯成個性化行程。
- 提供航班選項、酒店預訂和建議活動的詳細信息,確保建議符合用戶偏好。
4. **向用戶展示行程**
- 與用戶分享建議行程供其審閱。
- 例子:“這是您巴黎之旅的建議行程,包括航班詳情、酒店預訂以及推薦活動和餐廳。請告訴我您的想法!”
5. **收集反饋**
- 詢問用戶對建議行程的反饋。
- 例子:“您喜歡這些航班選項嗎?”“這家酒店是否符合您的需求?”“是否有任何活動需要添加或刪除?”
6. **根據反饋調整**
- 根據用戶反饋修改行程。
- 將航班、住宿和活動推薦做必要更改以更好地符合用戶偏好。
7. **最終確認**
- 向用戶展示更新後的行程供其最終確認。
- 例子:“我已根據您的反饋進行了調整。這是更新後的行程。一切看起來是否合適?”
8. **預訂並確認**
- 用戶批准行程後,進行航班、住宿及任何預先計劃活動的預訂。
- 將確認詳情發送給用戶。
9. **提供持續支持**
- 在旅行前和旅行期間,隨時為用戶提供幫助或額外需求。
- 例子:“如果您在旅行期間需要進一步的幫助,隨時聯繫我!”
### 互動示例
```python
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)
# Example usage within a booing request
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)
```
## 3. 糾正性 RAG 系統
首先,讓我們了解 RAG 工具與預先上下文加載的區別:

### 檢索增強生成(RAG)
RAG 將檢索系統與生成模型結合。當查詢被提出時,檢索系統從外部來源獲取相關文檔或數據,並將檢索到的信息用於增強生成模型的輸入。這有助於模型生成更準確和上下文相關的響應。
在 RAG 系統中,代理從知識庫中檢索相關信息並用於生成適當的響應或行動。
### 糾正性 RAG 方法
糾正性 RAG 方法專注於使用 RAG 技術糾正錯誤並提高人工智能代理的準確性。這涉及:
1. **提示技術**:使用特定提示指導代理檢索相關信息。
2. **工具**:實施算法和機制,使代理能夠評估檢索信息的相關性並生成準確的響應。
3. **評估**:持續評估代理的表現並進行調整以提高其準確性和效率。
#### 例子:搜索代理中的糾正性 RAG
考慮一個從網絡檢索信息以回答用戶查詢的搜索代理。糾正性 RAG 方法可能涉及:
1. **提示技術**:根據用戶輸入制定搜索查詢。
2. **工具**:使用自然語言處理和機器學習算法對搜索結果進行排序和過濾。
3. **評估**:分析用戶反饋以識別和糾正檢索信息中的不準確之處。
### 糾正性 RAG 在旅行代理中的應用
糾正性 RAG(檢索增強生成)增強了人工智能在檢索和生成信息時糾正任何不準確的能力。讓我們看看旅行代理如何使用糾正性 RAG 方法提供更準確和相關的旅行建議。這涉及:
- **提示技術**:使用特定提示指導代理檢索相關信息。
- **工具**:實施算法和機制,使代理能夠評估檢索信息的相關性並生成準確的響應。
- **評估**:持續評估代理的表現並進行調整以提高其準確性和效率。
#### 實施糾正性 RAG 的步驟
1. **初次用戶互動**
- 旅行代理收集用戶的初始偏好,例如目的地、旅行日期、預算和興趣。
- 例子:```python
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
```
2. **信息檢索**
- 旅行代理根據用戶偏好檢索有關航班、住宿、景點和餐廳的信息。
- 例子:```python
flights = search_flights(preferences)
hotels = search_hotels(preferences)
attractions = search_attractions(preferences)
```
3. **生成初始推薦**
- 旅行代理使用檢索到的信息生成個性化行程。
- 例子:```python
itinerary = create_itinerary(flights, hotels, attractions)
print("Suggested Itinerary:", itinerary)
```
4. **收集用戶反饋**
- 旅行代理詢問用戶對初始推薦的反饋。
- 例子:```python
feedback = {
"liked": ["Louvre Museum"],
"disliked": ["Eiffel Tower (too crowded)"]
}
```
5. **糾正性 RAG 過程**
- **提示技術**:請從左到右書寫輸出。
```
```markdown
旅遊代理根據用戶反饋制定新的搜索查詢。
- 範例:```python
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
```
- **工具**:旅遊代理使用算法對新的搜索結果進行排名和篩選,強調基於用戶反饋的相關性。
- 範例:```python
new_attractions = search_attractions(preferences)
new_itinerary = create_itinerary(flights, hotels, new_attractions)
print("Updated Itinerary:", new_itinerary)
```
- **評估**:旅遊代理通過分析用戶反饋並進行必要調整,不斷評估其推薦的相關性和準確性。
- 範例:```python
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)
```
#### 實用範例
以下是一個簡化的 Python 代碼範例,展示了如何在旅遊代理中應用 Corrective RAG 方法:
```python
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
# Example usage
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)
```
### 預先加載上下文
預先加載上下文是指在處理查詢之前,將相關的上下文或背景信息加載到模型中。這意味著模型從一開始就能夠訪問這些信息,從而在不需要在過程中檢索額外數據的情況下生成更有根據的回應。
以下是一個展示如何為旅遊代理應用程序在 Python 中進行預先加載上下文的簡化範例:
```python
class TravelAgent:
def __init__(self):
# Pre-load popular destinations and their information
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):
# Fetch destination information from pre-loaded context
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}."
# Example usage
travel_agent = TravelAgent()
print(travel_agent.get_destination_info("Paris"))
print(travel_agent.get_destination_info("Tokyo"))
```
#### 解釋
1. **初始化 (`__init__` method)**: The `TravelAgent` class pre-loads a dictionary containing information about popular destinations such as Paris, Tokyo, New York, and Sydney. This dictionary includes details like the country, currency, language, and major attractions for each destination.
2. **Retrieving Information (`get_destination_info` method)**: When a user queries about a specific destination, the `get_destination_info` 方法)**:該方法從預加載的上下文字典中獲取相關信息。通過預加載上下文,旅遊代理應用程序可以快速響應用戶查詢,而不需要實時從外部源檢索這些信息。這使應用程序更高效且更具響應性。
### 在迭代前用目標啟動計劃
在迭代前用目標啟動計劃是指以清晰的目標或預期結果為起點。通過提前定義這一目標,模型可以將其作為指導原則,貫穿整個迭代過程。這有助於確保每次迭代都朝著實現所需結果的方向邁進,使過程更加高效且聚焦。
以下是一個展示如何在旅遊代理中用目標啟動旅行計劃的 Python 範例:
### 場景
一位旅遊代理希望為客戶制定一個定制化的假期計劃。目標是基於客戶的偏好和預算,創建一個最大化客戶滿意度的旅行行程。
### 步驟
1. 定義客戶的偏好和預算。
2. 基於這些偏好啟動初始計劃。
3. 迭代以完善計劃,優化客戶滿意度。
#### Python 代碼
```python
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']
# Example usage
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)
```
#### 代碼解釋
1. **初始化 (`__init__` method)**: The `TravelAgent` class is initialized with a list of potential destinations, each having attributes like name, cost, and activity type.
2. **Bootstrapping the Plan (`bootstrap_plan` method)**: This method creates an initial travel plan based on the client's preferences and budget. It iterates through the list of destinations and adds them to the plan if they match the client's preferences and fit within the budget.
3. **Matching Preferences (`match_preferences` method)**: This method checks if a destination matches the client's preferences.
4. **Iterating the Plan (`iterate_plan` method)**: This method refines the initial plan by trying to replace each destination in the plan with a better match, considering the client's preferences and budget constraints.
5. **Calculating Cost (`calculate_cost` 方法)**:該方法計算當前計劃的總成本,包括一個潛在的新目的地。
#### 使用範例
- **初始計劃**:旅遊代理基於客戶對觀光的偏好和 $2000 的預算創建初始計劃。
- **優化計劃**:旅遊代理通過迭代完善計劃,優化客戶的偏好和預算。
通過以清晰的目標(例如,最大化客戶滿意度)啟動計劃並進行迭代以完善計劃,旅遊代理可以為客戶創建一個定制化且優化的旅行行程。這種方法確保旅行計劃從一開始就符合客戶的偏好和預算,並在每次迭代中得到改進。
### 利用 LLM 進行重新排序和評分
大型語言模型(LLMs)可以通過評估檢索到的文檔或生成的回應的相關性和質量來進行重新排序和評分。以下是其工作原理:
**檢索**:初始檢索步驟根據查詢獲取一組候選文檔或回應。
**重新排序**:LLM 評估這些候選項,並根據其相關性和質量重新排序。此步驟確保最相關和高質量的信息優先呈現。
**評分**:LLM 為每個候選項分配分數,反映其相關性和質量。這有助於選擇最適合用戶的回應或文檔。
通過利用 LLM 進行重新排序和評分,系統可以提供更準確且具有上下文相關的信息,從而改善整體用戶體驗。
以下是一個展示旅遊代理如何使用大型語言模型(LLM)根據用戶偏好對旅行目的地進行重新排序和評分的 Python 範例:
#### 場景 - 基於偏好的旅行
一位旅遊代理希望根據客戶的偏好推薦最佳旅行目的地。LLM 將幫助重新排序和評分目的地,確保呈現最相關的選項。
#### 步驟:
1. 收集用戶偏好。
2. 檢索潛在旅行目的地的列表。
3. 使用 LLM 根據用戶偏好重新排序和評分目的地。
以下是如何使用 Azure OpenAI 服務更新上述範例:
#### 要求
1. 您需要擁有 Azure 訂閱。
2. 創建 Azure OpenAI 資源並獲取您的 API 密鑰。
#### Python 代碼範例
```python
import requests
import json
class TravelAgent:
def __init__(self, destinations):
self.destinations = destinations
def get_recommendations(self, preferences, api_key, endpoint):
# Generate a prompt for the Azure OpenAI
prompt = self.generate_prompt(preferences)
# Define headers and payload for the request
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
payload = {
"prompt": prompt,
"max_tokens": 150,
"temperature": 0.7
}
# Call the Azure OpenAI API to get the re-ranked and scored destinations
response = requests.post(endpoint, headers=headers, json=payload)
response_data = response.json()
# Extract and return the recommendations
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
# Example usage
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)
```
#### 代碼解釋 - 偏好預訂器
1. **初始化**:將 `TravelAgent` class is initialized with a list of potential travel destinations, each having attributes like name and description.
2. **Getting Recommendations (`get_recommendations` method)**: This method generates a prompt for the Azure OpenAI service based on the user's preferences and makes an HTTP POST request to the Azure OpenAI API to get re-ranked and scored destinations.
3. **Generating Prompt (`generate_prompt` method)**: This method constructs a prompt for the Azure OpenAI, including the user's preferences and the list of destinations. The prompt guides the model to re-rank and score the destinations based on the provided preferences.
4. **API Call**: The `requests` library is used to make an HTTP POST request to the Azure OpenAI API endpoint. The response contains the re-ranked and scored destinations.
5. **Example Usage**: The travel agent collects user preferences (e.g., interest in sightseeing and diverse culture) and uses the Azure OpenAI service to get re-ranked and scored recommendations for travel destinations.
Make sure to replace `your_azure_openai_api_key` with your actual Azure OpenAI API key and `https://your-endpoint.com/...` 替換為 Azure OpenAI 部署的實際端點 URL。
通過利用 LLM 進行重新排序和評分,旅遊代理可以為客戶提供更個性化且相關性更高的旅行推薦,從而提升他們的整體體驗。
### RAG:提示技術與工具
檢索增強生成(RAG)既可以作為提示技術,也可以作為 AI 代理開發中的工具。理解兩者的區別有助於您更有效地在項目中利用 RAG。
#### RAG 作為提示技術
**什麼是 RAG?**
- 作為提示技術,RAG 涉及制定特定查詢或提示,以引導從大型語料庫或數據庫中檢索相關信息。這些信息隨後被用於生成回應或採取行動。
**如何運作:**
1. **制定提示**:根據任務或用戶輸入創建結構良好的提示或查詢。
2. **檢索信息**:使用提示從預先存在的知識庫或數據集中搜索相關數據。
3. **生成回應**:將檢索到的信息與生成式 AI 模型結合,生成全面且連貫的回應。
**旅遊代理範例**:
- 用戶輸入:「我想參觀巴黎的博物館。」
- 提示:「查找巴黎的頂級博物館。」
- 檢索信息:關於盧浮宮、奧賽博物館等的詳細信息。
- 生成回應:「以下是巴黎的一些頂級博物館:盧浮宮、奧賽博物館和蓬皮杜中心。」
#### RAG 作為工具
**什麼是 RAG?**
- 作為工具,RAG 是一個集成系統,自動化檢索和生成過程,使開發者能夠更輕鬆地實現複雜的 AI 功能,而無需為每個查詢手動編寫提示。
**如何運作:**
1. **集成**:將 RAG 嵌入到 AI 代理的架構中,使其能夠自動處理檢索和生成任務。
2. **自動化**:工具管理整個過程,從接收用戶輸入到生成最終回應,無需為每一步驟顯式提示。
3. **效率**:通過簡化檢索和生成過程,提高代理的性能,實現更快且更準確的回應。
**旅遊代理範例**:
- 用戶輸入:「我想參觀巴黎的博物館。」
- RAG 工具:自動檢索關於博物館的信息並生成回應。
- 生成回應:「以下是巴黎的一些頂級博物館:盧浮宮、奧賽博物館和蓬皮杜中心。」
### 比較
| **方面** | **提示技術** | **工具** |
|------------------------|-------------------------------------------------------------|---------------------------------------------------|
| **手動與自動** | 每個查詢手動制定提示。 | 檢索和生成過程自動化。 |
| **控制** | 提供對檢索過程的更多控制。 | 簡化並自動化檢索和生成過程。 |
| **靈活性** | 允許基於特定需求定制提示。 | 對於大規模實現更高效。 |
| **複雜性** | 需要編寫和調整提示。 | 更易於集成到 AI 代理的架構中。 |
### 實用範例
**提示技術範例:**
```python
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)
```
**工具範例:**
```python
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)
```
### 評估相關性
評估相關性是 AI 代理性能的一個關鍵方面。它確保代理檢索和生成的信息對用戶是適當的、準確的且有用的。讓我們探討如何在 AI 代理中評估相關性,包括實用範例和技術。
#### 評估相關性的關鍵概念
1. **上下文意識**:
- 代理必須理解用戶查詢的上下文,以檢索和生成相關信息。
- 範例:如果用戶詢問「巴黎最好的餐廳」,代理應考慮用戶的偏好,例如菜系類型和預算。
2. **準確性**:
- 代理提供的信息應該是事實正確且最新的。
- 範例:推薦目前營業且評價良好的餐廳,而不是過時或已關閉的選項。
3. **用戶意圖**:
- 代理應推斷用戶查詢背後的意圖,以提供最相關的信息。
- 範例:如果用戶詢問「經濟型酒店」,代理應優先考慮價格實惠的選項。
4. **反饋迴路**:
- 持續收集和分析用戶反饋,有助於代理完善其相關性評估過程。
- 範例:將用戶對先前推薦的評分和反饋納入,改進未來的回應。
#### 評估相關性的實用技術
1. **相關性評分**:
- 根據與用戶查詢和偏好的匹配程度,為每個檢索項分配相關性分數。
- 範例:```python
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
```
2. **篩選和排序**:
- 篩選掉不相關的項目,並根據相關性分數對剩餘項目進行排序。
- 範例:```python
def filter_and_rank(items, query):
ranked_items = sorted(items, key=lambda item: relevance_score(item, query), reverse=True)
return ranked_items[:10] # Return top 10 relevant items
```
3. **自然語言處理(NLP)**:
- 使用 NLP 技術來理解用戶查詢並檢索相關信息。
- 範例:```python
def process_query(query):
# Use NLP to extract key information from the user's query
processed_query = nlp(query)
return processed_query
```
4. **用戶反饋集成**:
- 收集用戶對推薦的反饋,並用於調整未來的相關性評估。
- 範例:```python
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
```
#### 範例:在旅遊代理中評估相關性
以下是一個展示旅遊代理如何評估旅行推薦相關性的實用範例:
```python
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] # Return top 10 relevant items
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
# Example usage
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)
```
### 帶有意圖的搜索
帶有意圖的搜索是指理解和解釋用戶查詢背後的潛在目的或目標,以檢索和生成最相關且有用的信息。這種方法超越了簡單的關鍵詞匹配,專注於掌握用戶的實際需求和上下文。
#### 帶有意圖的搜索的關鍵概念
1. **理解用戶意圖**:
- 用戶意圖可以分為三種主要類型:資訊性、導航性和交易性。
- **資訊性意圖**:用戶尋求有關某個主題的信息(例如,「什麼是...」)。
```
巴黎最好的博物館?"). - **導航意圖**:用戶希望導航到特定網站或頁面(例如,“盧浮宮官方網站”)。 - **交易意圖**:用戶旨在執行交易,例如預訂航班或進行購買(例如,“預訂飛往巴黎的航班”)。
2. **上下文意識**:
- 分析用戶查詢的上下文有助於準確識別其意圖。這包括考慮之前的互動、用戶偏好以及當前查詢的具體細節。
3. **自然語言處理 (NLP)**:
- 採用 NLP 技術來理解和解釋用戶提供的自然語言查詢。這包括實體識別、情感分析和查詢解析等任務。
4. **個性化**:
- 根據用戶的歷史記錄、偏好和反饋來個性化搜索結果,提高檢索信息的相關性。
#### 實用示例:在旅遊代理中基於意圖的搜索
讓我們以旅遊代理為例,看看如何實現基於意圖的搜索。
1. **收集用戶偏好**
```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
```
2. **理解用戶意圖**
```python
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"
```
3. **上下文意識**
```python
def analyze_context(query, user_history):
# Combine current query with user history to understand context
context = {
"current_query": query,
"user_history": user_history
}
return context
```
4. **搜索並個性化結果**
```python
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):
# Example search logic for informational intent
results = search_web(f"best {preferences['interests']} in {preferences['destination']}")
return results
def search_navigation(query):
# Example search logic for navigational intent
results = search_web(query)
return results
def search_transaction(query, preferences):
# Example search logic for transactional intent
results = search_web(f"book {query} to {preferences['destination']}")
return results
def personalize_results(results, user_history):
# Example personalization logic
personalized = [result for result in results if result not in user_history]
return personalized[:10] # Return top 10 personalized results
```
5. **示例使用**
```python
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)
```
---
## 4. 作為工具的代碼生成
代碼生成代理使用 AI 模型編寫和執行代碼,解決複雜問題並自動化任務。
### 代碼生成代理
代碼生成代理利用生成式 AI 模型來編寫和執行代碼。這些代理可以通過生成和運行多種編程語言的代碼來解決複雜問題、自動化任務並提供有價值的見解。
#### 實用應用
1. **自動代碼生成**:為特定任務生成代碼片段,例如數據分析、網頁抓取或機器學習。
2. **SQL 作為 RAG**:使用 SQL 查詢從數據庫檢索和操作數據。
3. **問題解決**:創建並執行代碼以解決特定問題,例如優化算法或分析數據。
#### 示例:數據分析的代碼生成代理
假設您正在設計一個代碼生成代理。以下是其工作方式:
1. **任務**:分析數據集以識別趨勢和模式。
2. **步驟**:
- 將數據集加載到數據分析工具中。
- 生成 SQL 查詢以篩選和聚合數據。
- 執行查詢並檢索結果。
- 使用結果生成可視化和見解。
3. **所需資源**:訪問數據集、數據分析工具和 SQL 功能。
4. **經驗**:利用過去的分析結果來提高未來分析的準確性和相關性。
### 示例:旅遊代理的代碼生成代理
在此示例中,我們將設計一個代碼生成代理(旅遊代理),以通過生成和執行代碼來協助用戶規劃旅行。該代理可以處理例如獲取旅行選項、篩選結果和使用生成式 AI 編制行程的任務。
#### 代碼生成代理概述
1. **收集用戶偏好**:收集用戶輸入,如目的地、旅行日期、預算和興趣。
2. **生成代碼以獲取數據**:生成代碼片段以檢索有關航班、酒店和景點的信息。
3. **執行生成的代碼**:運行生成的代碼以獲取實時信息。
4. **生成行程**:將檢索到的數據編制成個性化旅行計劃。
5. **基於反饋進行調整**:接收用戶反饋,並在必要時重新生成代碼以優化結果。
#### 分步實現
1. **收集用戶偏好**
```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
```
2. **生成代碼以獲取數據**
```python
def generate_code_to_fetch_data(preferences):
# Example: Generate code to search for flights based on user preferences
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):
# Example: Generate code to search for hotels
code = f"""
def search_hotels():
import requests
response = requests.get('https://api.example.com/hotels', params={preferences})
return response.json()
"""
return code
```
3. **執行生成的代碼**
```python
def execute_code(code):
# Execute the generated code using 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)
```
4. **生成行程**
```python
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)
```
5. **基於反饋進行調整**
```python
def adjust_based_on_feedback(feedback, preferences):
# Adjust preferences based on user feedback
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)
# Regenerate and execute code with updated preferences
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)
```
### 利用環境感知和推理
基於表格的架構確實可以通過利用環境感知和推理來增強查詢生成過程。以下是如何實現的示例:
1. **理解架構**:系統將理解表格的架構並利用此信息來支持查詢生成。
2. **基於反饋進行調整**:系統將根據反饋調整用戶偏好,並推理需要在架構中更新的字段。
3. **生成和執行查詢**:系統將生成並執行查詢以根據新偏好檢索更新的航班和酒店數據。
以下是包含這些概念的更新 Python 代碼示例:
```python
def adjust_based_on_feedback(feedback, preferences, schema):
# Adjust preferences based on user feedback
if "liked" in feedback:
preferences["favorites"] = feedback["liked"]
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
# Reasoning based on schema to adjust other related preferences
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):
# Custom logic to adjust preferences based on schema and feedback
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):
# Generate code to fetch flight data based on updated preferences
return f"fetch_flights(preferences={preferences})"
def generate_code_to_fetch_hotels(preferences):
# Generate code to fetch hotel data based on updated preferences
return f"fetch_hotels(preferences={preferences})"
def execute_code(code):
# Simulate execution of code and return mock data
return {"data": f"Executed: {code}"}
def generate_itinerary(flights, hotels, attractions):
# Generate itinerary based on flights, hotels, and attractions
return {"flights": flights, "hotels": hotels, "attractions": attractions}
# Example schema
schema = {
"favorites": {"positive_adjustment": "increase", "negative_adjustment": "decrease", "default": "neutral"},
"avoid": {"positive_adjustment": "decrease", "negative_adjustment": "increase", "default": "neutral"}
}
# Example usage
preferences = {"favorites": "sightseeing", "avoid": "crowded places"}
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
updated_preferences = adjust_based_on_feedback(feedback, preferences, schema)
# Regenerate and execute code with updated preferences
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)
```
#### 解釋 - 基於反饋進行預訂
1. **架構感知**:
`schema` dictionary defines how preferences should be adjusted based on feedback. It includes fields like `favorites` and `avoid`, with corresponding adjustments.
2. **Adjusting Preferences (`adjust_based_on_feedback` method)**: This method adjusts preferences based on user feedback and the schema.
3. **Environment-Based Adjustments (`adjust_based_on_environment` 方法**:此方法根據架構和反饋定制調整。
4. **生成和執行查詢**:系統生成代碼以根據調整後的偏好檢索更新的航班和酒店數據,並模擬執行這些查詢。
5. **生成行程**:系統基於新的航班、酒店和景點數據創建更新的行程。
通過使系統具備環境感知並基於架構進行推理,它可以生成更準確和相關的查詢,從而提供更好的旅行建議和更個性化的用戶體驗。
### 使用 SQL 作為檢索增強生成 (RAG) 技術
SQL(結構化查詢語言)是與數據庫交互的強大工具。作為檢索增強生成 (RAG) 方法的一部分,SQL 可以從數據庫檢索相關數據,以在 AI 代理中生成響應或執行操作。讓我們探索在旅遊代理上下文中如何使用 SQL 作為 RAG 技術。
#### 關鍵概念
1. **數據庫交互**:
- 使用 SQL 查詢數據庫,檢索相關信息並操作數據。
- 示例:從旅遊數據庫中檢索航班詳情、酒店信息和景點。
2. **與 RAG 集成**:
- 根據用戶輸入和偏好生成 SQL 查詢。
- 然後使用檢索到的數據生成個性化建議或操作。
3. **動態查詢生成**:
- AI 代理根據上下文和用戶需求生成動態 SQL 查詢。
- 示例:定制 SQL 查詢以根據預算、日期和興趣篩選結果。
#### 應用
- **自動代碼生成**:為特定任務生成代碼片段。
- **SQL 作為 RAG**:使用 SQL 查詢操作數據。
- **問題解決**:創建並執行代碼以解決問題。
**示例**:數據分析代理:
1. **任務**:分析數據集以發現趨勢。
2. **步驟**:
- 加載數據集。
- 生成 SQL 查詢以篩選數據。
- 執行查詢並檢索結果。
- 生成可視化和見解。
3. **資源**:數據集訪問權限、SQL 功能。
4. **經驗**:利用過去的結果改進未來分析。
#### 實用示例:在旅遊代理中使用 SQL
1. **收集用戶偏好**
```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
```
2. **生成 SQL 查詢**
```python
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
```
3. **執行 SQL 查詢**
```python
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
```
4. **生成推薦**
```python
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)
```
#### 示例 SQL 查詢
1. **航班查詢**
```sql
SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate';
```
2. **酒店查詢**
```sql
SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate';
```
3. **景點查詢**
```sql
SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine';
```
通過將 SQL 作為檢索增強生成 (RAG) 技術的一部分,像旅遊代理這樣的 AI 代理可以動態檢索並利用相關數據,提供準確且個性化的建議。
### 結論
元認知是一種強大的工具,可以顯著增強 AI 代理的能力。通過納入元認知過程,您可以設計出更智能、更適應性和更高效的代理。利用額外資源進一步探索 AI 代理中元認知的迷人世界。
**免責聲明**:
本文件使用基於機器的人工智能翻譯服務進行翻譯。我們雖然致力於確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文文件作為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或錯誤解釋概不負責。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/hk/09-metacognition/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/09-metacognition/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 38907
} |
# AI Agents 在生產環境中的應用
## 簡介
本課程將涵蓋:
- 如何有效地計劃將你的 AI Agent 部署到生產環境。
- 部署 AI Agent 到生產環境時可能面臨的常見錯誤和問題。
- 如何在保持 AI Agent 性能的同時管理成本。
## 學習目標
完成本課程後,你將了解如何:
- 提升生產環境中的 AI Agent 系統性能、成本效益和有效性的技術。
- 評估你的 AI Agent 的方法以及具體操作方式。
- 控制 AI Agent 部署到生產環境時的成本。
部署可信任的 AI Agent 非常重要。請參考 "Building Trustworthy AI Agents" 課程以了解更多。
## 評估 AI Agents
在部署 AI Agents 前、中、後,建立一個完善的系統來評估你的 AI Agent 是至關重要的。這將確保你的系統與你和用戶的目標保持一致。
評估 AI Agent 時,不僅需要評估代理的輸出,還需要評估 AI Agent 所運行的整個系統。這包括但不限於:
- 初始模型請求。
- 代理識別用戶意圖的能力。
- 代理選擇正確工具執行任務的能力。
- 工具對代理請求的回應。
- 代理解讀工具回應的能力。
- 用戶對代理回應的反饋。
這樣可以讓你更模塊化地識別改進的空間,並更高效地監控模型、提示詞、工具以及其他組件的變更效果。
## AI Agents 的常見問題與潛在解決方案
| **問題** | **潛在解決方案** |
| ---------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AI Agent 無法穩定執行任務 | - 精煉給 AI Agent 的提示詞,明確目標。<br>- 確定是否可以將任務分解為子任務,並由多個代理處理。 |
| AI Agent 進入無限循環 | - 確保設置清晰的終止條件,讓代理知道何時結束流程。<br>- 對於需要推理和計劃的複雜任務,使用專為推理任務設計的大型模型。 |
| AI Agent 工具調用效果不佳 | - 在代理系統外測試並驗證工具的輸出。<br>- 優化工具的參數設置、提示詞和命名。 |
| 多代理系統無法穩定運行 | - 精煉給每個代理的提示詞,確保它們具體且彼此區分明確。<br>- 構建一個層級系統,使用 "路由" 或控制代理來決定哪個代理最適合處理任務。 |
## 成本管理
以下是一些管理 AI Agent 部署成本的策略:
- **緩存回應** - 識別常見的請求和任務,提前提供回應,避免它們經過你的代理系統。你甚至可以實現一個流程,使用更基礎的 AI 模型來判斷請求與緩存請求的相似度。
- **使用小型模型** - 小型語言模型 (SLMs) 在某些代理場景中表現良好,並能顯著降低成本。如前所述,建立一個評估系統來比較小型模型與大型模型的性能,是了解 SLM 是否適合你場景的最佳方法。
- **使用路由模型** - 一種相似的策略是使用多樣化的模型和規模。你可以使用 LLM/SLM 或無伺服器函數根據任務複雜度來路由請求,將其分配給最合適的模型。這樣既能降低成本,又能確保在適當的任務上保持性能。
## 恭喜
這是 "AI Agents for Beginners" 的最後一課。
我們計劃根據反饋和這個快速增長的行業變化繼續添加新課程,請在不久的將來再次訪問。
如果你想繼續學習並構建 AI Agents,歡迎加入 [Azure AI Community Discord](https://discord.gg/kzRShWzttr)。
我們在那裡舉辦工作坊、社區圓桌會議和 "問我任何事" 的互動環節。
我們還有一個學習資源集合,其中包含更多幫助你開始在生產環境中構建 AI Agents 的材料。
**免責聲明**:
本文件是使用機器翻譯人工智能服務進行翻譯的。儘管我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文文件為權威來源。如涉及關鍵信息,建議尋求專業人工翻譯。我們對因使用本翻譯而引起的任何誤解或誤釋不承擔責任。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/hk/10-ai-agents-production/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/10-ai-agents-production/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 2569
} |
# コースセットアップ
## はじめに
このレッスンでは、このコースのコードサンプルを実行する方法を説明します。
## 必要条件
- GitHubアカウント
- Python 3.12以上
## このリポジトリをクローンまたはフォークする
まず最初に、GitHubリポジトリをクローンまたはフォークしてください。これにより、コース教材の自分専用のバージョンが作成され、コードを実行、テスト、調整できるようになります。
以下のリンクをクリックして[リポジトリをフォークする](https://github.com/microsoft/ai-agents-for-beginners/fork)ことができます。
これで、以下のように自分専用のフォークされたコースバージョンが作成されます:

## GitHubパーソナルアクセストークン(PAT)の取得
現在、このコースではGitHub Models Marketplaceを利用して、AIエージェントを作成するための大規模言語モデル(LLMs)への無料アクセスを提供しています。
このサービスにアクセスするには、GitHubのパーソナルアクセストークンを作成する必要があります。
トークンを作成するには、GitHubアカウントの[Personal Access Tokens設定](https://github.com/settings/personal-access-tokens)にアクセスしてください。
画面左側の `Fine-grained tokens` オプションを選択します。
次に `Generate new token` を選択してください。

作成した新しいトークンをコピーしてください。このトークンを、このコースに含まれる `.env` ファイルに追加します。
## 環境変数に追加する
`.env` ファイルを作成するには、以下のコマンドをターミナルで実行してください:
```bash
cp .env.example .env
```
これにより、サンプルファイルがコピーされ、ディレクトリ内に `.env` が作成されます。
そのファイルを開き、作成したトークンを `.env` ファイルの `GITHUB_TOKEN=` フィールドに貼り付けてください。
## 必要なパッケージのインストール
コードを実行するために必要なPythonパッケージをすべてインストールするには、以下のコマンドをターミナルに入力してください。
Python仮想環境を作成することをお勧めします。これにより、競合や問題を回避できます。
```bash
pip install -r requirements.txt
```
これで必要なPythonパッケージがインストールされます。
これでコードを実行する準備が整いました。AIエージェントの世界について学ぶことを楽しんでください!
セットアップの実行中に問題が発生した場合は、[Azure AI Community Discord](https://discord.gg/kzRShWzttr)に参加するか、[Issueを作成](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst)してください。
```
**免責事項**:
この文書は、AIによる機械翻訳サービスを使用して翻訳されています。正確さを期すよう努めておりますが、自動翻訳には誤りや不正確な部分が含まれる可能性があります。原文(元の言語で記載された文書)が正式な情報源として優先されるべきです。重要な情報については、専門の人間による翻訳をお勧めします。この翻訳の利用により生じた誤解や解釈の相違について、当方は一切の責任を負いません。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/00-course-setup/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/00-course-setup/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 1969
} |
# AIエージェントとそのユースケース入門
「初心者向けAIエージェント」コースへようこそ!このコースでは、AIエージェントを構築するための基本的な知識と実践的なサンプルを学べます。
[Azure AI Discord Community](https://discord.gg/kzRShWzttr) に参加して、他の学習者やAIエージェント開発者と交流し、このコースに関する質問を自由にしてください。
このコースを始めるにあたり、まずAIエージェントとは何か、そしてそれを私たちのアプリケーションやワークフローでどのように活用できるかを理解するところから始めます。
## はじめに
このレッスンでは以下を学びます:
- AIエージェントとは何か、そしてその種類にはどのようなものがあるのか?
- AIエージェントが適しているユースケースとは?また、それがどのように役立つのか?
- エージェントソリューションを設計する際の基本的な構成要素は何か?
## 学習目標
このレッスンを修了すると、以下ができるようになります:
- AIエージェントの概念を理解し、他のAIソリューションとの違いを把握する。
- AIエージェントを最も効率的に活用する。
- ユーザーと顧客の両方にとって生産的なエージェントソリューションを設計する。
## AIエージェントの定義と種類
### AIエージェントとは?
AIエージェントは、**大規模言語モデル(LLM)** に **ツールや知識へのアクセス** を提供し、その能力を拡張することで **アクションを実行** できるようにする **システム** です。
この定義を分解してみましょう:
- **システム** - エージェントを単一のコンポーネントとしてではなく、複数のコンポーネントから成るシステムとして考えることが重要です。AIエージェントの基本的な構成要素は以下の通りです:
- **環境** - AIエージェントが動作する定義された空間。例えば、旅行予約のAIエージェントの場合、環境はエージェントがタスクを完了するために使用する旅行予約システムとなります。
- **センサー** - 環境には情報があり、フィードバックを提供します。AIエージェントはセンサーを使用して、環境の現在の状態に関する情報を収集・解釈します。旅行予約エージェントの例では、ホテルの空室状況や航空券の価格などの情報を旅行予約システムから取得します。
- **アクチュエーター** - AIエージェントが環境の現在の状態を受け取った後、そのタスクに応じて環境を変化させるためにどのようなアクションを実行するかを決定します。旅行予約エージェントの場合、ユーザーのために空室を予約するアクションが該当します。

**大規模言語モデル** - エージェントの概念自体はLLMが誕生する以前から存在していましたが、LLMを用いたAIエージェント構築の利点は、人間の言語やデータを解釈する能力にあります。この能力により、LLMは環境情報を解釈し、環境を変化させるための計画を立てることができます。
**アクションの実行** - AIエージェントシステムの外では、LLMはユーザーのプロンプトに基づいてコンテンツや情報を生成する状況に限定されます。一方で、AIエージェントシステム内では、LLMはユーザーのリクエストを解釈し、環境内で利用可能なツールを使用することでタスクを達成することができます。
**ツールへのアクセス** - LLMがアクセスできるツールは、1) その動作環境と、2) AIエージェントの開発者によって定義されます。旅行エージェントの例では、エージェントのツールは予約システムで利用可能な操作によって制限される場合や、開発者がフライト予約に限定する場合があります。
**知識** - 環境から提供される情報以外にも、AIエージェントは他のシステム、サービス、ツール、さらには他のエージェントから知識を取得することができます。旅行エージェントの例では、顧客データベースに保存されたユーザーの旅行の好みに関する情報が該当します。
### AIエージェントの種類
AIエージェントの一般的な定義を理解したところで、特定のエージェントタイプと、それらが旅行予約AIエージェントにどのように適用されるかを見てみましょう。
| **エージェントタイプ** | **説明** | **例** |
| ----------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **単純反射エージェント** | 定義されたルールに基づいて即座にアクションを実行します。 | 旅行エージェントがメールの文脈を解釈し、旅行の苦情をカスタマーサービスに転送します。 |
| **モデルベース反射エージェント** | 世界のモデルとその変化に基づいてアクションを実行します。 | 旅行エージェントが過去の価格データへのアクセスを基に、大幅な価格変動があるルートを優先します。 |
| **目標ベースエージェント** | 目標を解釈し、それを達成するためのアクションを決定して計画を立てます。 | 旅行エージェントが現在地から目的地までの移動手段(車、公共交通機関、フライト)を決定し、旅行を予約します。 |
| **効用ベースエージェント** | 好みを考慮し、数値的にトレードオフを比較して目標を達成する方法を決定します。 | 旅行エージェントが利便性とコストを比較して最大効用を得るように旅行を予約します。 |
| **学習エージェント** | フィードバックに応じて行動を調整し、時間とともに改善します。 | 旅行エージェントが旅行後のアンケートから顧客のフィードバックを利用し、将来の予約を調整して改善します。 |
| **階層型エージェント** | 複数のエージェントが階層的に構成され、高次のエージェントがタスクをサブタスクに分割し、下位エージェントがそれを完了します。 | 旅行エージェントが旅行をキャンセルする際、タスクを(例えば、特定の予約のキャンセルなど)サブタスクに分割し、下位エージェントがそれを完了し、高次エージェントに報告します。 |
| **マルチエージェントシステム(MAS)** | 協力的または競争的に、エージェントが独立してタスクを完了します。 | 協力的: 複数のエージェントがホテル、フライト、エンターテイメントなど特定の旅行サービスを予約します。競争的: 複数のエージェントが共有のホテル予約カレンダーを管理し、顧客の予約を競合しながら進めます。 |
## AIエージェントを使用するタイミング
前のセクションでは、旅行エージェントのユースケースを使用して、さまざまな種類のエージェントが旅行予約の異なるシナリオでどのように使用されるかを説明しました。このアプリケーションはコース全体で引き続き使用します。
次に、AIエージェントが最適に使用されるユースケースの種類を見てみましょう:

- **オープンエンドな問題** - ワークフローに常にハードコードできないため、LLMがタスクを完了するために必要なステップを判断する必要がある場合。
- **複数ステップのプロセス** - ツールや情報を複数のターンにわたって使用する必要がある、ある程度の複雑さを持つタスク。
- **時間とともに改善** - 環境やユーザーからのフィードバックを受け取り、より良いユーティリティを提供するために改善できるタスク。
AIエージェントを使用する際のさらなる考慮事項については、「信頼できるAIエージェントの構築」レッスンで詳しく学びます。
## エージェントソリューションの基本
### エージェントの開発
AIエージェントシステムを設計する最初のステップは、ツール、アクション、動作を定義することです。このコースでは、**Azure AI Agent Service** を使用してエージェントを定義する方法に焦点を当てます。このサービスには以下のような特徴があります:
- OpenAI、Mistral、Llamaなどのオープンモデルの選択
- Tripadvisorなどのプロバイダーを通じたライセンスデータの利用
- 標準化されたOpenAPI 3.0ツールの利用
### エージェントパターン
LLMとのコミュニケーションはプロンプトを通じて行われます。AIエージェントは半自律的な性質を持つため、環境の変化後に手動でLLMを再プロンプトする必要がない場合があります。このため、複数ステップでLLMをよりスケーラブルにプロンプトするための **エージェントパターン** を使用します。
このコースでは、現在人気のあるエージェントパターンをいくつか学びます。
### エージェントフレームワーク
エージェントフレームワークを使用すると、開発者はコードを通じてエージェントパターンを実装できます。これらのフレームワークは、テンプレート、プラグイン、ツールを提供し、AIエージェントのコラボレーションをより良くします。これにより、AIエージェントシステムの可観測性やトラブルシューティングの能力が向上します。
このコースでは、研究主導のAutoGenフレームワークと、Semantic Kernelのプロダクション対応エージェントフレームワークを探ります。
**免責事項**:
この文書は、機械翻訳AIサービスを使用して翻訳されています。正確性を追求していますが、自動翻訳には誤りや不正確さが含まれる可能性があります。元の言語で記載された原文が正式な情報源と見なされるべきです。重要な情報については、専門の人間による翻訳を推奨します。この翻訳の利用によって生じる誤解や解釈の誤りについて、当方は一切の責任を負いません。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/01-intro-to-ai-agents/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/01-intro-to-ai-agents/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 6455
} |
# AIエージェントフレームワークを探る
AIエージェントフレームワークは、AIエージェントの作成、展開、管理を簡素化するために設計されたソフトウェアプラットフォームです。これらのフレームワークは、開発者にあらかじめ構築されたコンポーネント、抽象化、およびツールを提供し、複雑なAIシステムの開発を効率化します。
これらのフレームワークは、AIエージェント開発における共通の課題に対して標準化されたアプローチを提供することで、開発者がアプリケーションの独自の側面に集中できるようにします。また、AIシステムのスケーラビリティ、アクセシビリティ、効率性を向上させます。
## はじめに
このレッスンでは以下について学びます:
- AIエージェントフレームワークとは何か、そしてそれによって開発者が何を実現できるのか?
- チームがこれらをどのように活用して、エージェントの能力を迅速にプロトタイプ化、反復、改善できるのか?
- Microsoftが提供するフレームワークとツール([Autogen](https://aka.ms/ai-agents/autogen) / [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) / [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service))の違いは何か?
- 既存のAzureエコシステムツールを直接統合できるのか、それともスタンドアロンのソリューションが必要なのか?
- Azure AI Agentsサービスとは何で、それがどのように役立つのか?
## 学習目標
このレッスンの目標は以下を理解することです:
- AI開発におけるAIエージェントフレームワークの役割。
- AIエージェントフレームワークを活用してインテリジェントエージェントを構築する方法。
- AIエージェントフレームワークによって可能になる主要な機能。
- Autogen、Semantic Kernel、Azure AI Agent Serviceの違い。
## AIエージェントフレームワークとは何か、そしてそれによって開発者が何を実現できるのか?
従来のAIフレームワークは、AIをアプリに統合し、それらのアプリを以下の方法で改善するのに役立ちます:
- **パーソナライズ**: AIはユーザーの行動や好みを分析し、パーソナライズされた推奨、コンテンツ、体験を提供します。
例: Netflixのようなストリーミングサービスは、視聴履歴に基づいて映画や番組を提案し、ユーザーのエンゲージメントと満足度を向上させます。
- **自動化と効率化**: AIは反復的なタスクを自動化し、ワークフローを合理化し、運用効率を向上させます。
例: カスタマーサービスアプリは、AI搭載のチャットボットを使用して一般的な問い合わせを処理し、応答時間を短縮し、人間のエージェントがより複雑な問題に集中できるようにします。
- **ユーザーエクスペリエンスの向上**: AIは音声認識、自然言語処理、予測テキストなどのインテリジェント機能を提供することで、全体的なユーザー体験を向上させます。
例: SiriやGoogleアシスタントのようなバーチャルアシスタントは、AIを使用して音声コマンドを理解し応答し、ユーザーがデバイスと簡単にやり取りできるようにします。
### それは素晴らしいことのように聞こえますが、なぜAIエージェントフレームワークが必要なのでしょうか?
AIエージェントフレームワークは、単なるAIフレームワーク以上のものを表しています。それは、特定の目標を達成するために、ユーザー、他のエージェント、環境とやり取りできるインテリジェントエージェントの作成を可能にするように設計されています。これらのエージェントは、自律的な行動を示し、意思決定を行い、変化する条件に適応することができます。AIエージェントフレームワークによって可能になる主要な機能をいくつか見てみましょう:
- **エージェントの協調と調整**: 複数のAIエージェントを作成し、それらが協力し、通信し、調整して複雑なタスクを解決することを可能にします。
- **タスクの自動化と管理**: 複数ステップのワークフローの自動化、タスクの委任、エージェント間の動的タスク管理の仕組みを提供します。
- **コンテキストの理解と適応**: エージェントがコンテキストを理解し、変化する環境に適応し、リアルタイムの情報に基づいて意思決定を行う能力を備えています。
要するに、エージェントを活用することで、より多くのことを行い、自動化を次のレベルに引き上げ、環境から学び適応できるよりインテリジェントなシステムを作成できるのです。
## エージェントの能力を迅速にプロトタイプ化、反復、改善するには?
この分野は急速に進化していますが、ほとんどのAIエージェントフレームワークに共通する点がいくつかあります。それは、モジュール型コンポーネント、協調ツール、リアルタイム学習です。以下にそれらを詳しく見ていきましょう:
- **モジュール型コンポーネントの利用**: AIフレームワークは、プロンプト、パーサー、メモリ管理などのあらかじめ構築されたコンポーネントを提供します。
- **協調ツールの活用**: 特定の役割やタスクを持つエージェントを設計し、協調的なワークフローをテストして改善します。
- **リアルタイムで学ぶ**: フィードバックループを実装し、エージェントがインタラクションから学び、動的に行動を調整します。
### モジュール型コンポーネントの利用
LangChainやMicrosoft Semantic Kernelのようなフレームワークは、プロンプト、パーサー、メモリ管理などのあらかじめ構築されたコンポーネントを提供します。
**チームがこれらを活用する方法**: チームはこれらのコンポーネントを迅速に組み立てて、ゼロから始めることなく機能的なプロトタイプを作成し、迅速な実験と反復を可能にします。
**実際の動作方法**: あらかじめ構築されたパーサーを使用してユーザー入力から情報を抽出し、メモリモジュールを使用してデータを保存および取得し、プロンプトジェネレーターを使用してユーザーと対話することができます。これらすべてをゼロから構築する必要はありません。
**コード例**: 以下は、あらかじめ構築されたパーサーを使用してユーザー入力から情報を抽出する方法の例です:
```python
from langchain import Parser
parser = Parser()
user_input = "Book a flight from New York to London on July 15th"
parsed_data = parser.parse(user_input)
print(parsed_data)
# Output: {'origin': 'New York', 'destination': 'London', 'date': 'July 15th'}
```
この例からわかるように、あらかじめ構築されたパーサーを活用して、フライト予約リクエストの出発地、目的地、日付などの重要な情報をユーザー入力から抽出できます。このモジュール型アプローチにより、高レベルのロジックに集中することができます。
### 協調ツールの活用
CrewAIやMicrosoft Autogenのようなフレームワークは、複数のエージェントを作成して連携させることを容易にします。
**チームがこれらを活用する方法**: チームは特定の役割やタスクを持つエージェントを設計し、協調的なワークフローをテストして洗練し、システム全体の効率を向上させることができます。
**実際の動作方法**: データ取得、分析、意思決定などの特定の機能を持つエージェントチームを作成できます。これらのエージェントは通信し、情報を共有して、ユーザーの質問に答えたり、タスクを完了したりする共通の目標を達成します。
**コード例(Autogen)**:
```python
# creating agents, then create a round robin schedule where they can work together, in this case in order
# Data Retrieval Agent
# Data Analysis Agent
# Decision Making Agent
agent_retrieve = AssistantAgent(
name="dataretrieval",
model_client=model_client,
tools=[retrieve_tool],
system_message="Use tools to solve tasks."
)
agent_analyze = AssistantAgent(
name="dataanalysis",
model_client=model_client,
tools=[analyze_tool],
system_message="Use tools to solve tasks."
)
# conversation ends when user says "APPROVE"
termination = TextMentionTermination("APPROVE")
user_proxy = UserProxyAgent("user_proxy", input_func=input)
team = RoundRobinGroupChat([agent_retrieve, agent_analyze, user_proxy], termination_condition=termination)
stream = team.run_stream(task="Analyze data", max_turns=10)
# Use asyncio.run(...) when running in a script.
await Console(stream)
```
上記のコードでは、複数のエージェントがデータを分析するタスクを協調して実行する例を示しています。それぞれのエージェントが特定の機能を果たし、エージェントを調整して目標を達成します。専用の役割を持つエージェントを作成することで、タスクの効率とパフォーマンスを向上させることができます。
### リアルタイムで学ぶ
高度なフレームワークは、リアルタイムでのコンテキスト理解と適応機能を提供します。
**チームがこれらを活用する方法**: チームはフィードバックループを実装し、エージェントがインタラクションから学び、動的に行動を調整することで、能力の継続的な向上と洗練を実現します。
**実際の動作方法**: エージェントはユーザーのフィードバック、環境データ、タスクの結果を分析して知識ベースを更新し、意思決定アルゴリズムを調整し、時間とともにパフォーマンスを向上させます。この反復学習プロセスにより、エージェントは変化する条件やユーザーの好みに適応し、システム全体の効果を向上させます。
## Autogen、Semantic Kernel、Azure AI Agent Serviceの違いとは?
これらのフレームワークを比較する方法はいくつかありますが、その設計、機能、対象ユースケースに基づいて主な違いを見てみましょう。
### Autogen
Microsoft ResearchのAI Frontiers Labによって開発されたオープンソースフレームワークです。イベント駆動型の分散型エージェンティックアプリケーションに焦点を当てており、複数のLLMやSLM、ツール、高度なマルチエージェント設計パターンをサポートします。
Autogenは、エージェントというコアコンセプトに基づいて構築されています。エージェントとは、環境を認識し、意思決定を行い、特定の目標を達成するために行動を起こす自律的なエンティティです。エージェントは非同期メッセージを通じて通信し、独立して並列に動作することで、システムのスケーラビリティと応答性を向上させます。
エージェントは[アクターモデル](https://en.wikipedia.org/wiki/Actor_model)に基づいています。Wikipediaによると、アクターとは_メッセージを受信した際にローカルな意思決定を行い、新しいアクターを作成し、さらなるメッセージを送信し、次に受信するメッセージへの応答方法を決定できる並行計算の基本構成要素_です。
**ユースケース**: コード生成、データ分析タスクの自動化、計画および研究機能のためのカスタムエージェントの構築。
Autogenの重要なコアコンセプトについて以下に示します:
- **エージェント**
- エージェントは、メッセージ通信、自身の状態の保持、受信メッセージや状態変化に応じた行動を行います。
- 例: チャットエージェントの作成
```python
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.messages import TextMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient
class MyAssistant(RoutedAgent):
def __init__(self, name: str) -> None:
super().__init__(name)
model_client = OpenAIChatCompletionClient(model="gpt-4o")
self._delegate = AssistantAgent(name, model_client=model_client)
@message_handler
async def handle_my_message_type(self, message: MyMessageType, ctx: MessageContext) -> None:
print(f"{self.id.type} received message: {message.content}")
response = await self._delegate.on_messages(
[TextMessage(content=message.content, source="user")], ctx.cancellation_token
)
print(f"{self.id.type} responded: {response.chat_message.content}")
```
ここでは、`MyAssistant`というエージェントが作成されています。
エージェントタイプをAutogenに登録してプログラムを開始します:
```python
# main.py
runtime = SingleThreadedAgentRuntime()
await MyAgent.register(runtime, "my_agent", lambda: MyAgent())
runtime.start() # Start processing messages in the background.
await runtime.send_message(MyMessageType("Hello, World!"), AgentId("my_agent", "default"))
```
上記では、エージェントが登録され、メッセージを送信することで応答を得ています。
- **マルチエージェント**
- Autogenは複数のエージェントを作成し、それらが連携して複雑なタスクを効率的に解決する仕組みを提供します。
```python
editor_description = "Editor for planning and reviewing the content."
# Example of declaring an Agent
editor_agent_type = await EditorAgent.register(
runtime,
editor_topic_type, # Using topic type as the agent type.
lambda: EditorAgent(
description=editor_description,
group_chat_topic_type=group_chat_topic_type,
model_client=OpenAIChatCompletionClient(
model="gpt-4o-2024-08-06",
# api_key="YOUR_API_KEY",
),
),
)
# remaining declarations shortened for brevity
# Group chat
group_chat_manager_type = await GroupChatManager.register(
runtime,
"group_chat_manager",
lambda: GroupChatManager(
participant_topic_types=[writer_topic_type, illustrator_topic_type, editor_topic_type, user_topic_type],
model_client=OpenAIChatCompletionClient(
model="gpt-4o-2024-08-06",
# api_key="YOUR_API_KEY",
),
participant_descriptions=[
writer_description,
illustrator_description,
editor_description,
user_description
],
),
)
```
上記の例では、`GroupChatManager`がエージェント間のやり取りを調整しています。
- **エージェントランタイム**
- エージェント間の通信、アイデンティティとライフサイクルの管理、セキュリティ境界の強制を行います。
- **スタンドアロンランタイム**
単一プロセスアプリケーション向け。

- **分散エージェントランタイム**
マルチプロセスアプリケーション向け。

### Semantic Kernel + エージェントフレームワーク
Semantic Kernelには以下のコアコンセプトがあります:
- **接続**: 外部AIサービスやデータソースとのインターフェース。
```csharp
using Microsoft.SemanticKernel;
// Create kernel
var builder = Kernel.CreateBuilder();
// Add a chat completion service:
builder.Services.AddAzureOpenAIChatCompletion(
"your-resource-name",
"your-endpoint",
"your-resource-key",
"deployment-model");
var kernel = builder.Build();
```
上記はAzure OpenAI Chat Completionサービスへの接続例です。
- **プラグイン**: アプリケーションで使用可能な関数をカプセル化。
```csharp
var userInput = Console.ReadLine();
// Define semantic function inline.
string skPrompt = @"Summarize the provided unstructured text in a sentence that is easy to understand.
Text to summarize: {{$userInput}}";
// Register the function
kernel.CreateSemanticFunction(
promptTemplate: skPrompt,
functionName: "SummarizeText",
pluginName: "SemanticFunctions"
);
```
Semantic Kernelは、提供されたセマンティック情報に基づいて適切な関数を呼び出します。
- **ネイティブ関数**: フレームワークが直接呼び出せる関数。
```csharp
public class NativeFunctions {
[SKFunction, Description("Retrieve content from local file")]
public async Task<string> RetrieveLocalFile(string fileName, int maxSize = 5000)
{
string content = await File.ReadAllTextAsync(fileName);
if (content.Length <= maxSize) return content;
return content.Substring(0, maxSize);
}
}
//Import native function
string plugInName = "NativeFunction";
string functionName = "RetrieveLocalFile";
var nativeFunctions = new NativeFunctions();
kernel.ImportFunctions(nativeFunctions, plugInName);
```
- **プランナー**: ユーザー入力に基づいて実行計画を策定。
```csharp
string planDefinition = "Read content from a local file and summarize the content.";
SequentialPlanner sequentialPlanner = new SequentialPlanner(kernel);
string assetsFolder = @"../../assets";
string fileName = Path.Combine(assetsFolder,"docs","06_SemanticKernel", "aci_documentation.txt");
ContextVariables contextVariables = new ContextVariables();
contextVariables.Add("fileName", fileName);
var customPlan = await sequentialPlanner.CreatePlanAsync(planDefinition);
// Execute the plan
KernelResult kernelResult = await kernel.RunAsync(contextVariables, customPlan);
Console.WriteLine($"Summarization: {kernelResult.GetValue<string>()}");
```
- **メモリ**: AIアプリケーションのコンテキスト管理を抽象化。
```csharp
var facts = new Dictionary<string,string>();
facts.Add(
"Azure Machine Learning; https://learn.microsoft.com/azure/machine-learning/",
@"Azure Machine Learning is a cloud service for accelerating and
managing the machine learning project lifecycle. Machine learning professionals,
data scientists, and engineers can use it in their day-to-day workflows"
);
facts.Add(
"Azure SQL Service; https://learn.microsoft.com/azure/azure-sql/",
@"Azure SQL is a family of managed, secure, and intelligent products
that use the SQL Server database engine in the Azure cloud."
);
string memoryCollectionName = "SummarizedAzureDocs";
foreach (var fact in facts) {
await memoryBuilder.SaveReferenceAsync(
collection: memoryCollectionName,
description: fact.Key.Split(";")[1].Trim(),
text: fact.Value,
externalId: fact.Key.Split(";")[2].Trim(),
externalSourceName: "Azure Documentation"
);
}
```
メモリコレクションに情報を保存して活用します。
### Azure AI Agent Service
Azure AI Agent Serviceは、Microsoft Ignite 2024で導入された新しいサービスで、オープンソースLLM(例: Llama 3、Mistral、Cohere)の直接呼び出しをサポートします。
- **エージェント**: "スマート"マイクロサービスとして動作。
```python
agent = project_client.agents.create_agent(
model="gpt-4o-mini",
name="my-agent",
instructions="You are helpful agent",
tools=code_interpreter.definitions,
tool_resources=code_interpreter.resources,
)
```
- **スレッドとメッセージ**: 会話やインタラクションを管理。
```python
thread = project_client.agents.create_thread()
message = project_client.agents.create_message(
thread_id=thread.id,
role="user",
content="Could you please create a bar chart for the operating profit using the following data and provide the file to me? Company A: $1.2 million, Company B: $2.5 million, Company C: $3.0 million, Company D: $1.8 million",
)
# Ask the agent to perform work on the thread
run = project_client.agents.create_and_process_run(thread_id=thread.id, agent_id=agent.id)
# Fetch and log all messages to see the agent's response
messages = project_client.agents.list_messages(thread_id=thread.id)
print(f"Messages: {messages}")
```
- **他のAIフレームワークとの統合**: AutogenやSemantic Kernelと連携可能。
**ユースケース**: エンタープライズ向けのセキュアでスケーラブルなAIエージェント展開に最適。
## これらのフレームワークの違いとは?
以下の表で主な違いをまとめました:
| フレームワーク | フォーカス | コアコンセプト | ユースケース |
|----------------------|-----------------------------------------|--------------------------------------|----------------------------------|
| Autogen | イベント駆動型、分散型エージェンティックアプリケーション | エージェント、ペルソナ、関数、データ | コード生成、データ分析タスク |
| Semantic Kernel | 人間のようなテキスト生成と理解 | エージェント、モジュール型コンポーネント、協調 | 自然言語理解、コンテンツ生成 |
| Azure AI Agent Service | 柔軟なモデル、エンタープライズセキュリティ、ツール呼び出し | モジュール性、協調、プロセスオーケストレーション | セキュアでスケーラブルなAI展開 |
### どのフレームワークを選ぶべき?
> **Q**: コード生成やデータ分析タスクを自動化するプロジェクトに取り組んでいます。どのフレームワークを使用すべきですか?
> **A**: Autogenが適しています。イベント駆動型で分散型エージェンティックアプリケーションに特化しており、高度なマルチエージェント設計パターンをサポートしています。
> **Q**: エンタープライズ
プロジェクト目標に基づいています。自然言語理解、コンテンツ生成に最適です。
- **Azure AI Agent Service**: 柔軟なモデル、エンタープライズ向けのセキュリティメカニズム、データストレージ方法。エンタープライズアプリケーションにおける安全でスケーラブルかつ柔軟なAIエージェントの展開に最適です。
## 既存のAzureエコシステムツールを直接統合できますか、それともスタンドアロンのソリューションが必要ですか?
答えは「はい」です。既存のAzureエコシステムツールをAzure AI Agent Serviceと直接統合できます。特に、このサービスは他のAzureサービスとシームレスに動作するように設計されています。たとえば、Bing、Azure AI Search、Azure Functionsと統合することができます。また、Azure AI Foundryとの深い統合もあります。
AutogenやSemantic Kernelについても、Azureサービスと統合できますが、コードからAzureサービスを呼び出す必要がある場合があります。別の統合方法としては、Azure SDKを使用してエージェントからAzureサービスとやり取りすることも可能です。さらに、前述のように、Azure AI Agent ServiceをAutogenやSemantic Kernelで構築されたエージェントのオーケストレーターとして使用することで、Azureエコシステムへの簡単なアクセスを実現できます。
## 参考文献
- [1] - [Azure Agent Service](https://techcommunity.microsoft.com/blog/azure-ai-services-blog/introducing-azure-ai-agent-service/4298357)
- [2] - [Semantic Kernel and Autogen](https://devblogs.microsoft.com/semantic-kernel/microsofts-agentic-ai-frameworks-autogen-and-semantic-kernel/)
- [3] - [Semantic Kernel Agent Framework](https://learn.microsoft.com/semantic-kernel/frameworks/agent/?pivots=programming-language-csharp)
- [4] - [Azure AI Agent service](https://learn.microsoft.com/azure/ai-services/agents/overview)
- [5] - [Using Azure AI Agent Service with AutoGen / Semantic Kernel to build a multi-agent's solution](https://techcommunity.microsoft.com/blog/educatordeveloperblog/using-azure-ai-agent-service-with-autogen--semantic-kernel-to-build-a-multi-agen/4363121)
**免責事項**:
この文書は、機械ベースのAI翻訳サービスを使用して翻訳されています。正確性を追求しておりますが、自動翻訳にはエラーや不正確な部分が含まれる可能性があります。元の言語で記載された原文を正式な情報源と見なしてください。重要な情報については、専門の人間による翻訳を推奨します。本翻訳の使用に起因する誤解や誤解釈について、当方は一切の責任を負いません。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/02-explore-agentic-frameworks/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/02-explore-agentic-frameworks/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 16610
} |
# AIエージェント設計の原則
## はじめに
AIエージェントシステムを構築する方法はさまざまです。生成AIの設計において曖昧さはバグではなく特徴であるため、エンジニアにとってどこから始めればいいのか分からないことがあります。そこで、私たちは開発者がビジネスニーズを解決するための顧客中心のエージェントシステムを構築できるように、人間中心のUX設計原則を作成しました。これらの設計原則は厳密なアーキテクチャではなく、エージェント体験を定義し構築するチームにとっての出発点です。
一般的に、エージェントは以下を目指すべきです:
- 人間の能力を広げ、スケールさせる(ブレインストーミング、問題解決、自動化など)
- 知識のギャップを埋める(知識分野を短期間で把握する、翻訳など)
- 私たちが個々に他者と協力する際の好みに応じて、コラボレーションを促進しサポートする
- 私たちをより良い自分にしてくれる(例:ライフコーチ/タスクマスターとして、感情の調整やマインドフルネススキルの習得、レジリエンスの構築を助けるなど)
## このレッスンで学ぶこと
- エージェント設計の原則とは何か
- これらの設計原則を実装する際のガイドライン
- 設計原則を活用した具体例
## 学習目標
このレッスンを終えた後、次のことができるようになります:
1. エージェント設計の原則が何であるか説明できる
2. エージェント設計の原則を使用する際のガイドラインを説明できる
3. エージェント設計の原則を活用してエージェントを構築する方法を理解する
## エージェント設計の原則

### エージェント(空間)
これはエージェントが動作する環境を指します。この原則は、物理的およびデジタルの世界でエージェントを設計する際の指針となります。
- **つなげる、壊さない** – 人々を他の人々、イベント、行動可能な知識につなげ、コラボレーションと接続を可能にする。
- エージェントはイベント、知識、人々をつなげる役割を果たします。
- エージェントは人々をより近づけるものであり、人々を置き換えたり軽視するものではありません。
- **簡単にアクセスできるが、時には見えない** – エージェントは主にバックグラウンドで動作し、関連性があり適切なタイミングでのみ私たちに働きかけます。
- エージェントは、どのデバイスやプラットフォームでも認可されたユーザーが簡単に発見・アクセスできるように設計されています。
- エージェントは音声、テキストなどのマルチモーダルな入力と出力をサポートします。
- エージェントは、ユーザーのニーズを感知しながら、前景と背景、能動的と受動的の間をシームレスに移行します。
- エージェントは見えない形で動作することもありますが、そのバックグラウンドでのプロセスや他のエージェントとのコラボレーションはユーザーにとって透明で制御可能です。
### エージェント(時間)
これはエージェントが時間を通じてどのように動作するかを指します。この原則は、過去、現在、未来にわたるエージェントの設計方法を示します。
- **過去**: 状態とコンテキストを含む履歴を反映する。
- エージェントは、イベントや人々、状態だけでなく、より豊かな履歴データの分析に基づいて関連性の高い結果を提供します。
- エージェントは過去のイベントからつながりを生み出し、記憶を積極的に反映して現在の状況に対応します。
- **現在**: 通知以上の働きかけをする。
- エージェントは、人々とのやり取りに包括的なアプローチを取ります。イベントが発生した際、静的な通知や形式的なものを超えて、ユーザーの注意を適切なタイミングで引きつける動的な指針を生成します。
- エージェントはコンテキスト環境、社会的・文化的変化、ユーザーの意図に合わせた情報を提供します。
- エージェントのやり取りは徐々に進化し、長期的にユーザーをエンパワーする複雑さを備えています。
- **未来**: 適応し進化する。
- エージェントはさまざまなデバイス、プラットフォーム、モダリティに適応します。
- エージェントはユーザーの行動やアクセシビリティのニーズに適応し、自由にカスタマイズ可能です。
- エージェントは継続的なユーザーとのやり取りを通じて形成され、進化します。
### エージェント(コア)
これはエージェント設計の中心的な要素です。
- **不確実性を受け入れつつ信頼を構築する**。
- エージェントの不確実性はある程度予想されるものです。不確実性はエージェント設計の重要な要素です。
- 信頼と透明性はエージェント設計の基盤となるレイヤーです。
- エージェントがオン/オフの状態は人間が制御し、エージェントのステータスは常に明確に表示されます。
## これらの原則を実装するためのガイドライン
上記の設計原則を使用する際には、以下のガイドラインを参考にしてください:
1. **透明性**: AIが関与していること、その仕組み(過去のアクションを含む)、フィードバックの方法やシステムの修正方法をユーザーに知らせる。
2. **制御**: ユーザーがシステムやその属性(忘れる機能を含む)をカスタマイズ、好みを指定、個別化し、制御できるようにする。
3. **一貫性**: デバイスやエンドポイント間で一貫したマルチモーダル体験を目指す。可能であれば馴染みのあるUI/UX要素を使用し(例:音声操作のためのマイクアイコン)、ユーザーの認知負荷を可能な限り軽減する(例:簡潔な応答、視覚的補助、‘詳細を学ぶ’コンテンツ)。
## これらの原則とガイドラインを使用して旅行エージェントを設計する方法
旅行エージェントを設計する場合、以下のように設計原則とガイドラインを活用することを考えてみてください:
1. **透明性** – 旅行エージェントがAI対応エージェントであることをユーザーに知らせます。基本的な使い方を説明する(例:「こんにちは」メッセージ、サンプルプロンプト)。これを製品ページに明確に記載します。過去にユーザーが入力したプロンプトのリストを表示します。フィードバック方法(サムズアップ/ダウン、フィードバック送信ボタンなど)を明確にします。エージェントに使用制限やトピック制限がある場合は明確に説明します。
2. **制御** – システムプロンプトなどを使って、エージェントを作成した後にユーザーがどのように修正できるかを明確にします。エージェントの詳細さや文体、話題にしない内容などをユーザーが選べるようにします。関連ファイルやデータ、プロンプト、過去の会話を表示・削除できるようにします。
3. **一貫性** – プロンプトの共有、ファイルや写真の追加、誰かや何かをタグ付けするためのアイコンが標準的で認識しやすいものであることを確認します。ファイルのアップロード/共有にはクリップアイコンを、グラフィックのアップロードには画像アイコンを使用します。
## 追加リソース
- [Practices for Governing Agentic AI Systems | OpenAI](https://openai.com)
- [The HAX Toolkit Project - Microsoft Research](https://microsoft.com)
- [Responsible AI Toolbox](https://responsibleaitoolbox.ai)
```
**免責事項**:
この文書は、機械ベースのAI翻訳サービスを使用して翻訳されています。正確性を追求しておりますが、自動翻訳には誤りや不正確さが含まれる可能性があることをご了承ください。元の言語で作成された原文が、信頼できる正式な情報源とみなされるべきです。重要な情報については、専門の人間による翻訳をお勧めします。本翻訳の使用に起因する誤解や解釈の誤りについて、当方は一切責任を負いません。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/03-agentic-design-patterns/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/03-agentic-design-patterns/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 3681
} |
# ツール利用デザインパターン
## はじめに
このレッスンでは、以下の質問に答えることを目指します:
- ツール利用デザインパターンとは何か?
- どのようなユースケースに適用できるのか?
- デザインパターンを実装するために必要な要素や構成要素は何か?
- 信頼性の高いAIエージェントを構築する際に、ツール利用デザインパターンを使用する際の特別な考慮事項は何か?
## 学習目標
このレッスンを完了すると、次のことができるようになります:
- ツール利用デザインパターンとその目的を定義する。
- ツール利用デザインパターンが適用可能なユースケースを特定する。
- デザインパターンを実装するために必要な主要要素を理解する。
- このデザインパターンを使用するAIエージェントの信頼性を確保するための考慮事項を認識する。
## ツール利用デザインパターンとは?
**ツール利用デザインパターン**は、LLM(大規模言語モデル)に外部ツールと連携する能力を与え、特定の目標を達成することを目的としています。ツールとは、エージェントがアクションを実行するために使用できるコードのことを指します。ツールは、電卓のような単純な関数や、株価検索や天気予報のようなサードパーティサービスへのAPI呼び出しなどがあります。AIエージェントの文脈では、ツールは**モデル生成の関数呼び出し**に応じてエージェントによって実行されるように設計されています。
## 適用できるユースケースは何か?
AIエージェントはツールを活用して、複雑なタスクを完了したり、情報を取得したり、意思決定を行うことができます。ツール利用デザインパターンは、データベースやウェブサービス、コードインタプリタなどの外部システムとの動的なやり取りを必要とするシナリオでよく使用されます。この能力は、以下のようなさまざまなユースケースで役立ちます:
- **動的な情報取得**:エージェントが外部APIやデータベースをクエリし、最新のデータを取得(例:SQLiteデータベースを使ったデータ分析、株価や天気情報の取得)。
- **コードの実行と解釈**:エージェントがコードやスクリプトを実行し、数学的問題を解いたり、レポートを生成したり、シミュレーションを行う。
- **ワークフローの自動化**:タスクスケジューラ、メールサービス、データパイプラインなどのツールを統合して反復的または多段階のワークフローを自動化。
- **カスタマーサポート**:CRMシステム、チケッティングプラットフォーム、ナレッジベースと連携してユーザーの問い合わせに対応。
- **コンテンツ生成と編集**:文法チェッカー、テキスト要約ツール、コンテンツの安全性評価ツールを活用してコンテンツ作成を支援。
## ツール利用デザインパターンを実装するために必要な要素/構成要素は何か?
### 関数/ツール呼び出し
関数呼び出しは、LLMがツールと連携する主要な方法です。「関数」と「ツール」はしばしば同義で使われます。なぜなら、「関数」(再利用可能なコードブロック)が、エージェントがタスクを実行するために使用する「ツール」だからです。関数のコードを呼び出すためには、LLMがユーザーのリクエストを関数の説明と比較する必要があります。そのため、利用可能なすべての関数の説明を含むスキーマをLLMに送信します。LLMはタスクに最も適した関数を選択し、その名前と引数を返します。選択された関数が呼び出され、その応答がLLMに送信され、LLMはその情報を使用してユーザーのリクエストに応答します。
エージェント用に関数呼び出しを実装するためには、以下が必要です:
1. 関数呼び出しをサポートするLLMモデル
2. 関数の説明を含むスキーマ
3. 説明された各関数のコード
以下の例では、特定の都市の現在時刻を取得するプロセスを説明します:
- **関数呼び出しをサポートするLLMの初期化**:
すべてのモデルが関数呼び出しをサポートしているわけではないため、使用するLLMがサポートしていることを確認することが重要です。[Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/how-to/function-calling)は関数呼び出しをサポートしています。Azure OpenAIクライアントを初期化するところから始めましょう。
```python
# Initialize the Azure OpenAI client
client = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2024-05-01-preview"
)
```
- **関数スキーマの作成**:
次に、関数名、関数の機能の説明、関数パラメータの名前と説明を含むJSONスキーマを定義します。このスキーマを上記で作成したクライアントに渡し、サンフランシスコの時刻を見つけるためのユーザーリクエストと一緒に送信します。重要な点は、返されるのは**ツール呼び出し**であり、**最終的な答え**ではないということです。先述したように、LLMはタスクに選択された関数の名前と、それに渡される引数を返します。
```python
# Function description for the model to read
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Get the current time in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
},
"required": ["location"],
},
}
}
]
```
```python
# Initial user message
messages = [{"role": "user", "content": "What's the current time in San Francisco"}]
# First API call: Ask the model to use the function
response = client.chat.completions.create(
model=deployment_name,
messages=messages,
tools=tools,
tool_choice="auto",
)
# Process the model's response
response_message = response.choices[0].message
messages.append(response_message)
print("Model's response:")
print(response_message)
```
```bash
Model's response:
ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_pOsKdUlqvdyttYB67MOj434b', function=Function(arguments='{"location":"San Francisco"}', name='get_current_time'), type='function')])
```
- **タスクを実行するために必要な関数コード**:
LLMが実行すべき関数を選択した後、そのタスクを実行するコードを実装して実行する必要があります。
Pythonで現在時刻を取得するコードを実装します。また、response_messageから関数名と引数を抽出して最終結果を得るコードも記述します。
```python
def get_current_time(location):
"""Get the current time for a given location"""
print(f"get_current_time called with location: {location}")
location_lower = location.lower()
for key, timezone in TIMEZONE_DATA.items():
if key in location_lower:
print(f"Timezone found for {key}")
current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p")
return json.dumps({
"location": location,
"current_time": current_time
})
print(f"No timezone data found for {location_lower}")
return json.dumps({"location": location, "current_time": "unknown"})
```
```python
# Handle function calls
if response_message.tool_calls:
for tool_call in response_message.tool_calls:
if tool_call.function.name == "get_current_time":
function_args = json.loads(tool_call.function.arguments)
time_response = get_current_time(
location=function_args.get("location")
)
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": "get_current_time",
"content": time_response,
})
else:
print("No tool calls were made by the model.")
# Second API call: Get the final response from the model
final_response = client.chat.completions.create(
model=deployment_name,
messages=messages,
)
return final_response.choices[0].message.content
```
```bash
get_current_time called with location: San Francisco
Timezone found for san francisco
The current time in San Francisco is 09:24 AM.
```
関数呼び出しは、ほぼすべてのエージェントのツール利用設計の中心にありますが、ゼロから実装するのは時に困難です。
[レッスン2](../../../02-explore-agentic-frameworks)で学んだように、エージェントフレームワークはツール利用を実装するための事前構築された構成要素を提供してくれます。
### エージェントフレームワークを用いたツール利用の例
- ### **[Semantic Kernel](https://learn.microsoft.com/azure/ai-services/agents/overview)**
Semantic Kernelは、LLMを利用する.NET、Python、Java開発者向けのオープンソースAIフレームワークです。このフレームワークは、関数呼び出しのプロセスを簡素化し、関数とそのパラメータをモデルに自動的に説明する[シリアライズ](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions)というプロセスを通じて実現します。また、モデルとコード間のやり取りを処理する機能も備えています。さらに、Semantic Kernelのようなエージェントフレームワークを使用する利点として、[ファイル検索](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step4_assistant_tool_file_search.py)や[コードインタプリタ](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py)などの事前構築されたツールにアクセスできる点があります。
以下の図は、Semantic Kernelを使用した関数呼び出しのプロセスを示しています:

Semantic Kernelでは、関数/ツールは[プラグイン](https://learn.microsoft.com/semantic-kernel/concepts/plugins/?pivots=programming-language-python)と呼ばれます。`get_current_time` function we saw earlier into a plugin by turning it into a class with the function in it. We can also import the `kernel_function`デコレーターを使用して関数の説明を提供できます。このプラグインをKernelに追加すると、Kernelは関数とそのパラメータを自動的にシリアライズし、スキーマを作成してLLMに送信します。
```python
from semantic_kernel.functions import kernel_function
class GetCurrentTimePlugin:
async def __init__(self, location):
self.location = location
@kernel_function(
description="Get the current time for a given location"
)
def get_current_time(location: str = ""):
...
```
```python
from semantic_kernel import Kernel
# Create the kernel
kernel = Kernel()
# Create the plugin
get_current_time_plugin = GetCurrentTimePlugin(location)
# Add the plugin to the kernel
kernel.add_plugin(get_current_time_plugin)
```
- ### **[Azure AI Agent Service](https://learn.microsoft.com/azure/ai-services/agents/overview)**
Azure AI Agent Serviceは、新しいエージェントフレームワークであり、開発者が高品質で拡張可能なAIエージェントを、安全に構築、デプロイ、スケーリングすることを可能にします。計算リソースやストレージリソースを管理する必要がないため、特にエンタープライズアプリケーションに適しています。
LLM APIを直接使用する場合と比較して、Azure AI Agent Serviceは以下の利点を提供します:
- 自動ツール呼び出し – ツール呼び出しの解析、ツールの呼び出し、応答の処理がすべてサーバーサイドで行われます。
- セキュリティ管理されたデータ – 会話の状態を自分で管理する代わりに、スレッドを使用して必要な情報を保存できます。
- 事前構築されたツール – Bing、Azure AI Search、Azure Functionsなどのデータソースとやり取りするためのツールを使用可能。
Azure AI Agent Serviceで利用可能なツールは以下の2つのカテゴリに分けられます:
1. 知識ツール:
- [Bing Searchによる基盤情報](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/bing-grounding?tabs=python&pivots=overview)
- [ファイル検索](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/file-search?tabs=python&pivots=overview)
- [Azure AI Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-ai-search?tabs=azurecli%2Cpython&pivots=overview-azure-ai-search)
2. アクションツール:
- [関数呼び出し](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/function-calling?tabs=python&pivots=overview)
- [コードインタプリタ](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/code-interpreter?tabs=python&pivots=overview)
- [OpenAI定義ツール](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/openapi-spec?tabs=python&pivots=overview)
- [Azure Functions](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-functions?pivots=overview)
Agent Serviceを使用することで、これらのツールを`toolset`. It also utilizes `threads` which keep track of the history of messages from a particular conversation.
Imagine you are a sales agent at a company called Contoso. You want to develop a conversational agent that can answer questions about your sales data.
The image below illustrates how you could use Azure AI Agent Service to analyze your sales data:

To use any of these tools with the service we can create a client and define a tool or toolset. To implement this practically we can use the Python code below. The LLM will be able to look at the toolset and decide whether to use the user created function, `fetch_sales_data_using_sqlite_query`や、ユーザーリクエストに応じた事前構築されたコードインタプリタと組み合わせて使用することができます。
```python
import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from fecth_sales_data_functions import fetch_sales_data_using_sqlite_query # fetch_sales_data_using_sqlite_query function which can be found in a fecth_sales_data_functions.py file.
from azure.ai.projects.models import ToolSet, FunctionTool, CodeInterpreterTool
project_client = AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(),
conn_str=os.environ["PROJECT_CONNECTION_STRING"],
)
# Initialize function calling agent with the fetch_sales_data_using_sqlite_query function and adding it to the toolset
fetch_data_function = FunctionTool(fetch_sales_data_using_sqlite_query)
toolset = ToolSet()
toolset.add(fetch_data_function)11c90e8cda37025bea4db5c4a59d
# Initialize Code Interpreter tool and adding it to the toolset.
code_interpreter = code_interpreter = CodeInterpreterTool()
toolset = ToolSet()
toolset.add(code_interpreter)
agent = project_client.agents.create_agent(
model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent",
toolset=toolset
)
```
## 信頼性の高いAIエージェントを構築する際に、ツール利用デザインパターンを使用する際の特別な考慮事項は何か?
LLMによって動的に生成されるSQLに関する一般的な懸念は、セキュリティ、特にSQLインジェクションやデータベースの削除や改ざんなどの悪意あるアクションのリスクです。これらの懸念は有効ですが、データベースアクセス権限を適切に設定することで効果的に軽減できます。ほとんどのデータベースでは、データベースを読み取り専用として設定することが推奨されます。PostgreSQLやAzure SQLなどのデータベースサービスでは、アプリに読み取り専用(SELECT)のロールを割り当てるべきです。
アプリを安全な環境で実行することは、さらに保護を強化します。エンタープライズシナリオでは、データは通常、運用システムから抽出され、変換され、読み取り専用のデータベースやデータウェアハウスに保存されます。このアプローチにより、データが安全で、パフォーマンスとアクセス性が最適化され、アプリが制限された読み取り専用アクセスを持つように確保されます。
## 追加リソース
- [Azure AI Agents Service Workshop](https://microsoft.github.io/build-your-first-agent-with-azure-ai-agent-service-workshop/)
- [Contoso Creative Writer Multi-Agent Workshop](https://github.com/Azure-Samples/contoso-creative-writer/tree/main/docs/workshop)
- [Semantic Kernel Function Calling Tutorial](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions)
- [Semantic Kernel Code Interpreter](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py)
- [Autogen Tools](https://microsoft.github.io/autogen/dev/user-guide/core-user-guide/components/tools.html)
```
**免責事項**:
この文書は、機械ベースのAI翻訳サービスを使用して翻訳されています。正確性を追求しておりますが、自動翻訳には誤りや不正確さが含まれる可能性があることをご了承ください。元の言語で記載された原文が正式な情報源とみなされるべきです。重要な情報については、専門の人間による翻訳をお勧めします。本翻訳の使用に起因する誤解や解釈の誤りについて、当社は一切の責任を負いません。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/04-tool-use/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/04-tool-use/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 13811
} |
# エージェンティックRAG
このレッスンでは、エージェンティック・リトリーバル・オーグメンテッド・ジェネレーション(Agentic RAG)について包括的に解説します。Agentic RAGは、新たなAIパラダイムで、大規模言語モデル(LLM)が外部ソースから情報を取得しながら、自律的に次のステップを計画する仕組みです。従来の静的な「検索してから読む」パターンとは異なり、Agentic RAGでは、ツールや関数の呼び出し、構造化された出力を交えた反復的なLLM呼び出しが行われます。システムは結果を評価し、クエリを洗練し、必要に応じて追加のツールを呼び出し、満足のいく解決策が得られるまでこのサイクルを続けます。
## はじめに
このレッスンでは以下を学びます:
- **エージェンティックRAGを理解する:** 大規模言語モデル(LLM)が外部データソースから情報を取得しながら、自律的に次のステップを計画する新しいAIパラダイムについて学ぶ
- **反復的な「メーカー・チェッカー」スタイルを把握する:** ツールや関数呼び出し、構造化された出力を交えた反復的なLLM呼び出しのループを理解し、正確性の向上や不完全なクエリの処理方法を学ぶ
- **実用的な応用例を探る:** 正確性が最優先される環境、複雑なデータベースの操作、長時間のワークフローなど、Agentic RAGが活躍するシナリオを特定する
## 学習目標
このレッスンを修了すると、以下を理解し、実践できるようになります:
- **エージェンティックRAGの理解:** 大規模言語モデル(LLM)が外部データソースから情報を取得しながら、自律的に次のステップを計画する新しいAIパラダイムについて学ぶ
- **反復的な「メーカー・チェッカー」スタイル:** ツールや関数呼び出し、構造化された出力を交えた反復的なLLM呼び出しのループを把握し、不完全なクエリの処理や正確性の向上を目指す
- **推論プロセスの所有:** 問題へのアプローチを事前定義されたパスに頼らず、自律的に決定するシステムの能力を理解する
- **ワークフロー:** エージェンティックモデルが市場動向レポートを取得し、競合他社のデータを特定し、内部販売指標を相関させ、結果を統合し、戦略を評価する流れを理解する
- **反復ループ、ツール統合、メモリ:** システムが反復的なインタラクションパターンに依存し、ステップ間で状態とメモリを維持し、繰り返しを避けながら情報に基づいた意思決定を行う方法を学ぶ
- **失敗モードの処理と自己修正:** クエリの再試行や診断ツールの使用、人間の監視に頼るなど、システムの強力な自己修正メカニズムを探る
- **エージェンシーの限界:** ドメイン固有の自律性、インフラストラクチャへの依存、ガードレールの尊重に焦点を当て、Agentic RAGの限界を理解する
- **実用的な使用例と価値:** 正確性が重要な環境、複雑なデータベース操作、長時間のワークフローなど、Agentic RAGが活躍するシナリオを特定する
- **ガバナンス、透明性、信頼:** 説明可能な推論、バイアス制御、人間による監視の重要性を学ぶ
## Agentic RAGとは?
エージェンティック・リトリーバル・オーグメンテッド・ジェネレーション(Agentic RAG)は、大規模言語モデル(LLM)が外部ソースから情報を取得しながら、自律的に次のステップを計画する新たなAIパラダイムです。従来の静的な「検索してから読む」パターンとは異なり、Agentic RAGでは、ツールや関数呼び出し、構造化された出力を交えた反復的なLLM呼び出しが行われます。システムは結果を評価し、クエリを洗練し、必要に応じて追加のツールを呼び出し、満足のいく解決策が得られるまでこのサイクルを続けます。この反復的な「メーカー・チェッカー」スタイルは、正確性を向上させ、不完全なクエリを処理し、高品質な結果を保証します。
システムは推論プロセスを積極的に管理し、失敗したクエリを書き直し、異なる検索方法を選択し、複数のツール(Azure AI Searchのベクター検索、SQLデータベース、カスタムAPIなど)を統合して最終的な回答を完成させます。エージェンティックシステムの際立った特徴は、推論プロセスを自ら管理できる点です。従来のRAG実装では事前定義されたパスに依存しますが、エージェンティックシステムは、見つかった情報の質に基づいて次のステップの順序を自律的に決定します。
## エージェンティック・リトリーバル・オーグメンテッド・ジェネレーション(Agentic RAG)の定義
エージェンティック・リトリーバル・オーグメンテッド・ジェネレーション(Agentic RAG)は、LLMが外部データソースから情報を取得するだけでなく、自律的に次のステップを計画するAI開発の新しいパラダイムです。従来の静的な「検索してから読む」パターンや慎重にスクリプト化されたプロンプトシーケンスとは異なり、Agentic RAGは、ツールや関数呼び出し、構造化された出力を交えた反復的なLLM呼び出しのループを含みます。各ステップで、システムは得られた結果を評価し、クエリを洗練するかどうかを決定し、必要に応じて追加のツールを呼び出し、満足のいく解決策が得られるまでこのサイクルを続けます。
この反復的な「メーカー・チェッカー」スタイルの操作は、正確性を向上させ、構造化データベース(例:NL2SQL)に対する不完全なクエリを処理し、バランスの取れた高品質な結果を保証するよう設計されています。慎重に設計されたプロンプトチェーンにのみ依存するのではなく、システムは推論プロセスを積極的に管理します。失敗したクエリを書き直し、異なる検索方法を選択し、複数のツール(Azure AI Searchのベクター検索、SQLデータベース、カスタムAPIなど)を統合して最終的な回答を完成させます。これにより、複雑なオーケストレーションフレームワークの必要性がなくなります。代わりに、「LLM呼び出し → ツール使用 → LLM呼び出し → …」という比較的シンプルなループで洗練された、根拠のある出力を得ることができます。

## 推論プロセスの所有
システムが「エージェンティック」と見なされる際立った特徴は、推論プロセスを自ら管理できる能力にあります。従来のRAG実装では、モデルがどの情報をいつ取得するかを事前に定義されたチェーン・オブ・ソートに依存することが一般的です。しかし、本当にエージェンティックなシステムでは、問題へのアプローチを内部で決定します。それは単なるスクリプトの実行ではなく、見つかった情報の質に基づいて次のステップの順序を自律的に決定します。
たとえば、製品発売戦略を作成するよう求められた場合、エージェンティックモデルは以下を自律的に決定します:
1. Bing Web Groundingを使用して現在の市場動向レポートを取得する
2. Azure AI Searchを使用して関連する競合データを特定する
3. Azure SQL Databaseを用いて過去の内部販売指標を相関させる
4. Azure OpenAI Serviceを通じて統合された戦略を作成する
5. 戦略のギャップや矛盾を評価し、必要に応じて再度情報を取得する
これらすべてのステップ(クエリの洗練、情報源の選択、回答に「満足」するまでの反復)は、モデルが自ら決定するものであり、人間が事前にスクリプト化したものではありません。
## 反復ループ、ツール統合、メモリ

エージェンティックシステムは、ループ型のインタラクションパターンに依存しています:
- **初回呼び出し:** ユーザーの目的(ユーザープロンプト)がLLMに提示されます。
- **ツールの呼び出し:** モデルが不足している情報や曖昧な指示を特定した場合、ベクターデータベースクエリ(例:Azure AI Searchによるプライベートデータのハイブリッド検索)や構造化されたSQL呼び出しなど、ツールや検索方法を選択してさらなるコンテキストを収集します。
- **評価と洗練:** 返されたデータをレビューした後、モデルは情報が十分かどうかを判断します。不十分であれば、クエリを洗練し、別のツールを試すか、アプローチを調整します。
- **満足するまで繰り返す:** このサイクルは、モデルが十分な明確さと証拠を得て、最終的な合理的な回答を提供できると判断するまで続きます。
- **メモリと状態:** システムはステップ間で状態とメモリを維持するため、以前の試みとその結果を記憶し、繰り返しを避け、進行する中でより情報に基づいた意思決定を行います。
時間が経つにつれて、これにより進化する理解が生まれ、モデルは複雑なマルチステップタスクを人間が介入したりプロンプトを再形成したりする必要なく、効率的に処理することが可能になります。
## 失敗モードの処理と自己修正
エージェンティックRAGの自律性には、強力な自己修正メカニズムも含まれています。システムが行き詰まった場合(例:無関係なドキュメントを取得したり、不完全なクエリに遭遇したりした場合)、以下のアプローチを取ります:
- **反復と再クエリ:** 低価値の回答を返す代わりに、モデルは新しい検索戦略を試みたり、データベースクエリを書き直したり、代替データセットを調べたりします。
- **診断ツールの使用:** システムは、推論ステップをデバッグしたり、取得したデータの正確性を確認するための追加機能を呼び出す場合があります。Azure AI Tracingなどのツールは、堅牢な観測性と監視を可能にする重要な要素です。
- **人間の監視に頼る:** 高リスクまたは繰り返し失敗するシナリオでは、モデルは不確実性をフラグとして示し、人間の指導を求める場合があります。人間が修正フィードバックを提供した後、モデルはそのレッスンを今後のセッションに反映させることができます。
この反復的かつ動的なアプローチにより、モデルは継続的に改善し、単なる一度限りのシステムではなく、セッション中に失敗から学ぶことができるシステムとなります。

## エージェンシーの限界
タスク内での自律性がある一方で、エージェンティックRAGは人工汎用知能(AGI)と同義ではありません。その「エージェンティック」な能力は、人間の開発者が提供したツール、データソース、ポリシーに制限されています。独自のツールを発明したり、設定されたドメインの境界を超えたりすることはできません。その代わり、手元のリソースを動的にオーケストレーションすることに長けています。
より高度なAI形式との主な違いは以下の通りです:
1. **ドメイン固有の自律性:** エージェンティックRAGシステムは、ユーザー定義の目標を達成することに焦点を当てており、クエリの書き換えやツールの選択などの戦略を用いて結果を向上させます。
2. **インフラストラクチャ依存:** システムの能力は、開発者によって統合されたツールとデータに依存しています。これらの境界を人間の介入なしに超えることはできません。
3. **ガードレールの尊重:** 倫理的ガイドライン、コンプライアンスルール、ビジネスポリシーは依然として非常に重要です。エージェントの自由度は常に安全対策と監視メカニズムによって制約されています(おそらく?)。
## 実用的な使用例と価値
エージェンティックRAGは、反復的な洗練と精度が求められるシナリオで活躍します:
1. **正確性が最優先される環境:** コンプライアンスチェック、規制分析、法的調査などでは、エージェンティックモデルが繰り返し事実を確認し、複数のソースを参照し、クエリを書き直して、徹底的に検証された回答を提供します。
2. **複雑なデータベース操作:** クエリが頻繁に失敗したり調整が必要となる構造化データを扱う際、Azure SQLやMicrosoft Fabric OneLakeを使用してクエリを自律的に洗練し、最終的な取得がユーザーの意図に一致するようにします。
3. **長時間のワークフロー:** 新しい情報が出てくるにつれて進化するセッションでは、エージェンティックRAGが継続的に新しいデータを取り込み、問題領域について学びながら戦略を変更します。
## ガバナンス、透明性、信頼
これらのシステムが推論においてより自律的になるにつれ、ガバナンスと透明性が重要になります:
- **説明可能な推論:** モデルは、作成したクエリ、参照したソース、結論に至るまでの推論ステップの監査トレイルを提供できます。Azure AI Content SafetyやAzure AI Tracing / GenAIOpsのようなツールは、透明性を維持し、リスクを軽減するのに役立ちます。
- **バイアス制御とバランスの取れた検索:** 開発者は、バランスの取れた代表的なデータソースが考慮されるように検索戦略を調整し、Azure Machine Learningを使用して出力を定期的に監査し、バイアスや偏ったパターンを検出します。
- **人間の監視とコンプライアンス:** 敏感なタスクでは、人間によるレビューが依然として不可欠です。エージェンティックRAGは、高リスクの意思決定において人間の判断を置き換えるものではなく、より徹底的に検証された選択肢を提供することでそれを補完します。
マルチステップ
**免責事項**:
この文書は、機械ベースのAI翻訳サービスを使用して翻訳されています。正確さを期すよう努めておりますが、自動翻訳には誤りや不正確さが含まれる可能性があります。元の言語で作成された原文が正式な情報源とみなされるべきです。重要な情報については、専門の人間による翻訳を推奨します。この翻訳の使用に起因する誤解や誤った解釈について、当社は一切の責任を負いません。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/05-agentic-rag/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/05-agentic-rag/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 6469
} |
# 信頼できるAIエージェントの構築
## はじめに
このレッスンでは以下について学びます:
- 安全で効果的なAIエージェントの構築とデプロイ方法
- AIエージェント開発時の重要なセキュリティ考慮点
- データとユーザーのプライバシーを保護しながらAIエージェントを開発する方法
## 学習目標
このレッスンを完了すると、次のことができるようになります:
- AIエージェントを作成する際のリスクを特定し、軽減する方法を理解する。
- データとアクセスが適切に管理されるようにセキュリティ対策を実装する。
- データプライバシーを保ち、質の高いユーザー体験を提供するAIエージェントを作成する。
## 安全性
まず、安全なエージェントアプリケーションの構築について考えてみましょう。安全性とは、AIエージェントが設計通りに動作することを意味します。エージェントアプリケーションの開発者として、安全性を最大化するための方法とツールを活用することができます。
### メタプロンプトシステムの構築
もし大規模言語モデル(LLM)を使用してAIアプリケーションを構築したことがあるなら、堅牢なシステムプロンプトやシステムメッセージを設計する重要性をご存じでしょう。これらのプロンプトは、LLMがユーザーやデータとどのようにやり取りするかのメタルールや指示、ガイドラインを設定します。
AIエージェントの場合、システムプロンプトはさらに重要です。なぜなら、エージェントが設計されたタスクを完了するためには、非常に具体的な指示が必要だからです。
スケーラブルなシステムプロンプトを作成するために、アプリケーション内で1つ以上のエージェントを構築する際にメタプロンプトシステムを活用できます。

#### ステップ1: メタプロンプトまたはテンプレートプロンプトの作成
メタプロンプトは、作成するエージェントのシステムプロンプトを生成するためにLLMによって使用されます。これをテンプレートとして設計することで、必要に応じて複数のエージェントを効率的に作成できます。
以下は、LLMに渡すメタプロンプトの例です:
```plaintext
You are an expert at creating AI agent assitants.
You will be provided a company name, role, responsibilites and other
information that you will use to provide a system prompt for.
To create the system prompt, be descriptive as possible and provide a structure that a system using an LLM can better understand the role and responsibilites of the AI assistant.
```
#### ステップ2: 基本プロンプトの作成
次に、AIエージェントを説明する基本プロンプトを作成します。ここでは、エージェントの役割、エージェントが完了するタスク、その他の責任を含めるべきです。
例を示します:
```plaintext
You are a travel agent for Contoso Travel with that is great at booking flights for customers. To help customers you can perform the following tasks: lookup available flights, book flights, ask for preferences in seating and times for flights, cancel any previously booked flights and alert customers on any delays or cancellations of flights.
```
#### ステップ3: 基本プロンプトをLLMに提供
次に、このプロンプトを最適化するために、システムプロンプトとしてメタプロンプトを使用し、基本プロンプトを提供します。
これにより、AIエージェントを誘導するために適切に設計されたプロンプトが生成されます:
```markdown
**Company Name:** Contoso Travel
**Role:** Travel Agent Assistant
**Objective:**
You are an AI-powered travel agent assistant for Contoso Travel, specializing in booking flights and providing exceptional customer service. Your main goal is to assist customers in finding, booking, and managing their flights, all while ensuring that their preferences and needs are met efficiently.
**Key Responsibilities:**
1. **Flight Lookup:**
- Assist customers in searching for available flights based on their specified destination, dates, and any other relevant preferences.
- Provide a list of options, including flight times, airlines, layovers, and pricing.
2. **Flight Booking:**
- Facilitate the booking of flights for customers, ensuring that all details are correctly entered into the system.
- Confirm bookings and provide customers with their itinerary, including confirmation numbers and any other pertinent information.
3. **Customer Preference Inquiry:**
- Actively ask customers for their preferences regarding seating (e.g., aisle, window, extra legroom) and preferred times for flights (e.g., morning, afternoon, evening).
- Record these preferences for future reference and tailor suggestions accordingly.
4. **Flight Cancellation:**
- Assist customers in canceling previously booked flights if needed, following company policies and procedures.
- Notify customers of any necessary refunds or additional steps that may be required for cancellations.
5. **Flight Monitoring:**
- Monitor the status of booked flights and alert customers in real-time about any delays, cancellations, or changes to their flight schedule.
- Provide updates through preferred communication channels (e.g., email, SMS) as needed.
**Tone and Style:**
- Maintain a friendly, professional, and approachable demeanor in all interactions with customers.
- Ensure that all communication is clear, informative, and tailored to the customer's specific needs and inquiries.
**User Interaction Instructions:**
- Respond to customer queries promptly and accurately.
- Use a conversational style while ensuring professionalism.
- Prioritize customer satisfaction by being attentive, empathetic, and proactive in all assistance provided.
**Additional Notes:**
- Stay updated on any changes to airline policies, travel restrictions, and other relevant information that could impact flight bookings and customer experience.
- Use clear and concise language to explain options and processes, avoiding jargon where possible for better customer understanding.
This AI assistant is designed to streamline the flight booking process for customers of Contoso Travel, ensuring that all their travel needs are met efficiently and effectively.
```
#### ステップ4: 繰り返しと改善
このメタプロンプトシステムの価値は、複数のエージェントのプロンプトを簡単に作成できるだけでなく、プロンプトを時間をかけて改善できることです。完全なユースケースに対して最初から機能するプロンプトを持つことは稀です。基本プロンプトを少しずつ変更し、システムを通じて実行することで、結果を比較し評価することが可能になります。
## 脅威の理解
信頼できるAIエージェントを構築するには、エージェントに対するリスクや脅威を理解し、それを軽減することが重要です。ここでは、AIエージェントに対するさまざまな脅威の一部と、それに対してどのように計画し準備できるかを見ていきます。

### タスクと指示
**説明:** 攻撃者がプロンプトや入力を操作することで、AIエージェントの指示や目標を変更しようとします。
**軽減策:** 危険なプロンプトをAIエージェントが処理する前に検出するためのバリデーションチェックや入力フィルターを実行します。これらの攻撃は通常、エージェントとの頻繁なやり取りを必要とするため、会話のターン数を制限することも防止策の一つです。
### 重要なシステムへのアクセス
**説明:** AIエージェントが機密データを保存するシステムやサービスにアクセスできる場合、攻撃者はこれらのサービスとの通信を侵害する可能性があります。これには、直接的な攻撃やエージェントを介してこれらのシステムに関する情報を得ようとする間接的な試みが含まれます。
**軽減策:** この種の攻撃を防ぐために、AIエージェントは必要最小限のアクセス権のみを持つべきです。エージェントとシステム間の通信も安全にする必要があります。認証とアクセス制御を実装することも、この情報を保護する方法の一つです。
### リソースとサービスの過負荷
**説明:** AIエージェントはタスクを完了するためにさまざまなツールやサービスにアクセスします。攻撃者はこの能力を利用して、AIエージェントを介して大量のリクエストを送信し、システム障害や高額なコストを引き起こす可能性があります。
**軽減策:** AIエージェントがサービスに送信できるリクエストの数を制限するポリシーを実装します。AIエージェントとの会話のターン数やリクエスト数を制限することも、この種の攻撃を防ぐ方法です。
### 知識ベースの汚染
**説明:** この種の攻撃はAIエージェントそのものを直接狙うのではなく、エージェントが使用する知識ベースやその他のサービスを標的とします。これには、エージェントがタスクを完了するために使用するデータや情報を改ざんし、偏ったり意図しない応答をユーザーに返すようにすることが含まれます。
**軽減策:** AIエージェントがワークフローで使用するデータを定期的に検証します。このデータへのアクセスを安全に保ち、信頼できる人物のみが変更できるようにすることで、この種の攻撃を防ぎます。
### エラーの連鎖
**説明:** AIエージェントはタスクを完了するためにさまざまなツールやサービスにアクセスします。攻撃者によって引き起こされたエラーが、エージェントが接続している他のシステムの障害につながり、攻撃が広範囲に広がり、トラブルシューティングが困難になる可能性があります。
**軽減策:** この問題を回避する一つの方法は、AIエージェントがDockerコンテナ内でタスクを実行するなど、制限された環境で動作するようにすることです。特定のシステムがエラーを返した場合に備えたフォールバックメカニズムやリトライロジックを作成することも、大規模なシステム障害を防ぐ方法です。
## ヒューマン・イン・ザ・ループ
信頼できるAIエージェントシステムを構築するもう一つの効果的な方法は、ヒューマン・イン・ザ・ループを活用することです。これにより、ユーザーがエージェントの実行中にフィードバックを提供できるフローが作られます。ユーザーは、マルチエージェントシステム内のエージェントとして機能し、実行中のプロセスを承認または終了させる役割を果たします。

以下は、この概念をAutoGenを使用して実装するコードスニペットの例です:
```python
# Create the agents.
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
assistant = AssistantAgent("assistant", model_client=model_client)
user_proxy = UserProxyAgent("user_proxy", input_func=input) # Use input() to get user input from console.
# Create the termination condition which will end the conversation when the user says "APPROVE".
termination = TextMentionTermination("APPROVE")
# Create the team.
team = RoundRobinGroupChat([assistant, user_proxy], termination_condition=termination)
# Run the conversation and stream to the console.
stream = team.run_stream(task="Write a 4-line poem about the ocean.")
# Use asyncio.run(...) when running in a script.
await Console(stream)
```
**免責事項**:
この文書は、機械翻訳AIサービスを使用して翻訳されています。正確さを期すよう努めておりますが、自動翻訳には誤りや不正確な表現が含まれる可能性があります。原文(元の言語で記載された文書)を信頼できる情報源としてお考えください。重要な情報については、専門の人間による翻訳を推奨します。この翻訳の使用に起因する誤解や誤った解釈について、当方は一切の責任を負いかねます。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/06-building-trustworthy-agents/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/06-building-trustworthy-agents/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 8013
} |
# 設計の計画
## はじめに
このレッスンでは以下の内容を学びます:
* 明確な全体目標を定義し、複雑なタスクを扱いやすいタスクに分解する方法。
* 構造化された出力を活用して、信頼性が高く機械が読み取りやすい応答を得る方法。
* 動的なタスクや予期しない入力に対応するためのイベント駆動型アプローチを適用する方法。
## 学習目標
このレッスンを完了すると、次のことが理解できるようになります:
* AIエージェントの全体目標を特定し、設定することで、達成すべき内容を明確にする。
* 複雑なタスクを扱いやすいサブタスクに分解し、それらを論理的な順序で整理する。
* エージェントに適切なツール(例:検索ツールやデータ分析ツール)を装備させ、それらをいつ、どのように使用するかを決定し、予期しない状況に対応する。
* サブタスクの結果を評価し、パフォーマンスを測定し、最終的な出力を改善するためにアクションを繰り返す。
## 全体目標の定義とタスクの分解

多くの現実世界のタスクは、単一ステップで取り組むには複雑すぎます。AIエージェントには、計画と行動を導くための簡潔な目標が必要です。例えば、以下の目標を考えてみましょう:
"3日間の旅行プランを作成する。"
この目標は一見シンプルですが、さらに具体化が必要です。目標が明確であればあるほど、エージェント(および人間の協力者)は、適切な結果を達成することに集中できます。例えば、フライトオプション、ホテルのおすすめ、アクティビティの提案を含む包括的な旅程を作成することが求められる場合です。
### タスクの分解
大規模または複雑なタスクは、小さく目標志向のサブタスクに分割することで扱いやすくなります。
旅行プランの例では、次のように目標を分解できます:
* フライト予約
* ホテル予約
* レンタカー手配
* パーソナライズ
各サブタスクは、専用のエージェントやプロセスによって処理されます。例えば、フライトの最適な料金を検索するエージェント、ホテル予約に特化したエージェントなどです。その後、調整役または「下流」のエージェントが、これらの結果をまとめてユーザーに一つの統合された旅程として提供します。
このモジュール式アプローチは、段階的な改善も可能にします。例えば、フードのおすすめや地元のアクティビティの提案に特化したエージェントを追加し、旅程をさらに洗練させることができます。
### 構造化された出力
大規模言語モデル(LLM)は、JSONのような構造化された出力を生成できます。これにより、下流のエージェントやサービスが解析・処理しやすくなります。これは特にマルチエージェント環境において有用で、計画出力を受け取った後にタスクを実行できます。この点については、[こちらのブログ記事](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/cookbook/structured-output-agent.html)をご参照ください。
以下は、計画エージェントが目標をサブタスクに分解し、構造化された計画を生成する簡単なPythonコードの例です:
### マルチエージェントオーケストレーションを活用した計画エージェント
この例では、Semantic Router Agentがユーザーのリクエスト(例:"旅行のためのホテルプランが必要です。")を受け取ります。
計画エージェントは以下の手順を実行します:
* **ホテルプランの受信**: エージェントはユーザーのメッセージを受け取り、システムプロンプト(利用可能なエージェントの詳細を含む)に基づいて構造化された旅行プランを生成します。
* **エージェントとそのツールの一覧化**: エージェントレジストリには、フライト、ホテル、レンタカー、アクティビティなどのエージェントリストと、それぞれが提供する機能やツールが含まれています。
* **プランの割り当て**: サブタスクの数に応じて、計画エージェントは専用エージェントに直接メッセージを送信する(単一タスクの場合)か、グループチャットマネージャーを介してマルチエージェントでのコラボレーションを調整します。
* **結果の要約**: 最後に、生成されたプランを要約して分かりやすくします。
以下はこれらのステップを示すPythonコードのサンプルです:
```python
from pydantic import BaseModel
from enum import Enum
from typing import List, Optional, Union
class AgentEnum(str, Enum):
FlightBooking = "flight_booking"
HotelBooking = "hotel_booking"
CarRental = "car_rental"
ActivitiesBooking = "activities_booking"
DestinationInfo = "destination_info"
DefaultAgent = "default_agent"
GroupChatManager = "group_chat_manager"
# Travel SubTask Model
class TravelSubTask(BaseModel):
task_details: str
assigned_agent: AgentEnum # we want to assign the task to the agent
class TravelPlan(BaseModel):
main_task: str
subtasks: List[TravelSubTask]
is_greeting: bool
import json
import os
from typing import Optional
from autogen_core.models import UserMessage, SystemMessage, AssistantMessage
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient
# Create the client with type-checked environment variables
client = AzureOpenAIChatCompletionClient(
azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
)
from pprint import pprint
# Define the user message
messages = [
SystemMessage(content="""You are an planner agent.
Your job is to decide which agents to run based on the user's request.
Below are the available agents specialised in different tasks:
- FlightBooking: For booking flights and providing flight information
- HotelBooking: For booking hotels and providing hotel information
- CarRental: For booking cars and providing car rental information
- ActivitiesBooking: For booking activities and providing activity information
- DestinationInfo: For providing information about destinations
- DefaultAgent: For handling general requests""", source="system"),
UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melbourne", source="user"),
]
response = await client.create(messages=messages, extra_create_args={"response_format": TravelPlan})
# Ensure the response content is a valid JSON string before loading it
response_content: Optional[str] = response.content if isinstance(response.content, str) else None
if response_content is None:
raise ValueError("Response content is not a valid JSON string")
# Print the response content after loading it as JSON
pprint(json.loads(response_content))
```
上記のコードから得られる出力例を以下に示します。この構造化された出力を使用して`assigned_agent`にルーティングし、旅行プランをエンドユーザーに要約して提供できます。
```json
{
"is_greeting": "False",
"main_task": "Plan a family trip from Singapore to Melbourne.",
"subtasks": [
{
"assigned_agent": "flight_booking",
"task_details": "Book round-trip flights from Singapore to Melbourne."
},
{
"assigned_agent": "hotel_booking",
"task_details": "Find family-friendly hotels in Melbourne."
},
{
"assigned_agent": "car_rental",
"task_details": "Arrange a car rental suitable for a family of four in Melbourne."
},
{
"assigned_agent": "activities_booking",
"task_details": "List family-friendly activities in Melbourne."
},
{
"assigned_agent": "destination_info",
"task_details": "Provide information about Melbourne as a travel destination."
}
]
}
```
上記コードの例を含むノートブックは[こちら](../../../07-planning-design/code_samples/07-autogen.ipynb)から利用できます。
### 繰り返し計画
いくつかのタスクでは、結果に応じて計画を再調整する必要があります。例えば、エージェントがフライト予約中に予期しないデータ形式を発見した場合、戦略を適応させてからホテル予約に進む必要があるかもしれません。
さらに、ユーザーからのフィードバック(例:早い時間のフライトを希望する)によって、部分的な再計画が必要になる場合もあります。この動的で反復的なアプローチにより、最終的な解決策が現実の制約やユーザーの好みに適合することを確保します。
以下はその例を示すコードです:
```python
from autogen_core.models import UserMessage, SystemMessage, AssistantMessage
#.. same as previous code and pass on the user history, current plan
messages = [
SystemMessage(content="""You are a planner agent to optimize the
Your job is to decide which agents to run based on the user's request.
Below are the available agents specialised in different tasks:
- FlightBooking: For booking flights and providing flight information
- HotelBooking: For booking hotels and providing hotel information
- CarRental: For booking cars and providing car rental information
- ActivitiesBooking: For booking activities and providing activity information
- DestinationInfo: For providing information about destinations
- DefaultAgent: For handling general requests""", source="system"),
UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melboune", source="user"),
AssistantMessage(content=f"Previous travel plan - {TravelPlan}", source="assistant")
]
# .. re-plan and send the tasks to respective agents
```
より包括的な計画については、複雑なタスクを解決するためのMagnetic Oneに関する[ブログ記事](https://www.microsoft.com/research/articles/magentic-one-a-generalist-multi-agent-system-for-solving-complex-tasks)をご覧ください。
## まとめ
この記事では、利用可能なエージェントを動的に選択できるプランナーを作成する方法について説明しました。プランナーの出力はタスクを分解し、それぞれのエージェントに割り当てて実行されます。エージェントがタスクを実行するために必要な機能やツールにアクセスできることが前提です。さらに、リフレクションや要約、ラウンドロビンチャットなどのパターンを追加することで、さらにカスタマイズが可能です。
## 追加リソース
* o1推論モデルは、複雑なタスクの計画において非常に優れていることが証明されています - TODO: 例を共有予定?
* Autogen Magnetic One - 複雑なタスクを解決するための汎用マルチエージェントシステムであり、複数の難しいエージェントベンチマークで印象的な成果を上げています。参考:[autogen-magentic-one](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-magentic-one)。この実装では、オーケストレーターがタスク固有の計画を作成し、これらのタスクを利用可能なエージェントに委任します。オーケストレーターは計画だけでなく、タスクの進行状況を監視し、必要に応じて再計画を行う追跡メカニズムも採用しています。
**免責事項**:
本書類は、機械翻訳AIサービスを使用して翻訳されています。正確性を追求しておりますが、自動翻訳にはエラーや不正確さが含まれる可能性があることをご了承ください。原文(元の言語の文書)が公式な情報源と見なされるべきです。重要な情報については、専門の人間による翻訳をお勧めします。本翻訳の使用に起因する誤解や解釈の誤りについて、当方は一切の責任を負いません。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/07-planning-design/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/07-planning-design/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 8203
} |
# マルチエージェント設計パターン
複数のエージェントを含むプロジェクトに取り組み始めると、マルチエージェント設計パターンを考慮する必要があります。ただし、いつマルチエージェントに切り替えるべきか、その利点が何であるかはすぐには明確にならないかもしれません。
## はじめに
このレッスンでは、以下の質問に答えることを目指します:
- マルチエージェントが適用されるシナリオはどのようなものか?
- 単一のエージェントが複数のタスクを行う場合と比べて、マルチエージェントを使用する利点は何か?
- マルチエージェント設計パターンを実装するための構成要素は何か?
- 複数のエージェントがどのように相互作用しているかをどのように可視化するか?
## 学習目標
このレッスンの後、次のことができるようになります:
- マルチエージェントが適用されるシナリオを特定する。
- 単一エージェントよりもマルチエージェントを使用する利点を理解する。
- マルチエージェント設計パターンを実装するための構成要素を理解する。
全体像は?
*マルチエージェントは、複数のエージェントが協力して共通の目標を達成するための設計パターン*です。
このパターンは、ロボティクス、自律システム、分散コンピューティングなど、さまざまな分野で広く使用されています。
## マルチエージェントが適用されるシナリオ
では、どのようなシナリオがマルチエージェントの使用に適しているでしょうか?答えは、多くのシナリオで複数のエージェントを使用することが有益であり、特に以下の場合に効果的です:
- **大規模な作業負荷**: 大規模な作業負荷は小さなタスクに分割され、それぞれ異なるエージェントに割り当てることで、並列処理と迅速な完了が可能になります。例としては、大量のデータ処理タスクがあります。
- **複雑なタスク**: 複雑なタスクも、小さなサブタスクに分割され、それぞれ特定の側面に特化したエージェントに割り当てられます。例としては、自動運転車があり、異なるエージェントがナビゲーション、障害物検知、他の車両との通信を管理します。
- **多様な専門性**: 異なるエージェントが多様な専門性を持つことで、単一エージェントよりもタスクの異なる側面を効果的に処理できます。例としては、医療分野で診断、治療計画、患者モニタリングを管理するエージェントが挙げられます。
## 単一エージェントよりマルチエージェントを使用する利点
単一エージェントシステムは単純なタスクには適していますが、より複雑なタスクでは、複数のエージェントを使用することでいくつかの利点が得られます:
- **専門化**: 各エージェントが特定のタスクに特化できます。単一エージェントの専門性の欠如は、複雑なタスクに直面した際に混乱を招き、適切でないタスクに取り組む可能性があります。
- **スケーラビリティ**: 単一エージェントを過負荷にするのではなく、エージェントを追加することでシステムを拡張する方が簡単です。
- **フォールトトレランス**: 1つのエージェントが失敗しても、他のエージェントが機能を続行することで、システムの信頼性が確保されます。
例を挙げてみましょう。ユーザーの旅行を予約するシステムを考えます。単一エージェントシステムでは、フライト検索からホテル予約、レンタカーの手配まで、旅行予約プロセスのすべての側面を処理する必要があります。このようなシステムを単一エージェントで実現するには、すべてのタスクを処理するためのツールが必要になり、維持や拡張が困難な複雑でモノリシックなシステムになる可能性があります。一方、マルチエージェントシステムでは、フライト検索、ホテル予約、レンタカー手配に特化した異なるエージェントを持つことができます。このようなシステムは、よりモジュール化され、維持が容易で、スケーラブルになります。
これは、個人経営の旅行代理店とフランチャイズ型の旅行代理店を比較するようなものです。個人経営の代理店では、単一のエージェントがすべての旅行予約プロセスを処理しますが、フランチャイズでは、各エージェントが異なる側面を処理します。
## マルチエージェント設計パターンを実装するための構成要素
マルチエージェント設計パターンを実装する前に、このパターンを構成する要素を理解する必要があります。
ユーザーの旅行を予約する例をもう一度考えてみましょう。この場合、構成要素には以下が含まれます:
- **エージェント間の通信**: フライト検索、ホテル予約、レンタカー手配のエージェントが、ユーザーの希望や制約について情報を共有する必要があります。この通信のプロトコルや方法を決定する必要があります。具体的には、フライト検索エージェントがホテル予約エージェントと連携し、フライトの日程に合わせてホテルを予約する必要があります。つまり、*どのエージェントが情報を共有し、どのように共有するのか*を決める必要があります。
- **調整メカニズム**: エージェントがユーザーの希望や制約を満たすために行動を調整する必要があります。たとえば、ユーザーが空港近くのホテルを希望する場合や、レンタカーが空港でのみ利用可能な場合、ホテル予約エージェントとレンタカー手配エージェントが調整する必要があります。つまり、*エージェントがどのように行動を調整するのか*を決める必要があります。
- **エージェントアーキテクチャ**: エージェントは意思決定を行い、ユーザーとのやり取りから学習するための内部構造を持つ必要があります。たとえば、フライト検索エージェントは、ユーザーに推奨するフライトを決定するための内部構造を持つ必要があります。これには、過去の好みに基づいてフライトを推奨する機械学習モデルを使用することが含まれます。
- **マルチエージェント間の相互作用の可視性**: 複数のエージェントがどのように相互作用しているかを可視化する必要があります。これには、エージェントの活動や相互作用を追跡するためのツールや技術が必要です。これには、ログやモニタリングツール、可視化ツール、パフォーマンス指標が含まれる可能性があります。
- **マルチエージェントパターン**: マルチエージェントシステムを実装するためのパターンには、集中型、分散型、ハイブリッド型のアーキテクチャがあります。ユースケースに最適なパターンを選択する必要があります。
- **人間の介入**: 多くの場合、人間が介入する場面があり、エージェントにいつ人間の判断を求めるべきかを指示する必要があります。たとえば、エージェントが推奨しなかった特定のホテルやフライトをユーザーが希望する場合や、予約前に確認を求める場合などです。
## マルチエージェント間の相互作用の可視性
複数のエージェントがどのように相互作用しているかを可視化することは重要です。この可視性は、デバッグ、最適化、全体的なシステムの効果を確保するために不可欠です。これを実現するには、エージェントの活動や相互作用を追跡するためのツールや技術が必要です。たとえば、ユーザーの旅行を予約する場合、各エージェントのステータス、ユーザーの希望や制約、エージェント間の相互作用を表示するダッシュボードを作成することができます。
各要素をもう少し詳しく見てみましょう。
- **ログとモニタリングツール**: 各エージェントが取ったアクションごとにログを記録します。ログには、アクションを取ったエージェント、取ったアクション、アクションが取られた時間、アクションの結果に関する情報を記録できます。この情報は、デバッグや最適化などに使用できます。
- **可視化ツール**: 可視化ツールを使用すると、エージェント間の相互作用をより直感的に把握できます。たとえば、エージェント間の情報の流れを示すグラフを作成することができます。これにより、ボトルネックや非効率性、その他の問題を特定できます。
- **パフォーマンス指標**: パフォーマンス指標を使用して、マルチエージェントシステムの効果を追跡できます。たとえば、タスクの完了にかかった時間、単位時間あたりに完了したタスク数、エージェントが行った推奨の正確性などを追跡できます。この情報を使用して、改善点を特定し、システムを最適化できます。
## マルチエージェントパターン
マルチエージェントアプリを作成するために使用できる具体的なパターンについて見ていきましょう。以下は、検討に値する興味深いパターンです:
### グループチャット
このパターンは、複数のエージェントが相互にコミュニケーションできるグループチャットアプリケーションを作成したい場合に役立ちます。典型的なユースケースには、チームコラボレーション、カスタマーサポート、ソーシャルネットワーキングが含まれます。
このパターンでは、各エージェントがグループチャット内のユーザーを表し、メッセージプロトコルを使用してメッセージがエージェント間で交換されます。エージェントはグループチャットにメッセージを送信し、グループチャットからメッセージを受信し、他のエージェントからのメッセージに応答できます。
このパターンは、すべてのメッセージが中央サーバーを介してルーティングされる集中型アーキテクチャ、またはメッセージが直接交換される分散型アーキテクチャを使用して実装できます。

### ハンドオフ
このパターンは、複数のエージェントがタスクを互いに引き継ぐアプリケーションを作成したい場合に役立ちます。
典型的なユースケースには、カスタマーサポート、タスク管理、ワークフロー自動化が含まれます。
このパターンでは、各エージェントがタスクまたはワークフロー内のステップを表し、事前定義されたルールに基づいてエージェント間でタスクを引き継ぐことができます。

### 協調フィルタリング
このパターンは、複数のエージェントが協力してユーザーに推奨を行うアプリケーションを作成したい場合に役立ちます。
複数のエージェントが協力する理由は、各エージェントが異なる専門知識を持ち、推奨プロセスに異なる形で貢献できるためです。
たとえば、ユーザーが株式市場で購入するのに最適な株を推奨してほしい場合を考えてみましょう。
- **業界の専門家**: 1つのエージェントは特定の業界に精通している。
- **テクニカル分析**: 別のエージェントはテクニカル分析の専門家である。
- **ファンダメンタル分析**: さらに別のエージェントはファンダメンタル分析の専門家である。これらのエージェントが協力することで、ユーザーに対してより包括的な推奨を提供できます。

## シナリオ: 返金プロセス
顧客が商品の返金を求めるシナリオを考えてみましょう。このプロセスには多くのエージェントが関与する可能性がありますが、このプロセスに特化したエージェントと、他のプロセスでも使用できる汎用エージェントに分けて考えます。
**返金プロセスに特化したエージェント**:
以下は、返金プロセスに関与する可能性のあるエージェントです:
- **顧客エージェント**: 顧客を表し、返金プロセスを開始する役割を担います。
- **販売者エージェント**: 販売者を表し、返金処理を担当します。
- **支払いエージェント**: 支払いプロセスを表し、顧客への支払い返金を担当します。
- **解決エージェント**: 解決プロセスを表し、返金プロセス中に発生する問題を解決します。
- **コンプライアンスエージェント**: コンプライアンスプロセスを表し、返金プロセスが規制やポリシーに準拠していることを確認します。
**汎用エージェント**:
これらのエージェントは、ビジネスの他の部分でも使用できます。
- **配送エージェント**: 配送プロセスを表し、商品を販売者に返送する役割を担います。このエージェントは、返金プロセスだけでなく、購入時の一般的な配送にも使用できます。
- **フィードバックエージェント**: フィードバックプロセスを表し、顧客からフィードバックを収集します。フィードバックは、返金プロセスだけでなく、いつでも収集できます。
- **エスカレーションエージェント**: エスカレーションプロセスを表し、問題を上位サポートレベルにエスカレートする役割を担います。このタイプのエージェントは、エスカレーションが必要なあらゆるプロセスで使用できます。
- **通知エージェント**: 通知プロセスを表し、返金プロセスのさまざまな段階で顧客に通知を送信します。
- **分析エージェント**: 分析プロセスを表し、返金プロセスに関連するデータを分析します。
- **監査エージェント**: 監査プロセスを表し、返金プロセスが正しく実行されていることを確認します。
- **レポートエージェント**: レポートプロセスを表し、返金プロセスに関するレポートを生成します。
- **ナレッジエージェント**: ナレッジプロセスを表し、返金プロセスに関連する情報のナレッジベースを維持します。このエージェントは、返金に関する知識だけでなく、ビジネスの他の部分についても知識を持つことができます。
- **セキュリティエージェント**: セキュリティプロセスを表し、返金プロセスのセキュリティを確保します。
- **品質エージェント**: 品質プロセスを表し、返金プロセスの品質を確保します。
上記には、特定の返金プロセス用のエージェントと、ビジネスの他の
**免責事項**:
本書類は、機械翻訳AIサービスを使用して翻訳されています。正確性を期して努力しておりますが、自動翻訳にはエラーや不正確な表現が含まれる可能性があります。元の言語で作成された原本を正式な情報源としてご参照ください。重要な情報については、専門の人間による翻訳をお勧めします。本翻訳の利用に起因する誤解や誤った解釈について、当社は一切の責任を負いかねます。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/08-multi-agent/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/08-multi-agent/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 6459
} |
# AIエージェントにおけるメタ認知
## はじめに
AIエージェントにおけるメタ認知に関するレッスンへようこそ!この章は、AIエージェントが自分自身の思考プロセスをどのように考えることができるかに興味を持つ初心者向けに設計されています。このレッスンを終える頃には、重要な概念を理解し、AIエージェントの設計にメタ認知を応用するための実践的な例を身につけることができるでしょう。
## 学習目標
このレッスンを完了すると、以下ができるようになります:
1. エージェントの定義における推論ループの影響を理解する。
2. 自己修正型エージェントを支援する計画および評価技術を使用する。
3. タスクを達成するためにコードを操作できるエージェントを作成する。
## メタ認知の紹介
メタ認知とは、自分自身の思考について考えるという高次の認知プロセスを指します。AIエージェントの場合、これは自己認識や過去の経験に基づいて行動を評価し、調整する能力を意味します。
### メタ認知とは?
メタ認知、つまり「思考についての思考」は、自己認識や自分の認知プロセスの自己調整を伴う高次の認知プロセスです。AIの分野では、メタ認知によりエージェントが戦略や行動を評価し適応させることができ、問題解決能力や意思決定能力の向上につながります。メタ認知を理解することで、より知的で適応性が高く効率的なAIエージェントを設計することができます。
### AIエージェントにおけるメタ認知の重要性
メタ認知は、AIエージェント設計において以下の理由から重要な役割を果たします:

- **自己反省**:エージェントは自分のパフォーマンスを評価し、改善が必要な領域を特定できます。
- **適応性**:エージェントは過去の経験や変化する環境に基づいて戦略を修正できます。
- **エラー修正**:エージェントはエラーを自律的に検出し修正することで、より正確な結果をもたらします。
- **リソース管理**:エージェントは、時間や計算能力などのリソースを計画し評価することで最適化できます。
## AIエージェントの構成要素
メタ認知プロセスに入る前に、AIエージェントの基本的な構成要素を理解することが重要です。AIエージェントは通常、以下の要素で構成されています:
- **ペルソナ**:エージェントの個性や特徴を指し、ユーザーとのやり取りの仕方を定義します。
- **ツール**:エージェントが実行できる能力や機能。
- **スキル**:エージェントが持つ知識や専門性。
これらの要素が組み合わさり、特定のタスクを実行する「専門ユニット」を形成します。
**例**:旅行代理店を考えてみましょう。このエージェントは、ユーザーの旅行を計画するだけでなく、リアルタイムデータや過去の顧客経験に基づいてその計画を調整します。
### 例:旅行代理店サービスにおけるメタ認知
AIを活用した旅行代理店サービスを設計する場面を想像してみてください。このエージェント「Travel Agent」は、ユーザーの休暇計画を支援します。メタ認知を取り入れることで、Travel Agentは自己認識や過去の経験に基づいて行動を評価し調整することができます。
#### 現在のタスク
現在のタスクは、ユーザーがパリ旅行を計画するのを支援することです。
#### タスクを完了するためのステップ
1. **ユーザーの好みを収集**:旅行日程、予算、興味(例:博物館、料理、ショッピング)、特定の要件についてユーザーに尋ねます。
2. **情報の取得**:ユーザーの好みに合ったフライトオプション、宿泊施設、観光地、レストランを検索します。
3. **提案の生成**:フライト詳細、ホテル予約、提案されたアクティビティを含む個別の旅程を提供します。
4. **フィードバックに基づく調整**:提案に対するユーザーのフィードバックを求め、必要に応じて調整を行います。
#### 必要なリソース
- フライトおよびホテル予約データベースへのアクセス。
- パリの観光地やレストランに関する情報。
- 過去のインタラクションからのユーザーフィードバックデータ。
#### 経験と自己反省
Travel Agentは、パフォーマンスを評価し、過去の経験から学ぶためにメタ認知を使用します。
1. **ユーザーフィードバックの分析**:提案が好評だったものとそうでなかったものを確認し、将来の提案を調整します。
2. **適応性**:例えば、ユーザーが以前に混雑した場所を嫌うと述べた場合、Travel Agentは今後ピーク時間帯の観光地を避けるようにします。
3. **エラー修正**:過去に満室のホテルを提案するなどのエラーがあった場合、より厳密に空室状況を確認することを学びます。
#### 実践的な開発者向け例
以下は、メタ認知を取り入れたTravel Agentのコードがどのように見えるかの簡単な例です:
```python
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):
# Search for flights, hotels, and attractions based on preferences
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)
# Analyze feedback and adjust future recommendations
self.user_preferences = adjust_preferences(self.user_preferences, feedback)
# Example usage
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)
```
#### メタ認知が重要な理由
- **自己反省**:エージェントはパフォーマンスを分析し、改善が必要な領域を特定できます。
- **適応性**:フィードバックや変化する条件に基づいて戦略を修正できます。
- **エラー修正**:エージェントは自律的にエラーを検出し修正できます。
- **リソース管理**:時間や計算能力などのリソースを最適化できます。
メタ認知を取り入れることで、Travel Agentはより個別化され正確な旅行提案を提供し、全体的なユーザー体験を向上させることができます。
---
```
```markdown
旅行代理店は、ユーザーからのフィードバックに基づいて新しい検索クエリを作成します。
- 例: ```python
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
```
- **ツール**: 旅行代理店はアルゴリズムを使用して新しい検索結果をランク付けおよびフィルタリングし、ユーザーからのフィードバックに基づいて関連性を強調します。
- 例: ```python
new_attractions = search_attractions(preferences)
new_itinerary = create_itinerary(flights, hotels, new_attractions)
print("Updated Itinerary:", new_itinerary)
```
- **評価**: 旅行代理店は、ユーザーからのフィードバックを分析し、必要に応じて調整を行うことで、推奨事項の関連性と正確性を継続的に評価します。
- 例: ```python
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)
```
#### 実用例
以下は、旅行代理店におけるCorrective RAGアプローチを取り入れた簡単なPythonコード例です:
```python
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
# Example usage
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)
```
### 事前コンテキストロード
事前コンテキストロードとは、クエリを処理する前に関連するコンテキストや背景情報をモデルにロードすることを指します。これにより、モデルはプロセス中に追加データを取得する必要がなく、最初からこの情報にアクセスでき、より情報に基づいた応答を生成できます。以下は、旅行代理店アプリケーションでの事前コンテキストロードの簡単な例です:
```python
class TravelAgent:
def __init__(self):
# Pre-load popular destinations and their information
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):
# Fetch destination information from pre-loaded context
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}."
# Example usage
travel_agent = TravelAgent()
print(travel_agent.get_destination_info("Paris"))
print(travel_agent.get_destination_info("Tokyo"))
```
#### 説明
1. **初期化 (`__init__` method)**: The `TravelAgent` class pre-loads a dictionary containing information about popular destinations such as Paris, Tokyo, New York, and Sydney. This dictionary includes details like the country, currency, language, and major attractions for each destination.
2. **Retrieving Information (`get_destination_info` method)**: When a user queries about a specific destination, the `get_destination_info` メソッド)**:
このメソッドは、事前にロードされたコンテキスト辞書から関連情報を取得します。事前にコンテキストをロードすることで、旅行代理店アプリケーションはリアルタイムで外部ソースから情報を取得することなく、ユーザーのクエリに迅速に応答できます。これにより、アプリケーションはより効率的で応答性が高くなります。
### ゴールを設定してからの計画のブートストラップ
ゴールを設定して計画をブートストラップするとは、明確な目標や期待する成果を最初に設定することを指します。このゴールを定義することで、モデルは反復プロセス全体を通じてこれを指針として使用できます。このアプローチにより、各反復が目標達成に向けて進むことを保証し、プロセスがより効率的かつ集中化されます。
以下は、旅行代理店がゴールを設定して計画をブートストラップし、反復を行う例です:
### シナリオ
旅行代理店が顧客のためにカスタマイズされた休暇プランを作成したいとします。目標は、顧客の満足度を最大化する旅行日程を作成することです。
### ステップ
1. 顧客の好みと予算を定義します。
2. これらの好みに基づいて初期計画をブートストラップします。
3. 顧客の満足度を最適化するために計画を反復します。
#### Pythonコード
```python
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']
# Example usage
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)
```
#### コード説明
1. **初期化 (`__init__` method)**: The `TravelAgent` class is initialized with a list of potential destinations, each having attributes like name, cost, and activity type.
2. **Bootstrapping the Plan (`bootstrap_plan` method)**: This method creates an initial travel plan based on the client's preferences and budget. It iterates through the list of destinations and adds them to the plan if they match the client's preferences and fit within the budget.
3. **Matching Preferences (`match_preferences` method)**: This method checks if a destination matches the client's preferences.
4. **Iterating the Plan (`iterate_plan` method)**: This method refines the initial plan by trying to replace each destination in the plan with a better match, considering the client's preferences and budget constraints.
5. **Calculating Cost (`calculate_cost` メソッド)**:
このメソッドは、現在の計画に新しい目的地を追加した場合の総コストを計算します。
#### 使用例
- **初期計画**: 旅行代理店は、観光を好み、予算が2000ドルの顧客の好みに基づいて初期計画を作成します。
- **改良された計画**: 旅行代理店は、顧客の好みと予算を最適化するために計画を反復します。
ゴールを明確に設定(例: 顧客満足度の最大化)し、それを反復して計画を改良することで、旅行代理店は顧客のためにカスタマイズされ最適化された旅行日程を作成できます。このアプローチにより、旅行計画は最初から顧客の好みと予算に合致し、各反復でさらに改善されます。
### LLMを活用した再ランク付けとスコアリング
大規模言語モデル(LLM)は、取得したドキュメントや生成された応答の関連性や品質を評価することで、再ランク付けとスコアリングに使用できます。その仕組みは以下の通りです:
**取得**: 初期取得ステップでは、クエリに基づいて候補ドキュメントや応答のセットを取得します。
**再ランク付け**: LLMはこれらの候補を評価し、関連性や品質に基づいて再ランク付けします。このステップにより、最も関連性が高く質の高い情報が最初に提示されることが保証されます。
**スコアリング**: LLMは各候補にスコアを割り当て、関連性や品質を反映します。これにより、ユーザーに最適な応答やドキュメントを選択するのに役立ちます。
LLMを再ランク付けとスコアリングに活用することで、システムはより正確で文脈に関連する情報を提供でき、全体的なユーザー体験が向上します。以下は、旅行代理店がユーザーの好みに基づいて旅行先を再ランク付けしスコアリングする方法の例です:
#### シナリオ - 好みに基づく旅行
旅行代理店が顧客の好みに基づいて最適な旅行先を推薦したいとします。LLMは旅行先を再ランク付けし、スコアリングすることで、最も関連性の高い選択肢が提示されるようにします。
#### ステップ:
1. ユーザーの好みを収集します。
2. 潜在的な旅行先のリストを取得します。
3. LLMを使用して、ユーザーの好みに基づいて旅行先を再ランク付けしスコアリングします。
以下は、Azure OpenAI Servicesを使用して前述の例を更新する方法です:
#### 必要条件
1. Azureサブスクリプションが必要です。
2. Azure OpenAIリソースを作成し、APIキーを取得します。
#### Pythonコード例
```python
import requests
import json
class TravelAgent:
def __init__(self, destinations):
self.destinations = destinations
def get_recommendations(self, preferences, api_key, endpoint):
# Generate a prompt for the Azure OpenAI
prompt = self.generate_prompt(preferences)
# Define headers and payload for the request
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
payload = {
"prompt": prompt,
"max_tokens": 150,
"temperature": 0.7
}
# Call the Azure OpenAI API to get the re-ranked and scored destinations
response = requests.post(endpoint, headers=headers, json=payload)
response_data = response.json()
# Extract and return the recommendations
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
# Example usage
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)
```
#### コード説明 - Preference Booker
1. **初期化**: `TravelAgent` class is initialized with a list of potential travel destinations, each having attributes like name and description.
2. **Getting Recommendations (`get_recommendations` method)**: This method generates a prompt for the Azure OpenAI service based on the user's preferences and makes an HTTP POST request to the Azure OpenAI API to get re-ranked and scored destinations.
3. **Generating Prompt (`generate_prompt` method)**: This method constructs a prompt for the Azure OpenAI, including the user's preferences and the list of destinations. The prompt guides the model to re-rank and score the destinations based on the provided preferences.
4. **API Call**: The `requests` library is used to make an HTTP POST request to the Azure OpenAI API endpoint. The response contains the re-ranked and scored destinations.
5. **Example Usage**: The travel agent collects user preferences (e.g., interest in sightseeing and diverse culture) and uses the Azure OpenAI service to get re-ranked and scored recommendations for travel destinations.
Make sure to replace `your_azure_openai_api_key` with your actual Azure OpenAI API key and `https://your-endpoint.com/...` にAzure OpenAIデプロイメントの実際のエンドポイントURLを入力します。
LLMを再ランク付けとスコアリングに活用することで、旅行代理店は顧客によりパーソナライズされた関連性の高い旅行推薦を提供し、全体的な体験を向上させることができます。
```
```markdown
パリの最高の美術館?"). - **ナビゲーション意図**: ユーザーは特定のウェブサイトやページに移動したいと考えています(例:「ルーブル美術館公式ウェブサイト」)。 - **取引意図**: ユーザーはフライト予約や購入などの取引を行おうとしています(例:「パリ行きのフライトを予約」)。
2. **コンテキスト認識**:
- ユーザーのクエリのコンテキストを分析することで、意図を正確に特定するのに役立ちます。これには、過去のインタラクション、ユーザーの好み、現在のクエリの具体的な詳細を考慮することが含まれます。
3. **自然言語処理 (NLP)**:
- NLP技術を使用して、ユーザーが提供する自然言語クエリを理解し解釈します。これには、エンティティ認識、感情分析、クエリ解析などのタスクが含まれます。
4. **パーソナライズ**:
- ユーザーの履歴、好み、フィードバックに基づいて検索結果をパーソナライズすることで、取得する情報の関連性を向上させます。
#### 実践例: 旅行代理店における意図を用いた検索
旅行代理店を例にとり、意図を用いた検索がどのように実装されるかを見てみましょう。
1. **ユーザーの好みを収集する**
```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
```
2. **ユーザーの意図を理解する**
```python
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"
```
3. **コンテキスト認識**
```python
def analyze_context(query, user_history):
# Combine current query with user history to understand context
context = {
"current_query": query,
"user_history": user_history
}
return context
```
4. **検索と結果のパーソナライズ**
```python
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):
# Example search logic for informational intent
results = search_web(f"best {preferences['interests']} in {preferences['destination']}")
return results
def search_navigation(query):
# Example search logic for navigational intent
results = search_web(query)
return results
def search_transaction(query, preferences):
# Example search logic for transactional intent
results = search_web(f"book {query} to {preferences['destination']}")
return results
def personalize_results(results, user_history):
# Example personalization logic
personalized = [result for result in results if result not in user_history]
return personalized[:10] # Return top 10 personalized results
```
5. **使用例**
```python
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)
```
---
## 4. ツールとしてのコード生成
コード生成エージェントはAIモデルを使用してコードを作成・実行し、複雑な問題を解決しタスクを自動化します。
### コード生成エージェント
コード生成エージェントは生成AIモデルを使用してコードを作成・実行します。これらのエージェントは、さまざまなプログラミング言語でコードを生成・実行することで、複雑な問題を解決し、タスクを自動化し、貴重な洞察を提供します。
#### 実践的な応用
1. **自動コード生成**: データ分析、ウェブスクレイピング、機械学習などの特定のタスクに対応するコードスニペットを生成します。
2. **RAGとしてのSQL**: データベースからデータを取得・操作するためのSQLクエリを使用します。
3. **問題解決**: アルゴリズムの最適化やデータ分析など、特定の問題を解決するためのコードを作成・実行します。
#### 例: データ分析のためのコード生成エージェント
データ分析用のコード生成エージェントを設計する場合、以下のように機能します:
1. **タスク**: データセットを分析してトレンドやパターンを特定します。
2. **ステップ**:
- データセットをデータ分析ツールにロードします。
- データをフィルタリング・集計するためのSQLクエリを生成します。
- クエリを実行して結果を取得します。
- 結果を使用して可視化や洞察を生成します。
3. **必要なリソース**: データセットへのアクセス、データ分析ツール、SQL機能。
4. **経験**: 過去の分析結果を活用して、将来の分析の精度と関連性を向上させます。
### 例: 旅行代理店向けのコード生成エージェント
この例では、旅行計画を支援するためにコードを生成・実行する旅行代理店エージェントを設計します。このエージェントは、旅行オプションの取得、結果のフィルタリング、生成AIを使用した旅程の作成などのタスクを処理できます。
#### コード生成エージェントの概要
1. **ユーザーの好みを収集する**: 目的地、旅行日程、予算、興味などのユーザー入力を収集します。
2. **データを取得するコードを生成する**: フライト、ホテル、観光地に関するデータを取得するコードスニペットを生成します。
3. **生成されたコードを実行する**: 生成されたコードを実行してリアルタイム情報を取得します。
4. **旅程を作成する**: 取得したデータを個人化された旅行プランにまとめます。
5. **フィードバックに基づいて調整する**: ユーザーのフィードバックを受け取り、必要に応じてコードを再生成して結果を改善します。
#### 実装のステップ
1. **ユーザーの好みを収集する**
```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
```
2. **データを取得するコードを生成する**
```python
def generate_code_to_fetch_data(preferences):
# Example: Generate code to search for flights based on user preferences
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):
# Example: Generate code to search for hotels
code = f"""
def search_hotels():
import requests
response = requests.get('https://api.example.com/hotels', params={preferences})
return response.json()
"""
return code
```
3. **生成されたコードを実行する**
```python
def execute_code(code):
# Execute the generated code using 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)
```
4. **旅程を作成する**
```python
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)
```
5. **フィードバックに基づいて調整する**
```python
def adjust_based_on_feedback(feedback, preferences):
# Adjust preferences based on user feedback
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)
# Regenerate and execute code with updated preferences
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)
```
### 環境認識と推論を活用する
テーブルのスキーマに基づくクエリ生成プロセスを強化するために、環境認識と推論を活用できます。以下はその例です:
1. **スキーマの理解**: システムはテーブルのスキーマを理解し、この情報を使用してクエリ生成を基盤にします。
2. **フィードバックに基づく調整**: システムはフィードバックに基づいてユーザーの好みを調整し、スキーマ内のどのフィールドを更新する必要があるかを推論します。
3. **クエリの生成と実行**: システムは新しい好みに基づいて更新されたフライトやホテルデータを取得するクエリを生成・実行します。
以下はこれらの概念を組み込んだPythonコードの例です:
```python
def adjust_based_on_feedback(feedback, preferences, schema):
# Adjust preferences based on user feedback
if "liked" in feedback:
preferences["favorites"] = feedback["liked"]
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
# Reasoning based on schema to adjust other related preferences
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):
# Custom logic to adjust preferences based on schema and feedback
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):
# Generate code to fetch flight data based on updated preferences
return f"fetch_flights(preferences={preferences})"
def generate_code_to_fetch_hotels(preferences):
# Generate code to fetch hotel data based on updated preferences
return f"fetch_hotels(preferences={preferences})"
def execute_code(code):
# Simulate execution of code and return mock data
return {"data": f"Executed: {code}"}
def generate_itinerary(flights, hotels, attractions):
# Generate itinerary based on flights, hotels, and attractions
return {"flights": flights, "hotels": hotels, "attractions": attractions}
# Example schema
schema = {
"favorites": {"positive_adjustment": "increase", "negative_adjustment": "decrease", "default": "neutral"},
"avoid": {"positive_adjustment": "decrease", "negative_adjustment": "increase", "default": "neutral"}
}
# Example usage
preferences = {"favorites": "sightseeing", "avoid": "crowded places"}
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
updated_preferences = adjust_based_on_feedback(feedback, preferences, schema)
# Regenerate and execute code with updated preferences
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)
```
#### 説明 - フィードバックに基づく予約
1. **スキーマ認識**: `schema` dictionary defines how preferences should be adjusted based on feedback. It includes fields like `favorites` and `avoid`, with corresponding adjustments.
2. **Adjusting Preferences (`adjust_based_on_feedback` method)**: This method adjusts preferences based on user feedback and the schema.
3. **Environment-Based Adjustments (`adjust_based_on_environment` メソッド)**: このメソッドはスキーマとフィードバックに基づいて調整をカスタマイズします。
4. **クエリの生成と実行**: システムは調整された好みに基づいて更新されたフライトとホテルデータを取得するコードを生成し、これらのクエリの実行をシミュレートします。
5. **旅程の生成**: システムは新しいフライト、ホテル、観光地のデータに基づいて更新された旅程を作成します。
システムを環境認識型にし、スキーマに基づいて推論することで、より正確で関連性の高いクエリを生成できるようになり、より良い旅行の推奨と個人化されたユーザー体験を提供できます。
### RAG技術としてのSQLの使用
SQL(Structured Query Language)はデータベースと対話するための強力なツールです。RAG(Retrieval-Augmented Generation)アプローチの一部として使用される場合、SQLはデータベースから関連データを取得し、AIエージェントの応答やアクションに情報を提供できます。
#### 重要な概念
1. **データベースとの対話**:
- SQLを使用してデータベースをクエリし、関連情報を取得し、データを操作します。
- 例: フライトの詳細、ホテル情報、観光地を旅行データベースから取得する。
2. **RAGとの統合**:
- SQLクエリはユーザー入力と好みに基づいて生成されます。
- 取得されたデータは、個人化された推奨やアクションを生成するために使用されます。
3. **動的クエリ生成**:
- AIエージェントはコンテキストとユーザーのニーズに基づいて動的なSQLクエリを生成します。
- 例: 予算、日程、興味に基づいて結果をフィルタリングするSQLクエリをカスタマイズする。
#### 応用例
- **自動コード生成**: 特定のタスクに対応するコードスニペットを生成します。
- **RAGとしてのSQL**: データを操作するためにSQLクエリを使用します。
- **問題解決**: 問題を解決するためのコードを作成・実行します。
**例**: データ分析エージェント:
1. **タスク**: データセットを分析してトレンドを見つける。
2. **ステップ**:
- データセットをロードする。
- データをフィルタリングするSQLクエリを生成する。
- クエリを実行して結果を取得する。
- 可視化と洞察を生成する。
3. **リソース**: データセットへのアクセス、SQL機能。
4. **経験**: 過去の結果を使用して将来の分析を改善する。
#### 実践例: 旅行代理店におけるSQLの使用
1. **ユーザーの好みを収集する**
```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
```
2. **SQLクエリを生成する**
```python
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
```
3. **SQLクエリを実行する**
```python
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
```
4. **推奨を生成する**
```python
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)
```
#### SQLクエリの例
1. **フライトクエリ**
```sql
SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate';
```
2. **ホテルクエリ**
```sql
SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate';
```
3. **観光地クエリ**
```sql
SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine';
```
SQLをRAG技術の一部として活用することで、旅行代理店のようなAIエージェントは関連性の高いデータを動的に取得し、正確で個人化された推奨を提供できます。
### 結論
メタ認知はAIエージェントの能力を大幅に向上させる強力なツールです。メタ認知プロセスを組み込むことで、より知的で適応性が高く効率的なエージェントを設計できます。追加のリソースを活用して、AIエージェントにおけるメタ認知の魅力的な世界をさらに探求してください。
```
**免責事項**:
本書類は、機械翻訳AIサービスを使用して翻訳されています。正確性を追求しておりますが、自動翻訳にはエラーや不正確な部分が含まれる可能性があります。原文(元の言語で記載された文書)を公式な情報源としてご参照ください。重要な情報については、専門の人間による翻訳をお勧めします。本翻訳の利用により生じた誤解や誤解釈について、当方は一切の責任を負いません。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/09-metacognition/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/09-metacognition/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 31598
} |
# 本番環境でのAIエージェント
## はじめに
このレッスンでは以下を学びます:
- AIエージェントを本番環境に効果的にデプロイするための計画方法。
- AIエージェントを本番環境にデプロイする際に直面する可能性のある一般的なミスや問題。
- パフォーマンスを維持しつつ、コストを管理する方法。
## 学習目標
このレッスンを終えた後には、以下のことを理解し、実行できるようになります:
- 本番環境でのAIエージェントシステムのパフォーマンス、コスト、効果を向上させるための手法。
- AIエージェントの評価内容と評価方法。
- AIエージェントを本番環境にデプロイする際のコスト管理方法。
信頼できるAIエージェントをデプロイすることは非常に重要です。「Building Trustworthy AI Agents(信頼できるAIエージェントを構築する)」のレッスンもぜひ確認してください。
## AIエージェントの評価
AIエージェントをデプロイする前、デプロイ中、そしてデプロイ後には、適切な評価システムを持つことが重要です。これにより、システムが自分自身やユーザーの目標に沿っていることを確認できます。
AIエージェントを評価する際には、エージェントの出力だけでなく、エージェントが動作するシステム全体を評価できる能力が必要です。これには以下が含まれますが、これらに限定されません:
- 初期のモデルリクエスト。
- ユーザーの意図を正確に把握するエージェントの能力。
- タスクを実行するための適切なツールを特定するエージェントの能力。
- エージェントのリクエストに対するツールの応答。
- ツールの応答を解釈するエージェントの能力。
- エージェントの応答に対するユーザーからのフィードバック。
これにより、改善が必要な領域をよりモジュール的に特定することができます。その後、モデル、プロンプト、ツール、その他のコンポーネントの変更による影響を効率よくモニタリングすることが可能になります。
## AIエージェントにおける一般的な問題とその解決策
| **問題** | **解決策** |
| --------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| タスクを一貫して実行しないAIエージェント | - AIエージェントに与えるプロンプトを改善し、目的を明確にする。<br>- タスクをサブタスクに分割し、複数のエージェントで処理することで効果的になる場合を検討する。 |
| AIエージェントが無限ループに陥る | - プロセスを終了する条件を明確に設定し、エージェントが停止タイミングを認識できるようにする。<br>- 推論や計画を必要とする複雑なタスクの場合、推論に特化した大規模モデルを使用する。 |
| ツール呼び出しがうまく機能しない | - エージェントシステムの外でツールの出力をテスト・検証する。<br>- 定義されたパラメータ、プロンプト、ツールの名前付けを改善する。 |
| マルチエージェントシステムが一貫して動作しない | - 各エージェントに与えるプロンプトを精査し、それぞれが具体的かつ明確に異なるようにする。<br>- "ルーティング" またはコントローラーエージェントを使用して、どのエージェントが適切かを判断する階層型システムを構築する。 |
## コスト管理
AIエージェントを本番環境にデプロイする際のコストを管理するための戦略は以下の通りです:
- **レスポンスのキャッシュ** - 一般的なリクエストやタスクを特定し、それらのレスポンスをエージェントシステムを通さずに提供することで、類似したリクエストの量を減らすことができます。さらに、基本的なAIモデルを使用してリクエストがキャッシュされたリクエストにどれだけ類似しているかを識別するフローを実装することも可能です。
- **小規模モデルの使用** - 小規模言語モデル(SLM)は、特定のエージェントユースケースで良好なパフォーマンスを発揮し、コストを大幅に削減することができます。前述の通り、評価システムを構築して、大規模モデルとのパフォーマンス比較を行い、自分のユースケースでSLMがどの程度うまく機能するかを理解するのが最善です。
- **ルーターモデルの使用** - 類似した戦略として、さまざまなモデルやサイズを使用する方法があります。LLM/SLMやサーバーレス関数を使用してリクエストを複雑さに基づいて最適なモデルにルーティングすることで、コストを削減しつつ、適切なタスクでのパフォーマンスを確保できます。
## おめでとうございます
これで「AI Agents for Beginners」の最後のレッスンが終了しました。
私たちは、この急速に成長する業界の変化やフィードバックに基づいて、今後もレッスンを追加していく予定ですので、ぜひまたお越しください。
AIエージェントについてさらに学び、構築を続けたい場合は、[Azure AI Community Discord](https://discord.gg/kzRShWzttr) に参加してください。
ここでは、ワークショップ、コミュニティラウンドテーブル、"何でも質問" セッションを開催しています。
また、AIエージェントを本番環境で構築するための追加資料が含まれたLearnコレクションもご用意しています。
**免責事項**:
本書類は、機械翻訳AIサービスを使用して翻訳されています。正確性を期しておりますが、自動翻訳にはエラーや不正確な部分が含まれる可能性があることをご承知おきください。原文(原言語の文書)が公式で信頼できる情報源とみなされるべきです。重要な情報については、専門の人間による翻訳をお勧めします。本翻訳の使用に起因する誤解や解釈の相違について、当方は一切の責任を負いかねます。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/10-ai-agents-production/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/10-ai-agents-production/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 3208
} |
# 코스 설정
## 소개
이 강의에서는 코스의 코드 샘플을 실행하는 방법에 대해 다룹니다.
## 요구 사항
- GitHub 계정
- Python 3.12+
## 이 저장소를 클론하거나 포크하기
시작하려면 GitHub 저장소를 클론하거나 포크하세요. 이렇게 하면 코스 자료의 자신의 버전을 만들어 코드를 실행하고, 테스트하고, 수정할 수 있습니다!
이 작업은 [fork the repo](https://github.com/microsoft/ai-agents-for-beginners/fork) 링크를 클릭하여 수행할 수 있습니다.
이제 아래와 같이 강의의 포크된 버전을 가지게 될 것입니다:

## GitHub Personal Access Token (PAT) 가져오기
현재 이 강의는 GitHub Models Marketplace를 사용하여 대형 언어 모델(LLMs)에 무료로 접근할 수 있는 서비스를 제공합니다. 이 모델들은 AI 에이전트를 생성하는 데 사용됩니다.
이 서비스를 사용하려면 GitHub Personal Access Token을 생성해야 합니다.
GitHub 계정에서 [Personal Access Tokens settings](https://github.com/settings/personal-access-tokens)으로 이동하여 생성할 수 있습니다.
화면 왼쪽에서 `Fine-grained tokens` 옵션을 선택하세요.
그런 다음 `Generate new token`를 선택하세요.

방금 생성한 새 토큰을 복사하세요. 이 토큰을 이 강의에 포함된 `.env` 파일에 추가하게 됩니다.
## 환경 변수에 추가하기
`.env` 파일을 생성하려면 터미널에서 아래 명령을 실행하세요:
```bash
cp .env.example .env
```
이 명령은 예제 파일을 복사하여 디렉토리에 `.env` 파일을 생성합니다.
그 파일을 열고 생성한 토큰을 .env 파일의 `GITHUB_TOKEN=` 필드에 붙여넣으세요.
## 필요한 패키지 설치하기
코드를 실행하는 데 필요한 모든 Python 패키지를 설치하려면 터미널에 다음 명령을 실행하세요.
Python 가상 환경을 생성하여 충돌 및 문제를 방지하는 것을 권장합니다.
```bash
pip install -r requirements.txt
```
이 명령은 필요한 Python 패키지를 설치할 것입니다.
이제 코드를 실행할 준비가 되었습니다. AI 에이전트의 세계를 더 배워보세요!
설정 중 문제가 발생하면 [Azure AI Community Discord](https://discord.gg/kzRShWzttr)에서 도움을 요청하거나 [create an issue](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst)를 통해 문제를 보고하세요.
```
**면책 조항**:
이 문서는 AI 기반 기계 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 노력하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원본 문서(원어로 작성된 문서)를 권위 있는 자료로 간주해야 합니다. 중요한 정보의 경우, 전문 번역가에 의한 번역을 권장합니다. 이 번역을 사용함으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/00-course-setup/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/00-course-setup/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 1999
} |
# AI 에이전트 및 에이전트 활용 사례 소개
"초보자를 위한 AI 에이전트" 과정에 오신 것을 환영합니다! 이 과정은 AI 에이전트를 구축하기 위한 기본 지식과 실제 예제를 제공합니다.
다른 학습자 및 AI 에이전트 개발자들과 만나고, 이 과정에 대한 질문을 할 수 있는 [Azure AI Discord 커뮤니티](https://discord.gg/kzRShWzttr)에 참여하세요.
이 과정을 시작하기 전에, AI 에이전트란 무엇인지, 그리고 우리가 구축하는 애플리케이션 및 워크플로에서 이를 어떻게 활용할 수 있는지 더 잘 이해해 보겠습니다.
## 소개
이 강의에서는 다음 내용을 다룹니다:
- AI 에이전트란 무엇이며, 어떤 유형의 에이전트가 있는가?
- AI 에이전트에 적합한 활용 사례는 무엇이며, 이를 통해 어떤 도움을 받을 수 있는가?
- 에이전트 솔루션을 설계할 때 기본적으로 필요한 요소는 무엇인가?
## 학습 목표
이 강의를 마치면 다음을 할 수 있습니다:
- AI 에이전트 개념을 이해하고, 이를 다른 AI 솔루션과 비교할 수 있습니다.
- AI 에이전트를 가장 효율적으로 활용할 수 있습니다.
- 사용자와 고객 모두에게 생산적인 에이전트 솔루션을 설계할 수 있습니다.
## AI 에이전트 정의 및 유형
### AI 에이전트란 무엇인가?
AI 에이전트는 **시스템**으로, **대규모 언어 모델(LLM)**에 **도구**와 **지식**에 대한 접근 권한을 제공하여 **작업을 수행**할 수 있도록 확장된 기능을 제공합니다.
이 정의를 더 작은 부분으로 나눠보겠습니다:
- **시스템** - 에이전트를 단일 구성 요소로 생각하는 것이 아니라 여러 구성 요소로 이루어진 시스템으로 이해하는 것이 중요합니다. AI 에이전트의 기본 구성 요소는 다음과 같습니다:
- **환경** - AI 에이전트가 작동하는 정의된 공간입니다. 예를 들어, 여행 예약 AI 에이전트를 생각해보면, 환경은 에이전트가 작업을 완료하기 위해 사용하는 여행 예약 시스템일 수 있습니다.
- **센서** - 환경은 정보를 제공하고 피드백을 전달합니다. AI 에이전트는 센서를 사용하여 환경의 현재 상태에 대한 정보를 수집하고 해석합니다. 여행 예약 에이전트의 경우, 호텔 가용성이나 항공편 가격과 같은 정보를 제공받을 수 있습니다.
- **액추에이터** - AI 에이전트가 환경의 현재 상태를 받으면, 현재 작업에 대해 환경을 변경하기 위해 어떤 작업을 수행할지 결정합니다. 여행 예약 에이전트의 경우, 사용자를 위해 이용 가능한 방을 예약하는 작업이 될 수 있습니다.

**대규모 언어 모델(LLM)** - 에이전트의 개념은 LLM이 개발되기 전부터 존재했습니다. LLM을 사용하여 AI 에이전트를 구축하는 이점은 인간 언어와 데이터를 해석할 수 있는 능력입니다. 이 능력은 LLM이 환경 정보를 해석하고 환경을 변경하기 위한 계획을 정의할 수 있게 합니다.
**작업 수행** - AI 에이전트 시스템 외부에서는, LLM은 사용자의 프롬프트에 따라 콘텐츠나 정보를 생성하는 상황에 제한됩니다. 그러나 AI 에이전트 시스템 내에서는, LLM이 사용자의 요청을 해석하고 환경 내에서 사용 가능한 도구를 활용하여 작업을 완료할 수 있습니다.
**도구 접근** - LLM이 접근할 수 있는 도구는 1) LLM이 작동하는 환경과 2) AI 에이전트 개발자에 의해 정의됩니다. 예를 들어, 여행 에이전트의 경우, 에이전트의 도구는 예약 시스템에서 제공하는 작업에 의해 제한되며, 개발자는 항공편과 같은 특정 도구 접근을 제한할 수도 있습니다.
**지식** - 환경에서 제공되는 정보 외에도, AI 에이전트는 다른 시스템, 서비스, 도구, 심지어 다른 에이전트로부터 지식을 검색할 수 있습니다. 여행 에이전트의 경우, 이 지식은 고객 데이터베이스에 저장된 사용자의 여행 선호도 정보일 수 있습니다.
### 다양한 에이전트 유형
이제 AI 에이전트의 일반적인 정의를 알았으니, 특정 에이전트 유형과 여행 예약 AI 에이전트에 어떻게 적용될 수 있는지 살펴보겠습니다.
| **에이전트 유형** | **설명** | **예시** |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **단순 반사 에이전트** | 미리 정의된 규칙에 따라 즉각적인 작업을 수행합니다. | 여행 에이전트가 이메일의 맥락을 해석하여 여행 불만 사항을 고객 서비스로 전달합니다. |
| **모델 기반 반사 에이전트** | 세계의 모델과 그 모델의 변화를 기반으로 작업을 수행합니다. | 여행 에이전트가 과거 가격 데이터에 접근하여 가격 변동이 큰 경로를 우선시합니다. |
| **목표 기반 에이전트** | 특정 목표를 달성하기 위해 계획을 세우고, 목표를 해석하여 이를 달성하기 위한 작업을 결정합니다. | 여행 에이전트가 현재 위치에서 목적지까지 필요한 여행 준비(차량, 대중교통, 항공편)를 결정하여 여정을 예약합니다. |
| **효용 기반 에이전트** | 선호도를 고려하고, 수치적으로 트레이드오프를 평가하여 목표를 달성하는 방법을 결정합니다. | 여행 에이전트가 편리함과 비용을 비교하여 최적의 여행을 예약합니다. |
| **학습 에이전트** | 피드백에 응답하여 시간이 지남에 따라 작업을 조정하고 개선합니다. | 여행 에이전트가 여행 후 설문조사에서 받은 고객 피드백을 사용하여 향후 예약을 개선합니다. |
| **계층적 에이전트** | 다중 에이전트를 계층 시스템에서 구성하며, 상위 에이전트가 작업을 하위 에이전트가 완료할 하위 작업으로 나눕니다. | 여행 에이전트가 여행을 취소할 때 작업을 하위 작업(예: 특정 예약 취소)으로 나누고, 하위 에이전트가 이를 완료한 후 상위 에이전트에 보고합니다. |
| **다중 에이전트 시스템(MAS)** | 에이전트가 독립적으로 작업을 완료하며, 협력하거나 경쟁할 수 있습니다. | 협력적: 여러 에이전트가 호텔, 항공편, 엔터테인먼트와 같은 특정 여행 서비스를 예약합니다. 경쟁적: 여러 에이전트가 공유 호텔 예약 캘린더를 관리하고 고객을 호텔에 예약하기 위해 경쟁합니다. |
## AI 에이전트를 사용할 때
앞서 여행 에이전트 사례를 사용하여 다양한 에이전트 유형이 여행 예약의 다양한 시나리오에서 어떻게 사용될 수 있는지 설명했습니다. 이 애플리케이션은 과정 전반에 걸쳐 계속 사용할 것입니다.
AI 에이전트가 가장 적합한 활용 사례 유형을 살펴보겠습니다:

- **개방형 문제** - 워크플로에 작업 단계를 항상 하드코딩할 수 없기 때문에, LLM이 작업을 완료하기 위해 필요한 단계를 스스로 결정하도록 허용합니다.
- **다중 단계 프로세스** - 단일 조회로 해결할 수 없는 도구나 정보를 여러 차례 사용해야 하는 복잡한 작업입니다.
- **시간에 따른 개선** - 에이전트가 환경이나 사용자로부터 피드백을 받아 시간이 지남에 따라 더 나은 효용을 제공할 수 있는 작업입니다.
AI 에이전트를 사용하는 추가적인 고려 사항은 "신뢰할 수 있는 AI 에이전트 구축" 강의에서 다룹니다.
## 에이전트 솔루션의 기본
### 에이전트 개발
AI 에이전트 시스템을 설계하는 첫 번째 단계는 도구, 작업, 행동을 정의하는 것입니다. 이 과정에서는 **Azure AI 에이전트 서비스**를 사용하여 에이전트를 정의하는 방법에 중점을 둡니다. 이 서비스는 다음과 같은 기능을 제공합니다:
- OpenAI, Mistral, Llama와 같은 오픈 모델 선택
- Tripadvisor와 같은 제공자를 통한 라이선스 데이터 사용
- 표준화된 OpenAPI 3.0 도구 사용
### 에이전트 패턴
LLM과의 통신은 프롬프트를 통해 이루어집니다. AI 에이전트는 반자동적인 특성을 가지므로, 환경 변화 이후에 LLM을 수동으로 다시 프롬프트하는 것이 항상 가능하거나 필요하지는 않습니다. 우리는 LLM을 여러 단계에 걸쳐 더 확장 가능하게 프롬프트할 수 있도록 하는 **에이전트 패턴**을 사용합니다.
이 과정은 현재 널리 사용되는 에이전트 패턴을 몇 가지로 나누어 진행됩니다.
### 에이전트 프레임워크
에이전트 프레임워크는 개발자가 코드로 에이전트 패턴을 구현할 수 있도록 합니다. 이러한 프레임워크는 템플릿, 플러그인, 도구를 제공하여 AI 에이전트 간의 협업을 개선합니다. 이를 통해 AI 에이전트 시스템의 관찰성과 문제 해결 능력을 향상시킬 수 있습니다.
이 과정에서는 연구 기반의 AutoGen 프레임워크와 실제 사용 가능한 Semantic Kernel의 Agent 프레임워크를 탐구할 것입니다.
**면책 조항**:
이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 노력하고 있으나, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원본 문서를 해당 언어로 작성된 상태에서 신뢰할 수 있는 권위 있는 자료로 간주해야 합니다. 중요한 정보의 경우, 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/01-intro-to-ai-agents/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/01-intro-to-ai-agents/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 6766
} |
# AI 에이전트 프레임워크 탐구하기
AI 에이전트 프레임워크는 AI 에이전트를 쉽게 생성, 배포, 관리할 수 있도록 설계된 소프트웨어 플랫폼입니다. 이러한 프레임워크는 개발자들에게 사전 구축된 컴포넌트, 추상화 및 도구를 제공하여 복잡한 AI 시스템 개발을 간소화합니다.
이 프레임워크는 AI 에이전트 개발에서 공통적으로 발생하는 문제를 표준화된 방식으로 해결하여 개발자가 애플리케이션의 고유한 측면에 집중할 수 있도록 돕습니다. 이를 통해 AI 시스템 구축에서 확장성, 접근성, 효율성이 향상됩니다.
## 소개
이번 강의에서는 다음을 다룹니다:
- AI 에이전트 프레임워크란 무엇이며, 개발자들이 이를 통해 무엇을 할 수 있는가?
- 팀이 이를 사용하여 에이전트의 기능을 빠르게 프로토타입하고, 반복하고, 개선할 수 있는 방법은 무엇인가?
- Microsoft에서 제공하는 프레임워크 및 도구([Autogen](https://aka.ms/ai-agents/autogen) / [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) / [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service)) 간의 차이점은 무엇인가?
- 기존 Azure 에코시스템 도구를 직접 통합할 수 있는가, 아니면 별도의 솔루션이 필요한가?
- Azure AI Agents 서비스란 무엇이며, 이것이 어떻게 도움이 되는가?
## 학습 목표
이번 강의의 목표는 다음을 이해하는 것입니다:
- AI 에이전트 프레임워크가 AI 개발에서 가지는 역할.
- AI 에이전트 프레임워크를 활용하여 지능형 에이전트를 구축하는 방법.
- AI 에이전트 프레임워크로 활성화되는 주요 기능.
- Autogen, Semantic Kernel, Azure AI Agent Service 간의 차이점.
## AI 에이전트 프레임워크란 무엇이며, 개발자들이 이를 통해 무엇을 할 수 있는가?
전통적인 AI 프레임워크는 AI를 앱에 통합하고 앱의 성능을 다음과 같은 방식으로 향상시킬 수 있도록 도와줍니다:
- **개인화**: AI는 사용자 행동과 선호도를 분석하여 개인화된 추천, 콘텐츠, 경험을 제공합니다.
예: Netflix와 같은 스트리밍 서비스는 시청 기록을 기반으로 영화를 추천하여 사용자 만족도를 높입니다.
- **자동화 및 효율성**: AI는 반복적인 작업을 자동화하고 워크플로를 간소화하며 운영 효율성을 향상시킬 수 있습니다.
예: 고객 서비스 앱은 AI 기반 챗봇을 활용하여 일반적인 문의를 처리하고, 응답 시간을 단축하며, 복잡한 문제는 인간 상담원이 처리할 수 있도록 합니다.
- **향상된 사용자 경험**: AI는 음성 인식, 자연어 처리, 예측 텍스트와 같은 지능형 기능을 제공하여 전반적인 사용자 경험을 개선합니다.
예: Siri와 Google Assistant와 같은 가상 비서는 AI를 활용하여 음성 명령을 이해하고 응답하여 사용자와의 상호작용을 더 쉽게 만듭니다.
### 모두 훌륭해 보이지만, 왜 AI 에이전트 프레임워크가 필요한가요?
AI 에이전트 프레임워크는 단순한 AI 프레임워크 이상의 것을 제공합니다. 이 프레임워크는 사용자가 지정한 목표를 달성하기 위해 사용자, 다른 에이전트, 환경과 상호작용할 수 있는 지능형 에이전트를 생성할 수 있도록 설계되었습니다. 이러한 에이전트는 자율적으로 행동하고, 의사 결정을 내리며, 변화하는 상황에 적응할 수 있습니다. 다음은 AI 에이전트 프레임워크가 제공하는 주요 기능입니다:
- **에이전트 간 협업 및 조정**: 여러 AI 에이전트를 생성하여 협력, 커뮤니케이션, 조정을 통해 복잡한 작업을 해결할 수 있습니다.
- **작업 자동화 및 관리**: 다단계 워크플로의 자동화, 작업 위임, 에이전트 간 동적 작업 관리를 위한 메커니즘을 제공합니다.
- **맥락 이해 및 적응**: 에이전트가 맥락을 이해하고, 변화하는 환경에 적응하며, 실시간 정보를 기반으로 의사 결정을 내릴 수 있는 기능을 제공합니다.
결론적으로, 에이전트는 더 많은 일을 가능하게 하고, 자동화를 한 단계 더 발전시키며, 환경에서 학습하고 적응할 수 있는 더 지능적인 시스템을 만들 수 있게 합니다.
## 에이전트의 기능을 빠르게 프로토타입하고, 반복하고, 개선하는 방법은?
이 분야는 빠르게 발전하고 있지만, 대부분의 AI 에이전트 프레임워크에서 공통적으로 활용할 수 있는 몇 가지 요소가 있습니다. 모듈형 컴포넌트, 협업 도구, 실시간 학습이 그 예입니다. 자세히 살펴보겠습니다:
- **모듈형 컴포넌트 사용**: AI 프레임워크는 프롬프트, 파서, 메모리 관리와 같은 사전 구축된 컴포넌트를 제공합니다.
- **협업 도구 활용**: 특정 역할과 작업을 가진 에이전트를 설계하여 협업 워크플로를 테스트하고 개선할 수 있습니다.
- **실시간 학습**: 피드백 루프를 구현하여 에이전트가 상호작용에서 학습하고 동적으로 행동을 조정하도록 합니다.
### 모듈형 컴포넌트 사용
LangChain 및 Microsoft Semantic Kernel과 같은 프레임워크는 프롬프트, 파서, 메모리 관리와 같은 사전 구축된 컴포넌트를 제공합니다.
**팀이 이를 사용하는 방법**: 팀은 이러한 컴포넌트를 빠르게 조립하여 기능적인 프로토타입을 만들 수 있습니다. 이는 처음부터 시작하지 않고도 빠르게 실험하고 반복할 수 있도록 합니다.
**실제 작동 방식**: 사전 구축된 파서를 사용하여 사용자 입력에서 정보를 추출하거나, 메모리 모듈을 사용하여 데이터를 저장 및 검색하거나, 프롬프트 생성기를 사용하여 사용자와 상호작용할 수 있습니다. 이를 통해 고수준의 논리에 집중할 수 있습니다.
**예제 코드**. 사용자 입력에서 정보를 추출하기 위해 사전 구축된 파서를 사용하는 예제를 살펴보겠습니다:
```python
from langchain import Parser
parser = Parser()
user_input = "Book a flight from New York to London on July 15th"
parsed_data = parser.parse(user_input)
print(parsed_data)
# Output: {'origin': 'New York', 'destination': 'London', 'date': 'July 15th'}
```
이 예제에서 볼 수 있듯이, 사전 구축된 파서를 활용하여 비행 예약 요청의 출발지, 목적지, 날짜와 같은 주요 정보를 추출할 수 있습니다. 이러한 모듈형 접근 방식은 고수준의 논리에 집중할 수 있게 합니다.
### 협업 도구 활용
CrewAI 및 Microsoft Autogen과 같은 프레임워크는 여러 에이전트를 생성하여 협력할 수 있도록 지원합니다.
**팀이 이를 사용하는 방법**: 팀은 특정 역할과 작업을 가진 에이전트를 설계하여 협업 워크플로를 테스트하고 개선하며, 전체 시스템 효율성을 높일 수 있습니다.
**실제 작동 방식**: 데이터 검색, 분석, 의사 결정과 같은 특정 기능을 가진 에이전트 팀을 생성할 수 있습니다. 이러한 에이전트는 정보를 공유하고 사용자 질의에 응답하거나 작업을 완료하기 위해 협력할 수 있습니다.
**예제 코드 (Autogen)**:
```python
# creating agents, then create a round robin schedule where they can work together, in this case in order
# Data Retrieval Agent
# Data Analysis Agent
# Decision Making Agent
agent_retrieve = AssistantAgent(
name="dataretrieval",
model_client=model_client,
tools=[retrieve_tool],
system_message="Use tools to solve tasks."
)
agent_analyze = AssistantAgent(
name="dataanalysis",
model_client=model_client,
tools=[analyze_tool],
system_message="Use tools to solve tasks."
)
# conversation ends when user says "APPROVE"
termination = TextMentionTermination("APPROVE")
user_proxy = UserProxyAgent("user_proxy", input_func=input)
team = RoundRobinGroupChat([agent_retrieve, agent_analyze, user_proxy], termination_condition=termination)
stream = team.run_stream(task="Analyze data", max_turns=10)
# Use asyncio.run(...) when running in a script.
await Console(stream)
```
위 코드에서 볼 수 있듯이, 여러 에이전트가 데이터를 분석하는 작업을 함께 수행하도록 설계할 수 있습니다. 각 에이전트는 특정 기능을 수행하며, 협력을 통해 원하는 결과를 달성합니다. 특정 역할을 가진 에이전트를 생성함으로써 작업 효율성과 성능을 향상시킬 수 있습니다.
### 실시간 학습
고급 프레임워크는 실시간 맥락 이해 및 적응 기능을 제공합니다.
**팀이 이를 사용하는 방법**: 팀은 피드백 루프를 구현하여 에이전트가 상호작용에서 학습하고 동적으로 행동을 조정하도록 하여 지속적으로 능력을 개선하고 정제할 수 있습니다.
**실제 작동 방식**: 에이전트는 사용자 피드백, 환경 데이터, 작업 결과를 분석하여 지식 기반을 업데이트하고, 의사 결정 알고리즘을 조정하며, 성능을 개선합니다. 이러한 반복 학습 프로세스를 통해 에이전트는 변화하는 조건과 사용자 선호도에 적응하며, 시스템의 전반적인 효과를 향상시킬 수 있습니다.
## Autogen, Semantic Kernel, Azure AI Agent Service 간의 차이점은 무엇인가?
이 프레임워크들을 비교하는 방법은 여러 가지가 있지만, 설계, 기능, 주요 사용 사례 측면에서 몇 가지 핵심 차이점을 살펴보겠습니다:
## Autogen
Microsoft Research의 AI Frontiers Lab에서 개발한 오픈소스 프레임워크입니다. 이벤트 기반, 분산된 *에이전트 기반* 애플리케이션에 중점을 두며, 여러 LLM 및 SLM, 도구, 고급 다중 에이전트 설계 패턴을 지원합니다.
Autogen은 에이전트를 중심으로 설계되었습니다. 에이전트는 환경을 인식하고, 의사 결정을 내리고, 특정 목표를 달성하기 위해 행동하는 자율적인 엔터티입니다. 에이전트는 비동기 메시지를 통해 통신하여 독립적이고 병렬로 작업할 수 있으며, 시스템의 확장성과 응답성을 향상시킵니다.
에이전트는 [액터 모델](https://en.wikipedia.org/wiki/Actor_model)을 기반으로 합니다. Wikipedia에 따르면, 액터는 _동시 계산의 기본 구성 요소로서, 수신된 메시지에 응답하여 로컬 결정을 내리고, 새로운 액터를 생성하며, 메시지를 보내고, 다음 메시지에 어떻게 응답할지 결정할 수 있습니다._
**사용 사례**: 코드 생성 자동화, 데이터 분석 작업, 계획 및 연구 기능을 위한 맞춤형 에이전트 구축.
Autogen의 핵심 개념에 대한 설명은 계속됩니다...
```
```markdown
프로젝트 목표를 기반으로 합니다. 자연어 이해 및 콘텐츠 생성에 이상적입니다.
- **Azure AI Agent Service**: 유연한 모델, 엔터프라이즈 보안 메커니즘, 데이터 저장 방법. 엔터프라이즈 애플리케이션에서 안전하고 확장 가능하며 유연한 AI 에이전트 배포에 이상적입니다.
## 기존 Azure 에코시스템 도구를 직접 통합할 수 있나요, 아니면 독립형 솔루션이 필요하나요?
답은 예입니다. Azure AI Agent Service는 다른 Azure 서비스와 원활하게 작동하도록 설계되었기 때문에 기존 Azure 에코시스템 도구를 직접 통합할 수 있습니다. 예를 들어 Bing, Azure AI Search, Azure Functions를 통합할 수 있습니다. 또한 Azure AI Foundry와 깊은 통합이 가능합니다.
Autogen 및 Semantic Kernel의 경우에도 Azure 서비스와 통합할 수 있지만, 이를 위해 코드에서 Azure 서비스를 호출해야 할 수 있습니다. 또 다른 통합 방법은 Azure SDK를 사용하여 에이전트에서 Azure 서비스와 상호 작용하는 것입니다.
추가적으로, 앞서 언급했듯이 Autogen 또는 Semantic Kernel에서 구축된 에이전트를 위한 오케스트레이터로 Azure AI Agent Service를 사용할 수 있으며, 이를 통해 Azure 에코시스템에 쉽게 접근할 수 있습니다.
## 참고 문헌
- [1] - [Azure Agent Service](https://techcommunity.microsoft.com/blog/azure-ai-services-blog/introducing-azure-ai-agent-service/4298357)
- [2] - [Semantic Kernel and Autogen](https://devblogs.microsoft.com/semantic-kernel/microsofts-agentic-ai-frameworks-autogen-and-semantic-kernel/)
- [3] - [Semantic Kernel Agent Framework](https://learn.microsoft.com/semantic-kernel/frameworks/agent/?pivots=programming-language-csharp)
- [4] - [Azure AI Agent service](https://learn.microsoft.com/azure/ai-services/agents/overview)
- [5] - [Using Azure AI Agent Service with AutoGen / Semantic Kernel to build a multi-agent's solution](https://techcommunity.microsoft.com/blog/educatordeveloperblog/using-azure-ai-agent-service-with-autogen--semantic-kernel-to-build-a-multi-agen/4363121)
```
**면책 조항**:
이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 최선을 다하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원본 문서의 모국어 버전을 권위 있는 출처로 간주해야 합니다. 중요한 정보에 대해서는 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/02-explore-agentic-frameworks/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/02-explore-agentic-frameworks/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 7655
} |
# AI 에이전트 설계 원칙
## 소개
AI 에이전트 시스템을 구축하는 방법에는 여러 가지가 있습니다. 생성형 AI 설계에서 모호성이 결함이 아니라 특징이라는 점을 고려할 때, 엔지니어들이 어디서부터 시작해야 할지 막막해하는 경우가 많습니다. 우리는 개발자들이 고객 중심의 에이전트 시스템을 설계하여 비즈니스 요구를 해결할 수 있도록 돕는 인간 중심의 UX 설계 원칙을 만들었습니다. 이 설계 원칙은 처방적인 아키텍처가 아니라, 에이전트 경험을 정의하고 구축하려는 팀에게 출발점을 제공하기 위한 것입니다.
일반적으로, 에이전트는 다음을 목표로 해야 합니다:
- 인간의 역량을 확장하고 규모를 키우기 (브레인스토밍, 문제 해결, 자동화 등)
- 지식 격차 메우기 (새로운 지식 영역 습득, 번역 등)
- 우리가 다른 사람들과 협업하는 방식을 지원하고 촉진하기
- 더 나은 자신이 되도록 돕기 (예: 라이프 코치/작업 관리자, 감정 조절 및 마음챙김 기술 학습 지원, 회복력 구축 등)
## 이 강의에서 다룰 내용
- 에이전트 설계 원칙이란 무엇인가
- 이 설계 원칙을 구현할 때 따라야 할 가이드라인
- 설계 원칙을 활용한 사례
## 학습 목표
이 강의를 완료한 후, 여러분은 다음을 할 수 있습니다:
1. 에이전트 설계 원칙이 무엇인지 설명할 수 있다
2. 에이전트 설계 원칙을 사용할 때의 가이드라인을 설명할 수 있다
3. 에이전트 설계 원칙을 사용하여 에이전트를 구축하는 방법을 이해할 수 있다
## 에이전트 설계 원칙

### 에이전트 (공간)
이는 에이전트가 작동하는 환경을 의미합니다. 이러한 원칙은 물리적 및 디지털 세계에서의 에이전트 설계를 안내합니다.
- **연결하되 붕괴시키지 않기** – 사람들, 이벤트, 실행 가능한 지식을 연결하여 협업과 연결을 가능하게 한다.
- 에이전트는 이벤트, 지식, 사람들을 연결하는 데 도움을 준다.
- 에이전트는 사람들을 더 가까이 연결한다. 사람을 대체하거나 폄하하기 위해 설계된 것이 아니다.
- **쉽게 접근 가능하지만 때로는 보이지 않게** – 에이전트는 주로 배경에서 작동하며, 관련성과 적절함이 있을 때만 사용자에게 신호를 보낸다.
- 에이전트는 모든 디바이스나 플랫폼에서 인증된 사용자에게 쉽게 발견되고 접근 가능해야 한다.
- 에이전트는 다중 모드 입력 및 출력(소리, 음성, 텍스트 등)을 지원한다.
- 에이전트는 사용자 요구를 감지하여 전경과 배경, 능동적 상태와 수동적 상태를 원활히 전환할 수 있다.
- 에이전트는 보이지 않는 형태로 작동할 수 있지만, 그 배경 프로세스 경로와 다른 에이전트와의 협업은 사용자에게 투명하고 제어 가능해야 한다.
### 에이전트 (시간)
이는 에이전트가 시간에 따라 작동하는 방식을 의미합니다. 이러한 원칙은 과거, 현재, 미래에 걸쳐 상호작용하는 에이전트를 설계하는 데 도움을 줍니다.
- **과거**: 상태와 맥락을 포함한 역사를 반영하기.
- 에이전트는 단순히 이벤트, 사람 또는 상태뿐만 아니라 더 풍부한 역사적 데이터를 분석하여 더 관련성 높은 결과를 제공한다.
- 에이전트는 과거 이벤트에서 연결을 생성하고, 현재 상황에 참여하기 위해 기억을 적극적으로 반영한다.
- **현재**: 알림을 넘어 유도하기.
- 에이전트는 사람들과 상호작용하는 데 있어 종합적인 접근 방식을 구현한다. 이벤트가 발생했을 때, 단순한 알림이나 형식적인 방식에 그치지 않고, 사용자 주의를 적시에 끌 수 있도록 동적 신호를 생성하거나 흐름을 단순화한다.
- 에이전트는 맥락 환경, 사회적/문화적 변화, 사용자 의도에 맞춰 정보를 전달한다.
- 에이전트와의 상호작용은 점진적이고, 장기적으로 사용자에게 권한을 부여할 수 있도록 복잡성이 진화/성장할 수 있다.
- **미래**: 적응하고 진화하기.
- 에이전트는 다양한 디바이스, 플랫폼, 모달리티에 적응한다.
- 에이전트는 사용자 행동, 접근성 요구에 적응하며, 자유롭게 사용자화할 수 있다.
- 에이전트는 지속적인 사용자 상호작용을 통해 형성되고 진화한다.
### 에이전트 (핵심)
이는 에이전트 설계의 핵심 요소들입니다.
- **불확실성을 수용하되 신뢰를 구축하기**.
- 에이전트 설계에서 어느 정도의 불확실성은 예상된다. 불확실성은 에이전트 설계의 중요한 요소이다.
- 신뢰와 투명성은 에이전트 설계의 기본적인 층이다.
- 에이전트가 켜져 있거나 꺼져 있는 상태는 항상 명확히 표시되며, 인간이 이를 제어할 수 있다.
## 이 원칙을 구현하기 위한 가이드라인
위의 설계 원칙을 사용할 때는 다음의 가이드라인을 따르세요:
1. **투명성**: 사용자에게 AI가 포함되어 있음을 알리고, 그것이 어떻게 작동하는지(과거 행동 포함), 피드백 제공 및 시스템 수정 방법을 알려준다.
2. **제어**: 사용자가 시스템 및 속성(예: 잊기 기능 포함)을 사용자화하고 선호도를 지정하며 제어할 수 있도록 한다.
3. **일관성**: 디바이스와 엔드포인트 전반에 걸쳐 일관된 다중 모드 경험을 목표로 한다. 가능한 경우 익숙한 UI/UX 요소를 사용하고(예: 음성 상호작용을 위한 마이크 아이콘), 고객의 인지적 부담을 최대한 줄인다(예: 간결한 응답, 시각적 도움 자료, ‘더 알아보기’ 콘텐츠 제공).
## 이 원칙과 가이드라인을 사용하여 여행 에이전트 설계하기
여행 에이전트를 설계한다고 가정해 봅시다. 다음은 설계 원칙과 가이드라인을 활용하는 방법입니다:
1. **투명성** – 여행 에이전트가 AI 기반 에이전트임을 사용자에게 알립니다. 시작하는 방법에 대한 기본 지침을 제공합니다(예: "안녕하세요" 메시지, 샘플 프롬프트). 이를 제품 페이지에 명확히 문서화합니다. 사용자가 과거에 요청한 프롬프트 목록을 표시합니다. 피드백 제공 방법(좋아요/싫어요 버튼, 피드백 보내기 버튼 등)을 명확히 합니다. 에이전트가 사용 제한이나 주제 제한이 있는 경우 이를 명확히 설명합니다.
2. **제어** – 에이전트를 생성한 후 수정할 수 있는 방법(예: 시스템 프롬프트)을 명확히 합니다. 에이전트의 응답 길이, 글쓰기 스타일, 다루지 말아야 할 주제 등을 사용자가 선택할 수 있도록 합니다. 사용자에게 관련 파일이나 데이터, 프롬프트, 과거 대화를 확인하고 삭제할 수 있는 기능을 제공합니다.
3. **일관성** – 프롬프트 공유, 파일 또는 사진 추가, 태그 지정 등을 나타내는 아이콘이 표준적이고 알아보기 쉽게 만듭니다. 파일 업로드/공유를 나타내는 클립 아이콘과 그래픽 업로드를 나타내는 이미지 아이콘을 사용합니다.
## 추가 자료
- [Practices for Governing Agentic AI Systems | OpenAI](https://openai.com)
- [The HAX Toolkit Project - Microsoft Research](https://microsoft.com)
- [Responsible AI Toolbox](https://responsibleaitoolbox.ai)
**면책 조항**:
이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 최선을 다하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원어로 작성된 원본 문서를 신뢰할 수 있는 권위 있는 자료로 간주해야 합니다. 중요한 정보의 경우, 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 오역에 대해 당사는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/03-agentic-design-patterns/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/03-agentic-design-patterns/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 3932
} |
# 도구 사용 설계 패턴
## 소개
이 강의에서는 다음 질문들에 답하려고 합니다:
- 도구 사용 설계 패턴이란 무엇인가요?
- 이 패턴이 적용될 수 있는 사용 사례는 무엇인가요?
- 이 설계 패턴을 구현하기 위해 필요한 요소/구성 요소는 무엇인가요?
- 신뢰할 수 있는 AI 에이전트를 구축하기 위해 도구 사용 설계 패턴을 사용할 때의 특별한 고려사항은 무엇인가요?
## 학습 목표
이 강의를 완료한 후, 여러분은 다음을 할 수 있습니다:
- 도구 사용 설계 패턴과 그 목적을 정의합니다.
- 도구 사용 설계 패턴이 적용 가능한 사용 사례를 식별합니다.
- 이 설계 패턴을 구현하는 데 필요한 핵심 요소를 이해합니다.
- 이 설계 패턴을 사용하는 AI 에이전트에서 신뢰성을 보장하기 위한 고려사항을 인식합니다.
## 도구 사용 설계 패턴이란 무엇인가요?
**도구 사용 설계 패턴**은 LLM(Large Language Models)이 특정 목표를 달성하기 위해 외부 도구와 상호작용할 수 있도록 하는 데 중점을 둡니다. 도구는 작업을 수행하기 위해 에이전트가 실행할 수 있는 코드입니다. 도구는 계산기와 같은 간단한 함수일 수도 있고, 주식 가격 조회나 날씨 예보와 같은 타사 서비스의 API 호출일 수도 있습니다. AI 에이전트의 맥락에서, 도구는 **모델이 생성한 함수 호출**에 응답하여 에이전트가 실행할 수 있도록 설계됩니다.
## 이 패턴이 적용될 수 있는 사용 사례는 무엇인가요?
AI 에이전트는 도구를 활용하여 복잡한 작업을 완료하거나, 정보를 검색하거나, 결정을 내릴 수 있습니다. 도구 사용 설계 패턴은 데이터베이스, 웹 서비스 또는 코드 해석기와 같은 외부 시스템과 동적으로 상호작용해야 하는 시나리오에서 자주 사용됩니다. 이 능력은 다음과 같은 다양한 사용 사례에서 유용합니다:
- **동적 정보 검색:** 에이전트는 외부 API나 데이터베이스를 쿼리하여 최신 데이터를 가져올 수 있습니다(예: SQLite 데이터베이스를 쿼리하여 데이터 분석, 주식 가격 또는 날씨 정보 검색).
- **코드 실행 및 해석:** 에이전트는 수학 문제를 해결하거나, 보고서를 생성하거나, 시뮬레이션을 수행하기 위해 코드나 스크립트를 실행할 수 있습니다.
- **워크플로 자동화:** 작업 스케줄러, 이메일 서비스, 데이터 파이프라인과 같은 도구를 통합하여 반복적이거나 다단계 워크플로를 자동화합니다.
- **고객 지원:** 에이전트는 CRM 시스템, 티켓 발급 플랫폼 또는 지식 기반과 상호작용하여 사용자 문의를 해결할 수 있습니다.
- **콘텐츠 생성 및 편집:** 에이전트는 문법 검사기, 텍스트 요약기 또는 콘텐츠 안전성 평가기와 같은 도구를 활용하여 콘텐츠 생성 작업을 지원할 수 있습니다.
## 이 설계 패턴을 구현하기 위해 필요한 요소/구성 요소는 무엇인가요?
### 함수/도구 호출
함수 호출은 LLM이 도구와 상호작용할 수 있도록 하는 주요 방법입니다. '함수'와 '도구'라는 용어는 종종 혼용되는데, 이는 '함수'(재사용 가능한 코드 블록)가 에이전트가 작업을 수행하기 위해 사용하는 '도구'이기 때문입니다. 함수의 코드가 호출되기 위해서는 LLM이 사용자 요청을 함수 설명과 비교해야 합니다. 이를 위해 사용 가능한 모든 함수의 설명을 포함한 스키마가 LLM에 전달됩니다. LLM은 작업에 가장 적합한 함수를 선택하고 함수 이름과 인수를 반환합니다. 선택된 함수가 호출되고, 그 응답이 LLM에 다시 전달되어 사용자의 요청에 응답합니다.
에이전트를 위한 함수 호출을 구현하려면 다음이 필요합니다:
1. 함수 호출을 지원하는 LLM 모델
2. 함수 설명을 포함한 스키마
3. 설명된 각 함수의 코드
도시의 현재 시간을 가져오는 예제를 사용해 보겠습니다:
- **함수 호출을 지원하는 LLM 초기화:**
모든 모델이 함수 호출을 지원하는 것은 아니므로, 사용하는 LLM이 이를 지원하는지 확인하는 것이 중요합니다. [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/how-to/function-calling)는 함수 호출을 지원합니다. Azure OpenAI 클라이언트를 초기화하는 것으로 시작할 수 있습니다.
```python
# Initialize the Azure OpenAI client
client = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2024-05-01-preview"
)
```
- **함수 스키마 생성:**
다음으로, 함수 이름, 함수가 수행하는 작업에 대한 설명, 함수 매개변수의 이름과 설명을 포함하는 JSON 스키마를 정의합니다. 그런 다음 이 스키마를 위에서 생성한 클라이언트와 함께 사용자의 요청(예: 샌프란시스코의 시간을 찾기 위해)과 함께 전달합니다. 중요한 점은 **도구 호출**이 반환된다는 것이며, **최종 답변**이 아니라는 것입니다. 앞서 언급했듯이, LLM은 작업에 대해 선택된 함수 이름과 전달될 인수를 반환합니다.
```python
# Function description for the model to read
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Get the current time in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
},
"required": ["location"],
},
}
}
]
```
```python
# Initial user message
messages = [{"role": "user", "content": "What's the current time in San Francisco"}]
# First API call: Ask the model to use the function
response = client.chat.completions.create(
model=deployment_name,
messages=messages,
tools=tools,
tool_choice="auto",
)
# Process the model's response
response_message = response.choices[0].message
messages.append(response_message)
print("Model's response:")
print(response_message)
```
```bash
Model's response:
ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_pOsKdUlqvdyttYB67MOj434b', function=Function(arguments='{"location":"San Francisco"}', name='get_current_time'), type='function')])
```
- **작업을 수행하기 위한 함수 코드:**
이제 LLM이 실행할 함수를 선택했으므로, 작업을 수행할 코드를 구현하고 실행해야 합니다. Python으로 현재 시간을 가져오는 코드를 구현할 수 있습니다. 또한 `response_message`에서 이름과 인수를 추출하여 최종 결과를 얻는 코드를 작성해야 합니다.
```python
def get_current_time(location):
"""Get the current time for a given location"""
print(f"get_current_time called with location: {location}")
location_lower = location.lower()
for key, timezone in TIMEZONE_DATA.items():
if key in location_lower:
print(f"Timezone found for {key}")
current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p")
return json.dumps({
"location": location,
"current_time": current_time
})
print(f"No timezone data found for {location_lower}")
return json.dumps({"location": location, "current_time": "unknown"})
```
```python
# Handle function calls
if response_message.tool_calls:
for tool_call in response_message.tool_calls:
if tool_call.function.name == "get_current_time":
function_args = json.loads(tool_call.function.arguments)
time_response = get_current_time(
location=function_args.get("location")
)
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": "get_current_time",
"content": time_response,
})
else:
print("No tool calls were made by the model.")
# Second API call: Get the final response from the model
final_response = client.chat.completions.create(
model=deployment_name,
messages=messages,
)
return final_response.choices[0].message.content
```
```bash
get_current_time called with location: San Francisco
Timezone found for san francisco
The current time in San Francisco is 09:24 AM.
```
함수 호출은 대부분의, 아니면 모든 에이전트 도구 사용 설계의 핵심에 있지만, 이를 처음부터 구현하는 것은 때로 도전적일 수 있습니다.
[Lesson 2](../../../02-explore-agentic-frameworks)에서 배운 것처럼 에이전트 프레임워크는 도구 사용을 구현하기 위한 사전 구축된 구성 요소를 제공합니다.
### 에이전트 프레임워크를 활용한 도구 사용 예제
- ### **[Semantic Kernel](https://learn.microsoft.com/azure/ai-services/agents/overview)**
Semantic Kernel은 LLM(Large Language Models)을 사용하는 .NET, Python, Java 개발자를 위한 오픈소스 AI 프레임워크입니다. 이 프레임워크는 [직렬화](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions)라는 과정을 통해 함수와 매개변수를 모델에 자동으로 설명하여 함수 호출 과정을 간소화합니다. 또한, 모델과 코드 간의 통신을 자동으로 처리합니다. Semantic Kernel과 같은 에이전트 프레임워크를 사용하는 또 다른 장점은 [파일 검색](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step4_assistant_tool_file_search.py) 및 [코드 해석기](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py)와 같은 사전 구축된 도구를 사용할 수 있다는 점입니다.
다음 다이어그램은 Semantic Kernel에서의 함수 호출 프로세스를 보여줍니다:

Semantic Kernel에서 함수/도구는 [플러그인](https://learn.microsoft.com/semantic-kernel/concepts/plugins/?pivots=programming-language-python)이라고 불립니다. `get_current_time` function we saw earlier into a plugin by turning it into a class with the function in it. We can also import the `kernel_function` 데코레이터를 사용하여 함수 설명을 전달할 수 있습니다. 그런 다음 GetCurrentTimePlugin과 함께 커널을 생성하면 커널이 함수와 매개변수를 자동으로 직렬화하여 LLM에 보낼 스키마를 생성합니다.
```python
from semantic_kernel.functions import kernel_function
class GetCurrentTimePlugin:
async def __init__(self, location):
self.location = location
@kernel_function(
description="Get the current time for a given location"
)
def get_current_time(location: str = ""):
...
```
```python
from semantic_kernel import Kernel
# Create the kernel
kernel = Kernel()
# Create the plugin
get_current_time_plugin = GetCurrentTimePlugin(location)
# Add the plugin to the kernel
kernel.add_plugin(get_current_time_plugin)
```
- ### **[Azure AI Agent Service](https://learn.microsoft.com/azure/ai-services/agents/overview)**
Azure AI Agent Service는 개발자가 고품질의 확장 가능한 AI 에이전트를 안전하게 구축, 배포, 확장할 수 있도록 설계된 새로운 에이전트 프레임워크입니다. 이 서비스는 기본 컴퓨팅 및 스토리지 리소스를 관리할 필요가 없기 때문에 특히 엔터프라이즈 애플리케이션에 유용합니다.
LLM API를 직접 사용하는 것과 비교했을 때, Azure AI Agent Service는 다음과 같은 장점을 제공합니다:
- 자동 도구 호출 – 도구 호출을 구문 분석하고, 도구를 호출하며, 응답을 처리할 필요가 없음; 모든 작업이 서버 측에서 처리됨
- 안전하게 관리되는 데이터 – 대화 상태를 직접 관리하는 대신, 스레드를 사용하여 필요한 모든 정보를 저장 가능
- 기본 제공 도구 – Bing, Azure AI Search, Azure Functions와 같은 데이터 소스와 상호작용할 수 있는 도구 사용 가능
Azure AI Agent Service에서 사용할 수 있는 도구는 두 가지 범주로 나뉩니다:
1. 지식 도구:
- [Bing 검색을 통한 정보 기반](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/bing-grounding?tabs=python&pivots=overview)
- [파일 검색](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/file-search?tabs=python&pivots=overview)
- [Azure AI Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-ai-search?tabs=azurecli%2Cpython&pivots=overview-azure-ai-search)
2. 액션 도구:
- [함수 호출](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/function-calling?tabs=python&pivots=overview)
- [코드 해석기](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/code-interpreter?tabs=python&pivots=overview)
- [OpenAI 정의 도구](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/openapi-spec?tabs=python&pivots=overview)
- [Azure Functions](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-functions?pivots=overview)
Agent Service를 사용하면 사용자 요청에 따라 `toolset`. It also utilizes `threads` which keep track of the history of messages from a particular conversation.
Imagine you are a sales agent at a company called Contoso. You want to develop a conversational agent that can answer questions about your sales data.
The image below illustrates how you could use Azure AI Agent Service to analyze your sales data:

To use any of these tools with the service we can create a client and define a tool or toolset. To implement this practically we can use the Python code below. The LLM will be able to look at the toolset and decide whether to use the user created function, `fetch_sales_data_using_sqlite_query` 또는 사전 구축된 코드 해석기를 함께 사용할 수 있습니다.
```python
import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from fecth_sales_data_functions import fetch_sales_data_using_sqlite_query # fetch_sales_data_using_sqlite_query function which can be found in a fecth_sales_data_functions.py file.
from azure.ai.projects.models import ToolSet, FunctionTool, CodeInterpreterTool
project_client = AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(),
conn_str=os.environ["PROJECT_CONNECTION_STRING"],
)
# Initialize function calling agent with the fetch_sales_data_using_sqlite_query function and adding it to the toolset
fetch_data_function = FunctionTool(fetch_sales_data_using_sqlite_query)
toolset = ToolSet()
toolset.add(fetch_data_function)
# Initialize Code Interpreter tool and adding it to the toolset.
code_interpreter = code_interpreter = CodeInterpreterTool()
toolset = ToolSet()
toolset.add(code_interpreter)
agent = project_client.agents.create_agent(
model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent",
toolset=toolset
)
```
## 신뢰할 수 있는 AI 에이전트를 구축하기 위해 도구 사용 설계 패턴을 사용할 때의 특별한 고려사항은 무엇인가요?
LLM이 동적으로 생성한 SQL과 관련된 일반적인 우려 사항은 SQL 삽입이나 데이터베이스 삭제 또는 조작과 같은 악의적인 작업의 위험입니다. 이러한 우려는 타당하지만, 데이터베이스 액세스 권한을 적절히 구성하면 효과적으로 완화할 수 있습니다. 대부분의 데이터베이스에서는 데이터베이스를 읽기 전용으로 구성하는 것이 포함됩니다. PostgreSQL 또는 Azure SQL과 같은 데이터베이스 서비스의 경우, 앱에 읽기 전용(SELECT) 역할을 할당해야 합니다.
앱을 안전한 환경에서 실행하면 보호 수준이 더욱 강화됩니다. 엔터프라이즈 시나리오에서는 데이터를 읽기 전용 데이터베이스 또는 사용자 친화적인 스키마를 갖춘 데이터 웨어하우스로 변환하여 운영 시스템에서 데이터를 추출하는 경우가 일반적입니다. 이러한 접근 방식은 데이터를 안전하게 유지하고, 성능과 접근성을 최적화하며, 앱이 제한된 읽기 전용 액세스만 가지도록 보장합니다.
## 추가 자료
- [Azure AI Agents Service Workshop](https://microsoft.github.io/build-your-first-agent-with-azure-ai-agent-service-workshop/)
- [Contoso Creative Writer Multi-Agent Workshop](https://github.com/Azure-Samples/contoso-creative-writer/tree/main/docs/workshop)
- [Semantic Kernel Function Calling Tutorial](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions)
- [Semantic Kernel Code Interpreter](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py)
- [Autogen Tools](https://microsoft.github.io/autogen/dev/user-guide/core-user-guide/components/tools.html)
```
**면책 조항**:
이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 최선을 다하고 있으나, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원본 문서(원어로 작성된 문서)를 권위 있는 출처로 간주해야 합니다. 중요한 정보의 경우, 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/04-tool-use/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/04-tool-use/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 14213
} |
# Agentic RAG
이 강의는 Agentic Retrieval-Augmented Generation (Agentic RAG)에 대한 포괄적인 개요를 제공합니다. 이는 대규모 언어 모델(LLM)이 외부 소스로부터 정보를 가져오면서 다음 단계를 자율적으로 계획하는 AI의 새로운 패러다임입니다. 정적 검색 후 읽기 패턴과 달리, Agentic RAG는 도구나 함수 호출 및 구조화된 출력을 포함한 반복적인 LLM 호출을 특징으로 합니다. 시스템은 결과를 평가하고, 쿼리를 개선하며, 필요시 추가 도구를 호출하고, 만족스러운 솔루션이 나올 때까지 이 과정을 반복합니다.
## 소개
이 강의에서는 다음 내용을 다룹니다:
- **Agentic RAG 이해하기:** 대규모 언어 모델(LLM)이 외부 데이터 소스에서 정보를 가져오면서 다음 단계를 자율적으로 계획하는 AI의 새로운 패러다임에 대해 학습합니다.
- **반복적 Maker-Checker 스타일 익히기:** LLM 호출과 도구 또는 함수 호출 및 구조화된 출력이 반복되는 루프를 이해하며, 이는 정확성을 개선하고 잘못된 쿼리를 처리하도록 설계되었습니다.
- **실용적 응용 탐구:** 정확성 우선 환경, 복잡한 데이터베이스 상호작용, 확장된 워크플로우와 같은 상황에서 Agentic RAG가 빛을 발하는 사례를 확인합니다.
## 학습 목표
이 강의를 완료하면 다음을 알게 됩니다:
- **Agentic RAG 이해:** 대규모 언어 모델(LLM)이 외부 데이터 소스에서 정보를 가져오면서 다음 단계를 자율적으로 계획하는 AI의 새로운 패러다임에 대해 학습합니다.
- **반복적 Maker-Checker 스타일:** LLM 호출과 도구 또는 함수 호출 및 구조화된 출력이 반복되는 루프의 개념을 이해하며, 이는 정확성을 개선하고 잘못된 쿼리를 처리하도록 설계되었습니다.
- **추론 과정 소유하기:** 시스템이 사전 정의된 경로에 의존하지 않고 문제를 해결하는 방법을 결정하는 능력을 이해합니다.
- **워크플로우:** 에이전트 모델이 독립적으로 시장 동향 보고서를 검색하고, 경쟁사 데이터를 식별하며, 내부 판매 지표를 상관시키고, 결과를 종합하고, 전략을 평가하는 과정을 이해합니다.
- **반복적 루프, 도구 통합 및 메모리:** 시스템이 반복적 상호작용 패턴에 의존하며, 상태와 메모리를 유지하여 반복 루프를 피하고 정보에 입각한 결정을 내리는 방법을 학습합니다.
- **실패 모드 처리 및 자기 수정:** 진단 도구를 사용하거나 인간 감독에 의존하는 등 시스템의 강력한 자기 수정 메커니즘을 탐구합니다.
- **에이전시의 한계:** 도메인별 자율성, 인프라 의존성, 안전 장치 준수를 중심으로 Agentic RAG의 한계를 이해합니다.
- **실용적 사용 사례 및 가치:** 정확성 우선 환경, 복잡한 데이터베이스 상호작용, 확장된 워크플로우와 같은 상황에서 Agentic RAG가 빛을 발하는 사례를 확인합니다.
- **거버넌스, 투명성, 신뢰:** 설명 가능한 추론, 편향 제어, 인간 감독 등 거버넌스와 투명성의 중요성을 학습합니다.
## Agentic RAG란 무엇인가?
Agentic Retrieval-Augmented Generation (Agentic RAG)은 대규모 언어 모델(LLM)이 외부 소스로부터 정보를 가져오면서 다음 단계를 자율적으로 계획하는 AI의 새로운 패러다임입니다. 정적 검색 후 읽기 패턴과 달리, Agentic RAG는 도구나 함수 호출 및 구조화된 출력을 포함한 반복적인 LLM 호출을 특징으로 합니다. 시스템은 결과를 평가하고, 쿼리를 개선하며, 필요시 추가 도구를 호출하고, 만족스러운 솔루션이 나올 때까지 이 과정을 반복합니다. 이러한 반복적인 "maker-checker" 스타일은 정확성을 개선하고, 잘못된 쿼리를 처리하며, 높은 품질의 결과를 보장합니다.
시스템은 추론 과정을 적극적으로 소유하며, 실패한 쿼리를 다시 작성하거나, 다른 검색 방법을 선택하고, 여러 도구(예: Azure AI Search의 벡터 검색, SQL 데이터베이스, 사용자 지정 API)를 통합하여 최종 답변을 도출합니다. 에이전틱 시스템의 차별화된 품질은 추론 과정을 스스로 소유하는 능력입니다. 기존 RAG 구현은 사전 정의된 경로에 의존하지만, 에이전틱 시스템은 발견된 정보의 품질에 따라 단계의 순서를 자율적으로 결정합니다.
## Agentic Retrieval-Augmented Generation (Agentic RAG) 정의
Agentic Retrieval-Augmented Generation (Agentic RAG)은 LLM이 외부 데이터 소스에서 정보를 가져오는 것뿐만 아니라, 다음 단계를 자율적으로 계획하는 AI 개발의 새로운 패러다임입니다. 정적 검색 후 읽기 패턴이나 신중히 스크립트된 프롬프트 시퀀스와 달리, Agentic RAG는 도구나 함수 호출 및 구조화된 출력을 포함한 반복적인 LLM 호출 루프를 특징으로 합니다. 매 단계마다 시스템은 얻은 결과를 평가하고, 쿼리를 개선하거나, 필요시 추가 도구를 호출하며, 만족스러운 솔루션이 나올 때까지 이 과정을 반복합니다.
이 반복적인 "maker-checker" 운영 스타일은 정확성을 개선하고, 구조화된 데이터베이스(NL2SQL 등)에 대한 잘못된 쿼리를 처리하며, 균형 잡힌 고품질 결과를 보장하도록 설계되었습니다. 신중히 설계된 프롬프트 체인에만 의존하는 대신, 시스템은 추론 과정을 적극적으로 소유합니다. 실패한 쿼리를 다시 작성하거나, 다른 검색 방법을 선택하고, 여러 도구(예: Azure AI Search의 벡터 검색, SQL 데이터베이스, 사용자 지정 API)를 통합하여 최종 답변을 도출합니다. 이는 지나치게 복잡한 오케스트레이션 프레임워크의 필요성을 제거합니다. 대신, "LLM 호출 → 도구 사용 → LLM 호출 → ..."라는 비교적 간단한 루프를 통해 정교하고 근거 있는 출력을 도출할 수 있습니다.

## 추론 과정 소유하기
시스템을 "에이전틱"하게 만드는 가장 큰 특징은 추론 과정을 스스로 소유하는 능력입니다. 기존 RAG 구현은 모델이 어떤 정보를 검색하고 언제 검색해야 할지에 대한 체인을 인간이 사전에 정의하는 경우가 많습니다. 그러나 진정으로 에이전틱한 시스템은 문제를 해결하는 방법을 내부적으로 결정합니다. 단순히 스크립트를 실행하는 것이 아니라, 발견된 정보의 품질에 따라 단계의 순서를 자율적으로 결정합니다.
예를 들어, 제품 출시 전략을 수립하라는 요청을 받았을 때, 에이전틱 모델은 전체 연구 및 의사 결정 워크플로우를 명시하는 프롬프트에만 의존하지 않습니다. 대신, 모델은 독립적으로 다음 단계를 결정합니다:
1. Bing Web Grounding을 사용하여 현재 시장 동향 보고서를 검색합니다.
2. Azure AI Search를 사용하여 관련 경쟁사 데이터를 식별합니다.
3. Azure SQL Database를 사용하여 과거 내부 판매 지표를 상관 분석합니다.
4. Azure OpenAI Service를 통해 결과를 종합하여 일관된 전략을 작성합니다.
5. 전략의 격차나 불일치를 평가하며, 필요한 경우 추가 검색을 진행합니다.
이 모든 단계—쿼리 개선, 소스 선택, "만족"할 때까지 반복—는 사람이 미리 스크립트화한 것이 아니라 모델이 스스로 결정합니다.
## 반복적 루프, 도구 통합 및 메모리

에이전틱 시스템은 반복적 상호작용 패턴에 의존합니다:
- **초기 호출:** 사용자의 목표(사용자 프롬프트)가 LLM에 제시됩니다.
- **도구 호출:** 모델이 누락된 정보나 모호한 지침을 식별하면, 벡터 데이터베이스 쿼리(예: Azure AI Search Hybrid search over private data)나 구조화된 SQL 호출과 같은 도구나 검색 방법을 선택하여 더 많은 컨텍스트를 수집합니다.
- **평가 및 개선:** 반환된 데이터를 검토한 후, 모델은 정보가 충분한지 여부를 결정합니다. 그렇지 않다면, 쿼리를 개선하거나, 다른 도구를 시도하거나, 접근 방식을 조정합니다.
- **만족할 때까지 반복:** 이 주기는 모델이 충분한 명확성과 증거를 확보하여 최종적이고 논리적인 응답을 제공할 때까지 계속됩니다.
- **메모리 및 상태:** 시스템은 단계별로 상태와 메모리를 유지하기 때문에 이전 시도와 결과를 기억하고, 반복 루프를 피하며 더 나은 결정을 내릴 수 있습니다.
시간이 지남에 따라 이는 점진적인 이해를 형성하며, 모델이 복잡하고 다단계 작업을 인간의 지속적인 개입이나 프롬프트 재구성 없이도 처리할 수 있도록 합니다.
## 실패 모드 처리 및 자기 수정
Agentic RAG의 자율성은 강력한 자기 수정 메커니즘도 포함합니다. 시스템이 막다른 길에 도달했을 때—예를 들어, 관련 없는 문서를 검색하거나 잘못된 쿼리를 마주칠 경우—다음과 같은 조치를 취할 수 있습니다:
- **반복 및 재쿼리:** 가치가 낮은 응답을 반환하는 대신, 모델은 새로운 검색 전략을 시도하거나, 데이터베이스 쿼리를 다시 작성하거나, 대체 데이터 세트를 탐색합니다.
- **진단 도구 사용:** 시스템은 추론 단계를 디버그하거나 검색된 데이터의 정확성을 확인하기 위해 추가 기능을 호출할 수 있습니다. Azure AI Tracing과 같은 도구는 강력한 관찰 가능성과 모니터링을 가능하게 합니다.
- **인간 감독 의존:** 높은 위험이 있거나 반복적으로 실패하는 시나리오에서는 모델이 불확실성을 표시하고 인간의 지침을 요청할 수 있습니다. 인간이 교정 피드백을 제공하면, 모델은 이를 향후에 반영할 수 있습니다.
이 반복적이고 동적인 접근 방식은 모델이 지속적으로 개선되도록 하며, 단순히 한 번 실행되는 시스템이 아니라 세션 중에 실수를 학습하는 시스템이 되도록 보장합니다.

## 에이전시의 한계
Agentic RAG는 작업 내에서 자율성을 가지지만, 이를 인공지능 일반 지능(AGI)과 동일시할 수는 없습니다. "에이전틱" 기능은 인간 개발자가 제공한 도구, 데이터 소스, 정책 내에서만 작동합니다. 자체 도구를 발명하거나 설정된 도메인 경계를 벗어날 수 없습니다. 대신, 제공된 자원을 동적으로 조정하는 데 탁월합니다.
주요 차이점은 다음과 같습니다:
1. **도메인별 자율성:** Agentic RAG 시스템은 알려진 도메인 내에서 사용자 정의 목표를 달성하는 데 중점을 두며, 쿼리 재작성이나 도구 선택과 같은 전략을 사용하여 결과를 개선합니다.
2. **인프라 의존성:** 시스템의 기능은 개발자가 통합한 도구와 데이터에 따라 달라집니다. 인간의 개입 없이는 이러한 경계를 초월할 수 없습니다.
3. **안전 장치 준수:** 윤리적 지침, 규정 준수 규칙, 비즈니스 정책은 여전히 매우 중요합니다. 에이전트의 자유는 항상 안전 조치와 감독 메커니즘에 의해 제한됩니다(희망적으로?).
## 실용적 사용 사례 및 가치
Agentic RAG는 반복적인 정제와 정확성이 요구되는 시나리오에서 빛을 발합니다:
1. **정확성 우선 환경:** 규정 준수 검사, 규제 분석, 법률 연구와 같은 경우, 에이전틱 모델은 사실을 반복적으로 확인하고, 여러 소스를 참조하며, 쿼리를 다시 작성하여 철저히 검증된 답변을 제공합니다.
2. **복잡한 데이터베이스 상호작용:** 구조화된 데이터와 작업할 때 쿼리가 자주 실패하거나 조정이 필요한 경우, 시스템은 Azure SQL이나 Microsoft Fabric OneLake를 사용하여 쿼리를 자율적으로 정제하여 최종 검색 결과가 사용자의 의도와 일치하도록 보장합니다.
3. **확장된 워크플로우:** 새로운 정보가 표면화됨에 따라 세션이 진화할 수 있습니다. Agentic RAG는 문제 공간에 대해 더 많이 배우면서 지속적으로 새 데이터를 통합하고 전략을 변경할 수 있습니다.
## 거버넌스, 투명성, 신뢰
이러한 시스템이 추론에서 더 자율적으로 발전함에 따라, 거버넌스와 투명성이 중요합니다:
- **설명 가능한 추론:** 모델은 수행한 쿼리, 참조한 소스, 결론에 도달하기 위해 취한 추론 단계를 감사 추적 형태로 제공할 수 있습니다. Azure AI Content Safety와 Azure AI Tracing / GenAIOps와 같은 도구는 투명성을 유지하고 위험을 완화하는 데 도움이 됩니다.
- **편향 제어 및 균형 잡힌 검색:** 개발자는 검색 전략을 조정하여 균형 잡힌 대표 데이터를 고려하도록 하고, Azure Machine Learning을 사용하는 고급 데이터 과학 조직의 사용자 지정 모델을 통해 출력물을 정기적으로 감사하여 편향이나 왜곡된 패턴을 감지할 수 있습니다.
- **인간 감독 및 규정 준수:** 민감한 작업의 경우, 인간 검토는 여전히 필수적입니다. Agentic RAG는 고위험 결정에서 인간의 판단을 대체하는 것이 아니라, 더 철저히 검토된 옵션을 제공하여 이를 보완합니다.
다단계 프로세스를 디버깅하기 위해 명확한 작업 기록을 제공하는 도구가 필수적입니다. 그렇지 않으면 디버깅이 매우 어려울 수 있습니다. 아래는 Literal AI(Chainlit 개발 회사)의 에이전트 실행 예제입니다:


## 결론
Agentic RAG는 AI 시스템이 복잡하고 데이터 집약적인 작업을 처리하는 방식에서 자연스러운 진화를 나타냅니다. 반복적인 상호작용 패턴을 채택하고, 도구를 자율적으로 선택하며, 고품질 결과를 달성할 때까지 쿼리를 정제함으로써, 이 시스템은 정적 프롬프트 추종을 넘어 보다 적응적이고 맥락을 인식하는 의사 결정자로 발전합니다. 여전히 인간이 정의한 인프라와 윤리적 지침에 의해 제한되지만, 이러한 에이전틱 기능은 기업과 최종 사용자 모두에게 더 풍부하고 동적이며 궁극적으로 더 유용한 AI 상호작용을 가능하게 합니다.
## 추가 리소스
- Implement Retrieval Augmented Generation (RAG) with Azure OpenAI Service: Learn how to use your own data with the Azure OpenAI Service.[This Microsoft Learn module provides a comprehensive guide on implementing RAG](https://learn.microsoft.com/training/modules/use-own-data-azure-openai)
- Evaluation of generative AI applications with Azure AI Foundry: This article covers the evaluation and comparison of models on publicly available datasets, including [Agentic AI applications and RAG architectures](https://learn.microsoft.com/azure/ai-studio/concepts/evaluation-approach-gen-ai)
- [What is Agentic RAG | Weaviate](https://weaviate.io/blog/what-is-agentic-rag)
- [Agentic RAG: A Complete Guide to Agent-Based Retrieval Augmented Generation – News from generation RAG](https://ragaboutit.com/agentic-rag-a-complete-guide-to-agent-based-retrieval-augmented-generation/)
- [Agentic RAG: turbocharge your RAG with query reformulation and self-query! Hugging Face Open-Source AI Cookbook](https://huggingface.co/learn/cookbook/agent_rag)
- [Adding Agentic Layers to RAG](https://youtu.be/aQ4yQXeB1Ss?si=2HUqBzHoeB5tR04U)
- [The Future of Knowledge Assistants: Jerry Liu](https://www.youtube.com/watch?v=zeAyuLc_f3Q&t=244s)
- [How to Build Agentic RAG Systems](https://www.youtube.com/watch?v=AOSjiXP1jmQ)
- [Using Azure AI Foundry Agent Service to scale your AI agents](https://ignite.microsoft.com/sessions/BRK102?source=sessions)
### 학술 논문
- [2303.17651 Self-Refine: Iterative Refinement with Self-Feedback](https://arxiv.org/abs/2303.17651)
- [2303.11366 Reflexion: Language Agents with Verbal Reinforcement Learning](https://arxiv.org/abs/2303.11366)
- [2305.11738 CRITIC: Large Language Models Can Self-Correct with Tool-Interactive Critiquing](https://arxiv.org/abs/2305.11738)
```
**면책 조항**:
이 문서는 AI 기반 기계 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 노력하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원본 문서(모국어로 작성된 문서)가 권위 있는 자료로 간주되어야 합니다. 중요한 정보의 경우, 전문적인 인간 번역을 권장합니다. 이 번역을 사용함으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/05-agentic-rag/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/05-agentic-rag/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 9600
} |
# 신뢰할 수 있는 AI 에이전트 구축
## 소개
이 강의에서는 다음 내용을 다룹니다:
- 안전하고 효과적인 AI 에이전트를 구축하고 배포하는 방법
- AI 에이전트를 개발할 때 고려해야 할 중요한 보안 사항
- AI 에이전트를 개발할 때 데이터와 사용자 프라이버시를 유지하는 방법
## 학습 목표
이 강의를 완료한 후, 여러분은 다음을 할 수 있습니다:
- AI 에이전트를 생성할 때 발생할 수 있는 위험을 식별하고 완화하는 방법을 이해합니다.
- 데이터와 접근 권한을 적절히 관리하기 위한 보안 조치를 구현합니다.
- 데이터 프라이버시를 유지하고 품질 높은 사용자 경험을 제공하는 AI 에이전트를 만듭니다.
## 안전성
우선 안전한 에이전트 기반 애플리케이션을 구축하는 방법을 살펴보겠습니다. 안전성이란 AI 에이전트가 설계된 대로 작동하는 것을 의미합니다. 에이전트 기반 애플리케이션을 구축하는 개발자로서, 우리는 안전성을 극대화하기 위한 방법과 도구를 가지고 있습니다.
### 메타 프롬프팅 시스템 구축
대규모 언어 모델(LLMs)을 사용해 AI 애플리케이션을 만들어본 경험이 있다면, 견고한 시스템 프롬프트나 시스템 메시지를 설계하는 것이 얼마나 중요한지 알 것입니다. 이러한 프롬프트는 LLM이 사용자 및 데이터와 상호작용하는 방식에 대한 메타 규칙, 지침, 가이드를 설정합니다.
AI 에이전트의 경우, 시스템 프롬프트는 더욱 중요합니다. AI 에이전트가 설계된 작업을 수행하려면 매우 구체적인 지침이 필요하기 때문입니다.
확장 가능한 시스템 프롬프트를 생성하려면, 애플리케이션에서 하나 이상의 에이전트를 구축하기 위한 메타 프롬프팅 시스템을 사용할 수 있습니다:

#### 1단계: 메타 또는 템플릿 프롬프트 생성
메타 프롬프트는 우리가 생성하는 에이전트의 시스템 프롬프트를 생성하기 위해 LLM이 사용할 템플릿입니다. 필요에 따라 여러 에이전트를 효율적으로 생성할 수 있도록 템플릿 형태로 설계합니다.
다음은 LLM에 제공할 메타 프롬프트의 예입니다:
```plaintext
You are an expert at creating AI agent assitants.
You will be provided a company name, role, responsibilites and other
information that you will use to provide a system prompt for.
To create the system prompt, be descriptive as possible and provide a structure that a system using an LLM can better understand the role and responsibilites of the AI assistant.
```
#### 2단계: 기본 프롬프트 생성
다음 단계는 AI 에이전트를 설명하는 기본 프롬프트를 작성하는 것입니다. 여기에는 에이전트의 역할, 에이전트가 수행할 작업, 기타 책임이 포함되어야 합니다.
다음은 그 예입니다:
```plaintext
You are a travel agent for Contoso Travel with that is great at booking flights for customers. To help customers you can perform the following tasks: lookup available flights, book flights, ask for preferences in seating and times for flights, cancel any previously booked flights and alert customers on any delays or cancellations of flights.
```
#### 3단계: LLM에 기본 프롬프트 제공
이제 메타 프롬프트를 시스템 프롬프트로 제공하고 기본 프롬프트를 추가하여 최적화된 프롬프트를 생성할 수 있습니다.
이렇게 하면 AI 에이전트를 보다 효과적으로 안내할 수 있는 프롬프트가 생성됩니다:
```markdown
**Company Name:** Contoso Travel
**Role:** Travel Agent Assistant
**Objective:**
You are an AI-powered travel agent assistant for Contoso Travel, specializing in booking flights and providing exceptional customer service. Your main goal is to assist customers in finding, booking, and managing their flights, all while ensuring that their preferences and needs are met efficiently.
**Key Responsibilities:**
1. **Flight Lookup:**
- Assist customers in searching for available flights based on their specified destination, dates, and any other relevant preferences.
- Provide a list of options, including flight times, airlines, layovers, and pricing.
2. **Flight Booking:**
- Facilitate the booking of flights for customers, ensuring that all details are correctly entered into the system.
- Confirm bookings and provide customers with their itinerary, including confirmation numbers and any other pertinent information.
3. **Customer Preference Inquiry:**
- Actively ask customers for their preferences regarding seating (e.g., aisle, window, extra legroom) and preferred times for flights (e.g., morning, afternoon, evening).
- Record these preferences for future reference and tailor suggestions accordingly.
4. **Flight Cancellation:**
- Assist customers in canceling previously booked flights if needed, following company policies and procedures.
- Notify customers of any necessary refunds or additional steps that may be required for cancellations.
5. **Flight Monitoring:**
- Monitor the status of booked flights and alert customers in real-time about any delays, cancellations, or changes to their flight schedule.
- Provide updates through preferred communication channels (e.g., email, SMS) as needed.
**Tone and Style:**
- Maintain a friendly, professional, and approachable demeanor in all interactions with customers.
- Ensure that all communication is clear, informative, and tailored to the customer's specific needs and inquiries.
**User Interaction Instructions:**
- Respond to customer queries promptly and accurately.
- Use a conversational style while ensuring professionalism.
- Prioritize customer satisfaction by being attentive, empathetic, and proactive in all assistance provided.
**Additional Notes:**
- Stay updated on any changes to airline policies, travel restrictions, and other relevant information that could impact flight bookings and customer experience.
- Use clear and concise language to explain options and processes, avoiding jargon where possible for better customer understanding.
This AI assistant is designed to streamline the flight booking process for customers of Contoso Travel, ensuring that all their travel needs are met efficiently and effectively.
```
#### 4단계: 반복 및 개선
메타 프롬프팅 시스템의 가치는 여러 에이전트를 쉽게 생성할 수 있을 뿐만 아니라, 프롬프트를 지속적으로 개선할 수 있다는 점입니다. 처음부터 완벽하게 작동하는 프롬프트를 얻는 것은 드문 일이므로, 기본 프롬프트를 약간씩 수정하고 시스템을 통해 실행해 결과를 비교하고 평가하는 것이 중요합니다.
## 위협 이해하기
신뢰할 수 있는 AI 에이전트를 구축하려면, AI 에이전트에 대한 위험과 위협을 이해하고 이를 완화하는 것이 중요합니다. 이제 AI 에이전트에 대한 다양한 위협과 이를 대비하고 계획하는 방법에 대해 살펴보겠습니다.

### 작업 및 지침
**설명:** 공격자는 프롬프트나 입력값을 조작하여 AI 에이전트의 지침이나 목표를 변경하려고 시도합니다.
**완화 방안:** AI 에이전트가 입력을 처리하기 전에 잠재적으로 위험한 프롬프트를 탐지할 수 있도록 검증 및 입력 필터링을 실행하세요. 이러한 공격은 일반적으로 에이전트와의 빈번한 상호작용을 필요로 하므로, 대화 횟수를 제한하는 것도 이러한 공격을 방지하는 방법입니다.
### 중요한 시스템에 대한 접근
**설명:** AI 에이전트가 민감한 데이터를 저장하는 시스템 및 서비스에 접근할 수 있는 경우, 공격자는 에이전트와 이러한 서비스 간의 통신을 손상시킬 수 있습니다. 이는 직접적인 공격이거나 에이전트를 통해 시스템 정보를 얻으려는 간접적인 시도일 수 있습니다.
**완화 방안:** AI 에이전트는 필요할 때만 시스템에 접근할 수 있도록 제한해야 합니다. 에이전트와 시스템 간의 통신은 반드시 안전해야 하며, 인증 및 접근 제어를 구현하여 정보를 보호하세요.
### 리소스 및 서비스 과부하
**설명:** AI 에이전트는 작업을 완료하기 위해 다양한 도구와 서비스를 사용할 수 있습니다. 공격자는 AI 에이전트를 통해 대량의 요청을 전송하여 해당 서비스에 시스템 장애나 높은 비용을 초래할 수 있습니다.
**완화 방안:** AI 에이전트가 서비스에 보낼 수 있는 요청 수를 제한하는 정책을 구현하세요. 대화 횟수와 요청 수를 제한하는 것도 이러한 공격을 방지하는 방법입니다.
### 지식 베이스 오염
**설명:** 이 유형의 공격은 AI 에이전트를 직접적으로 공격하는 것이 아니라, 에이전트가 사용하는 지식 베이스나 기타 서비스를 대상으로 합니다. 이는 데이터를 손상시키거나 AI 에이전트가 작업을 수행하는 데 사용하는 정보를 왜곡하여 편향되거나 의도하지 않은 응답을 유도할 수 있습니다.
**완화 방안:** AI 에이전트가 워크플로우에서 사용하는 데이터를 정기적으로 검증하세요. 이 데이터에 대한 접근은 반드시 신뢰할 수 있는 사람만 변경할 수 있도록 보안 조치를 취하세요.
### 연쇄 오류
**설명:** AI 에이전트는 작업을 완료하기 위해 다양한 도구와 서비스에 접근합니다. 공격으로 인해 발생한 오류가 AI 에이전트가 연결된 다른 시스템의 장애로 이어질 수 있으며, 이는 공격이 더 광범위하게 확산되고 문제 해결이 어려워질 수 있습니다.
**완화 방안:** AI 에이전트가 Docker 컨테이너와 같은 제한된 환경에서 작업하도록 하여 직접적인 시스템 공격을 방지하세요. 특정 시스템이 오류를 반환할 경우 대체 메커니즘과 재시도 로직을 구현하여 더 큰 시스템 장애를 방지하세요.
## 인간 개입 루프
신뢰할 수 있는 AI 에이전트 시스템을 구축하는 또 다른 효과적인 방법은 인간 개입 루프를 사용하는 것입니다. 이는 사용자가 실행 중인 에이전트에 피드백을 제공할 수 있는 흐름을 만듭니다. 사용자는 다중 에이전트 시스템의 하나의 에이전트처럼 작동하며, 실행 중인 프로세스를 승인하거나 종료하는 역할을 합니다.

다음은 AutoGen을 사용하여 이 개념을 구현하는 코드 스니펫입니다:
```python
# Create the agents.
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
assistant = AssistantAgent("assistant", model_client=model_client)
user_proxy = UserProxyAgent("user_proxy", input_func=input) # Use input() to get user input from console.
# Create the termination condition which will end the conversation when the user says "APPROVE".
termination = TextMentionTermination("APPROVE")
# Create the team.
team = RoundRobinGroupChat([assistant, user_proxy], termination_condition=termination)
# Run the conversation and stream to the console.
stream = team.run_stream(task="Write a 4-line poem about the ocean.")
# Use asyncio.run(...) when running in a script.
await Console(stream)
```
```
**면책 조항**:
이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 최선을 다하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있음을 유의하시기 바랍니다. 원본 문서의 원어 버전이 신뢰할 수 있는 권위 있는 자료로 간주되어야 합니다. 중요한 정보에 대해서는 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/06-building-trustworthy-agents/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/06-building-trustworthy-agents/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 8231
} |
# 설계 계획
## 소개
이 강의에서는 다음 내용을 다룹니다:
* 명확한 전체 목표를 정의하고 복잡한 작업을 관리 가능한 작업으로 나누는 방법.
* 구조화된 출력을 활용하여 더 신뢰할 수 있고 기계가 읽을 수 있는 응답을 생성하는 방법.
* 이벤트 기반 접근 방식을 적용하여 동적 작업과 예기치 않은 입력을 처리하는 방법.
## 학습 목표
이 강의를 완료한 후에는 다음 내용을 이해할 수 있습니다:
* AI 에이전트의 전체 목표를 설정하고, 이를 통해 무엇을 달성해야 하는지 명확히 알 수 있도록 합니다.
* 복잡한 작업을 관리 가능한 하위 작업으로 나누고 이를 논리적인 순서로 조직합니다.
* 에이전트에게 적합한 도구(예: 검색 도구 또는 데이터 분석 도구)를 제공하고, 언제 어떻게 사용할지 결정하며 발생하는 예기치 않은 상황을 처리합니다.
* 하위 작업의 결과를 평가하고 성능을 측정하며, 최종 출력을 개선하기 위해 행동을 반복적으로 수정합니다.
## 전체 목표 정의 및 작업 세분화

대부분의 실제 작업은 한 번에 해결하기에는 너무 복잡합니다. AI 에이전트는 계획 및 행동을 안내할 간결한 목표가 필요합니다. 예를 들어, 다음과 같은 목표를 고려해 봅시다:
"3일간의 여행 일정 생성하기."
이 목표는 간단히 표현되었지만, 여전히 구체화가 필요합니다. 목표가 명확할수록 에이전트(및 협력하는 사람들)가 올바른 결과를 달성하는 데 더 집중할 수 있습니다. 예를 들어, 항공편 옵션, 호텔 추천, 활동 제안을 포함하는 포괄적인 일정을 만드는 것이 그 예입니다.
### 작업 세분화
큰 작업이나 복잡한 작업은 더 작은 목표 지향적인 하위 작업으로 나누면 더 쉽게 관리할 수 있습니다.
여행 일정 예제를 기준으로 하면, 목표를 다음과 같이 세분화할 수 있습니다:
* 항공편 예약
* 호텔 예약
* 렌터카 예약
* 개인화
각 하위 작업은 전담 에이전트나 프로세스에 의해 처리될 수 있습니다. 한 에이전트는 최적의 항공편을 검색하는 데 전문화되고, 다른 에이전트는 호텔 예약을 담당하는 식입니다. 이후 조정 또는 "다운스트림" 에이전트가 이러한 결과를 하나의 완성된 일정으로 통합하여 최종 사용자에게 제공합니다.
이 모듈식 접근 방식은 점진적인 개선도 가능하게 합니다. 예를 들어, 음식 추천이나 현지 활동 제안을 전문으로 하는 에이전트를 추가하여 일정의 품질을 점진적으로 개선할 수 있습니다.
### 구조화된 출력
대형 언어 모델(LLM)은 다운스트림 에이전트나 서비스가 더 쉽게 구문 분석하고 처리할 수 있는 구조화된 출력(예: JSON)을 생성할 수 있습니다. 이는 계획 출력이 수신된 후 작업을 실행하는 다중 에이전트 컨텍스트에서 특히 유용합니다. 자세한 내용은 [이 블로그 글](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/cookbook/structured-output-agent.html)을 참고하세요.
아래는 목표를 하위 작업으로 분해하고 구조화된 계획을 생성하는 간단한 계획 에이전트를 보여주는 Python 코드 예제입니다:
### 다중 에이전트 오케스트레이션을 활용한 계획 에이전트
이 예제에서, 시맨틱 라우터 에이전트는 사용자 요청(예: "여행을 위한 호텔 계획이 필요합니다.")을 받습니다.
플래너는 다음을 수행합니다:
* 호텔 계획 수신: 플래너는 사용자의 메시지를 받고, 시스템 프롬프트(사용 가능한 에이전트 세부 정보 포함)를 기반으로 구조화된 여행 계획을 생성합니다.
* 에이전트와 그 도구 나열: 에이전트 레지스트리는 항공편, 호텔, 렌터카, 활동 등을 위한 에이전트 목록과 그들이 제공하는 기능 또는 도구를 포함합니다.
* 계획을 해당 에이전트에 라우팅: 하위 작업의 수에 따라, 플래너는 메시지를 전용 에이전트(단일 작업 시나리오의 경우)에게 직접 보내거나, 다중 에이전트 협업을 위한 그룹 채팅 관리자를 통해 조정합니다.
* 결과 요약: 마지막으로, 플래너는 생성된 계획을 명확히 요약합니다.
아래는 이러한 단계를 보여주는 Python 코드 샘플입니다:
```python
from pydantic import BaseModel
from enum import Enum
from typing import List, Optional, Union
class AgentEnum(str, Enum):
FlightBooking = "flight_booking"
HotelBooking = "hotel_booking"
CarRental = "car_rental"
ActivitiesBooking = "activities_booking"
DestinationInfo = "destination_info"
DefaultAgent = "default_agent"
GroupChatManager = "group_chat_manager"
# Travel SubTask Model
class TravelSubTask(BaseModel):
task_details: str
assigned_agent: AgentEnum # we want to assign the task to the agent
class TravelPlan(BaseModel):
main_task: str
subtasks: List[TravelSubTask]
is_greeting: bool
import json
import os
from typing import Optional
from autogen_core.models import UserMessage, SystemMessage, AssistantMessage
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient
# Create the client with type-checked environment variables
client = AzureOpenAIChatCompletionClient(
azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
)
from pprint import pprint
# Define the user message
messages = [
SystemMessage(content="""You are an planner agent.
Your job is to decide which agents to run based on the user's request.
Below are the available agents specialised in different tasks:
- FlightBooking: For booking flights and providing flight information
- HotelBooking: For booking hotels and providing hotel information
- CarRental: For booking cars and providing car rental information
- ActivitiesBooking: For booking activities and providing activity information
- DestinationInfo: For providing information about destinations
- DefaultAgent: For handling general requests""", source="system"),
UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melbourne", source="user"),
]
response = await client.create(messages=messages, extra_create_args={"response_format": TravelPlan})
# Ensure the response content is a valid JSON string before loading it
response_content: Optional[str] = response.content if isinstance(response.content, str) else None
if response_content is None:
raise ValueError("Response content is not a valid JSON string")
# Print the response content after loading it as JSON
pprint(json.loads(response_content))
```
위 코드에서 생성된 출력은 `assigned_agent`로 라우팅하고 최종 사용자에게 여행 계획을 요약하는 데 사용할 수 있습니다.
```json
{
"is_greeting": "False",
"main_task": "Plan a family trip from Singapore to Melbourne.",
"subtasks": [
{
"assigned_agent": "flight_booking",
"task_details": "Book round-trip flights from Singapore to Melbourne."
},
{
"assigned_agent": "hotel_booking",
"task_details": "Find family-friendly hotels in Melbourne."
},
{
"assigned_agent": "car_rental",
"task_details": "Arrange a car rental suitable for a family of four in Melbourne."
},
{
"assigned_agent": "activities_booking",
"task_details": "List family-friendly activities in Melbourne."
},
{
"assigned_agent": "destination_info",
"task_details": "Provide information about Melbourne as a travel destination."
}
]
}
```
위 코드 샘플이 포함된 예제 노트북은 [여기](../../../07-planning-design/code_samples/07-autogen.ipynb)에서 확인할 수 있습니다.
### 반복적 계획
일부 작업은 상호작용이나 재계획이 필요하며, 한 하위 작업의 결과가 다음 작업에 영향을 미칠 수 있습니다. 예를 들어, 에이전트가 항공편 예약 중 예기치 않은 데이터 형식을 발견하면, 호텔 예약으로 넘어가기 전에 전략을 조정해야 할 수 있습니다.
또한, 사용자 피드백(예: 사용자가 더 이른 항공편을 선호한다고 결정하는 경우)은 부분적인 재계획을 유발할 수 있습니다. 이러한 동적이고 반복적인 접근 방식은 최종 솔루션이 현실적인 제약 조건과 변화하는 사용자 선호도에 맞도록 보장합니다.
예제 코드:
```python
from autogen_core.models import UserMessage, SystemMessage, AssistantMessage
#.. same as previous code and pass on the user history, current plan
messages = [
SystemMessage(content="""You are a planner agent to optimize the
Your job is to decide which agents to run based on the user's request.
Below are the available agents specialised in different tasks:
- FlightBooking: For booking flights and providing flight information
- HotelBooking: For booking hotels and providing hotel information
- CarRental: For booking cars and providing car rental information
- ActivitiesBooking: For booking activities and providing activity information
- DestinationInfo: For providing information about destinations
- DefaultAgent: For handling general requests""", source="system"),
UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melboune", source="user"),
AssistantMessage(content=f"Previous travel plan - {TravelPlan}", source="assistant")
]
# .. re-plan and send the tasks to respective agents
```
더 포괄적인 계획에 대해 알아보려면 복잡한 작업 해결을 위한 Magnetic One [블로그 글](https://www.microsoft.com/research/articles/magentic-one-a-generalist-multi-agent-system-for-solving-complex-tasks)을 확인하세요.
## 요약
이 글에서는 가용한 에이전트를 동적으로 선택할 수 있는 플래너를 생성하는 방법의 예를 살펴보았습니다. 플래너의 출력은 작업을 세분화하고 에이전트에게 할당하여 실행되도록 합니다. 에이전트가 작업을 수행하는 데 필요한 기능/도구에 액세스할 수 있다고 가정합니다. 에이전트 외에도 반영, 요약, 라운드 로빈 채팅과 같은 패턴을 추가하여 더욱 맞춤화할 수 있습니다.
## 추가 자료
* O1 추론 모델은 복잡한 작업 계획에서 매우 뛰어난 성능을 입증했습니다 - TODO: 예제 공유?
* Autogen Magnetic One - 복잡한 작업을 해결하기 위한 범용 다중 에이전트 시스템으로, 다양한 도전적인 에이전트 벤치마크에서 인상적인 결과를 달성했습니다. 참고: [autogen-magentic-one](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-magentic-one). 이 구현에서는 오케스트레이터가 작업별 계획을 생성하고 이러한 작업을 사용 가능한 에이전트에 위임합니다. 계획 외에도 오케스트레이터는 작업 진행 상황을 모니터링하고 필요에 따라 재계획하는 추적 메커니즘도 활용합니다.
```
**면책 조항**:
이 문서는 AI 기반 기계 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 노력하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원본 문서를 해당 언어로 작성된 상태에서 권위 있는 자료로 간주해야 합니다. 중요한 정보의 경우, 전문 번역가에 의한 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해서는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/07-planning-design/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/07-planning-design/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 8432
} |
# 다중 에이전트 설계 패턴
여러 에이전트가 포함된 프로젝트를 시작하면, 다중 에이전트 설계 패턴을 고려해야 합니다. 그러나 언제 다중 에이전트로 전환해야 하는지와 그 장점이 무엇인지 바로 명확하지 않을 수 있습니다.
## 소개
이번 강의에서는 다음 질문에 답하려고 합니다:
- 다중 에이전트가 적용될 수 있는 시나리오는 무엇인가요?
- 하나의 에이전트가 여러 작업을 수행하는 대신 다중 에이전트를 사용하는 것의 장점은 무엇인가요?
- 다중 에이전트 설계 패턴을 구현하기 위한 구성 요소는 무엇인가요?
- 여러 에이전트가 서로 어떻게 상호작용하는지에 대한 가시성을 어떻게 확보할 수 있을까요?
## 학습 목표
이 강의를 마친 후, 여러분은 다음을 할 수 있어야 합니다:
- 다중 에이전트가 적용 가능한 시나리오를 식별할 수 있다.
- 단일 에이전트보다 다중 에이전트를 사용하는 장점을 이해할 수 있다.
- 다중 에이전트 설계 패턴을 구현하기 위한 구성 요소를 이해할 수 있다.
큰 그림은 무엇일까요?
*다중 에이전트는 여러 에이전트가 협력하여 공통 목표를 달성하도록 하는 설계 패턴입니다.*
이 패턴은 로봇공학, 자율 시스템, 분산 컴퓨팅 등 다양한 분야에서 널리 사용됩니다.
## 다중 에이전트가 적용 가능한 시나리오
그렇다면 어떤 시나리오가 다중 에이전트를 사용하는 좋은 사례일까요? 답은 많습니다. 특히 다음과 같은 경우에 다중 에이전트를 사용하는 것이 유용합니다:
- **대규모 작업량**: 대규모 작업량은 더 작은 작업으로 나누어져 서로 다른 에이전트에 할당될 수 있습니다. 이를 통해 병렬 처리가 가능하며 작업을 더 빠르게 완료할 수 있습니다. 예를 들어, 대규모 데이터 처리 작업이 이에 해당합니다.
- **복잡한 작업**: 복잡한 작업도 대규모 작업처럼 더 작은 하위 작업으로 나누어지고, 각 하위 작업은 특정 측면을 전문으로 하는 서로 다른 에이전트에 할당될 수 있습니다. 예를 들어, 자율 주행 차량의 경우 각 에이전트가 내비게이션, 장애물 감지, 다른 차량과의 통신을 관리합니다.
- **다양한 전문성**: 서로 다른 에이전트가 다양한 전문성을 가지고 있어 단일 에이전트보다 작업의 다양한 측면을 더 효과적으로 처리할 수 있습니다. 예를 들어, 의료 분야에서는 진단, 치료 계획, 환자 모니터링을 각각 관리하는 에이전트를 사용할 수 있습니다.
## 단일 에이전트보다 다중 에이전트를 사용하는 장점
단일 에이전트 시스템은 간단한 작업에는 적합할 수 있지만, 더 복잡한 작업에서는 다중 에이전트를 사용하는 것이 여러 가지 장점을 제공합니다:
- **전문화**: 각 에이전트는 특정 작업에 특화될 수 있습니다. 단일 에이전트가 전문화되지 않으면 모든 작업을 처리할 수는 있지만, 복잡한 작업에서는 혼란을 겪을 수 있습니다. 예를 들어, 적합하지 않은 작업을 수행할 수도 있습니다.
- **확장성**: 단일 에이전트를 과부하시키는 대신 에이전트를 추가하여 시스템을 확장하는 것이 더 쉽습니다.
- **내결함성**: 하나의 에이전트가 실패하더라도 다른 에이전트가 계속 작동하여 시스템 신뢰성을 보장할 수 있습니다.
예를 들어, 사용자의 여행 예약을 생각해 봅시다. 단일 에이전트 시스템은 항공편 검색부터 호텔 예약, 렌터카 예약까지 모든 작업을 처리해야 합니다. 이를 단일 에이전트로 구현하려면 모든 작업을 처리할 수 있는 도구가 필요하며, 이는 유지 관리와 확장이 어려운 복잡하고 단일화된 시스템으로 이어질 수 있습니다. 반면, 다중 에이전트 시스템에서는 항공편 검색, 호텔 예약, 렌터카 예약을 각각 전문으로 하는 에이전트를 사용할 수 있습니다. 이렇게 하면 시스템이 더 모듈화되고 유지 관리가 용이하며 확장 가능해집니다.
이를 소규모 가족 운영 여행사와 프랜차이즈 여행사를 비교해 볼 수 있습니다. 소규모 가족 운영 여행사는 모든 작업을 단일 에이전트가 처리하지만, 프랜차이즈 여행사는 각 작업을 전문으로 하는 여러 에이전트가 처리합니다.
## 다중 에이전트 설계 패턴 구현의 구성 요소
다중 에이전트 설계 패턴을 구현하기 전에 패턴을 구성하는 요소를 이해해야 합니다.
사용자의 여행 예약 예제를 다시 살펴보겠습니다. 이 경우, 구성 요소는 다음을 포함합니다:
- **에이전트 간 통신**: 항공편 검색, 호텔 예약, 렌터카 예약 에이전트는 사용자의 선호도와 제약 조건에 대한 정보를 공유하고 소통해야 합니다. 이를 위해 통신 프로토콜과 방법을 결정해야 합니다. 예를 들어, 항공편 검색 에이전트는 호텔 예약 에이전트와 소통하여 호텔이 항공편 날짜와 일치하도록 예약되었는지 확인해야 합니다. 즉, *어떤 에이전트가 정보를 공유하며, 어떻게 공유할지*를 결정해야 합니다.
- **조정 메커니즘**: 에이전트는 사용자의 선호도와 제약 조건을 충족하기 위해 작업을 조정해야 합니다. 사용자가 공항 근처 호텔을 선호하는 경우, 렌터카는 공항에서만 가능하다는 제약 조건이 있을 수 있습니다. 따라서 호텔 예약 에이전트는 렌터카 예약 에이전트와 협력하여 사용자의 선호도와 제약 조건을 충족해야 합니다. 즉, *에이전트가 작업을 어떻게 조정할지*를 결정해야 합니다.
- **에이전트 아키텍처**: 에이전트는 사용자의 상호작용에서 학습하고 결정을 내릴 내부 구조를 가져야 합니다. 예를 들어, 항공편 검색 에이전트는 사용자가 선호하는 항공편을 추천하기 위해 결정을 내릴 내부 구조를 가져야 합니다. 즉, *에이전트가 사용자와의 상호작용에서 어떻게 학습하고 결정을 내릴지*를 결정해야 합니다. 예를 들어, 항공편 검색 에이전트는 사용자의 과거 선호도를 기반으로 항공편을 추천하는 기계 학습 모델을 사용할 수 있습니다.
- **다중 에이전트 상호작용에 대한 가시성**: 여러 에이전트가 서로 어떻게 상호작용하는지에 대한 가시성을 확보해야 합니다. 이를 위해 에이전트 활동과 상호작용을 추적하기 위한 도구와 기술이 필요합니다. 이는 로깅 및 모니터링 도구, 시각화 도구, 성능 지표의 형태로 제공될 수 있습니다.
- **다중 에이전트 패턴**: 중앙 집중식, 분산식, 하이브리드 아키텍처와 같은 다양한 다중 에이전트 시스템 구현 패턴이 있습니다. 사용 사례에 가장 적합한 패턴을 선택해야 합니다.
- **사용자 개입**: 대부분의 경우, 사용자가 개입할 시점을 에이전트에게 지시해야 합니다. 예를 들어, 사용자가 에이전트가 추천하지 않은 특정 호텔이나 항공편을 요청하거나 예약 전에 확인을 요청하는 경우가 이에 해당합니다.
## 다중 에이전트 상호작용에 대한 가시성
여러 에이전트가 서로 어떻게 상호작용하는지에 대한 가시성을 확보하는 것은 중요합니다. 이는 디버깅, 최적화, 전체 시스템의 효과성을 보장하는 데 필수적입니다. 이를 위해 에이전트 활동과 상호작용을 추적하기 위한 도구와 기술이 필요합니다. 이는 로깅 및 모니터링 도구, 시각화 도구, 성능 지표의 형태로 제공될 수 있습니다.
예를 들어, 사용자의 여행 예약의 경우, 각 에이전트의 상태, 사용자의 선호도와 제약 조건, 에이전트 간 상호작용을 보여주는 대시보드를 가질 수 있습니다. 이 대시보드는 사용자의 여행 날짜, 항공편 에이전트가 추천한 항공편, 호텔 에이전트가 추천한 호텔, 렌터카 에이전트가 추천한 렌터카를 보여줄 수 있습니다. 이를 통해 에이전트가 서로 어떻게 상호작용하고 있는지, 사용자의 선호도와 제약 조건이 충족되고 있는지를 명확히 파악할 수 있습니다.
각각의 측면을 더 자세히 살펴봅시다:
- **로깅 및 모니터링 도구**: 각 에이전트가 수행한 작업에 대해 로깅을 수행해야 합니다. 로그 항목에는 작업을 수행한 에이전트, 수행된 작업, 작업 수행 시간, 작업 결과에 대한 정보가 포함될 수 있습니다. 이 정보는 디버깅, 최적화 등에 사용될 수 있습니다.
- **시각화 도구**: 시각화 도구는 에이전트 간 상호작용을 더 직관적으로 볼 수 있도록 도와줍니다. 예를 들어, 에이전트 간 정보 흐름을 보여주는 그래프를 가질 수 있습니다. 이를 통해 병목 현상, 비효율성, 시스템 문제를 식별할 수 있습니다.
- **성능 지표**: 성능 지표는 다중 에이전트 시스템의 효과성을 추적하는 데 도움을 줍니다. 예를 들어, 작업 완료에 걸린 시간, 단위 시간당 완료된 작업 수, 에이전트가 제공한 추천의 정확도를 추적할 수 있습니다. 이를 통해 개선이 필요한 영역을 식별하고 시스템을 최적화할 수 있습니다.
## 다중 에이전트 패턴
다중 에이전트 앱을 만들기 위해 사용할 수 있는 몇 가지 구체적인 패턴을 살펴봅시다. 다음은 고려할 만한 흥미로운 패턴들입니다:
### 그룹 채팅
이 패턴은 여러 에이전트가 서로 소통할 수 있는 그룹 채팅 애플리케이션을 만들고자 할 때 유용합니다. 이 패턴의 일반적인 사용 사례로는 팀 협업, 고객 지원, 소셜 네트워킹 등이 있습니다.
이 패턴에서 각 에이전트는 그룹 채팅의 사용자로 나타나며, 메시지는 메시징 프로토콜을 사용하여 에이전트 간에 교환됩니다. 에이전트는 그룹 채팅에 메시지를 보내고, 그룹 채팅에서 메시지를 받고, 다른 에이전트의 메시지에 응답할 수 있습니다.
이 패턴은 모든 메시지가 중앙 서버를 통해 라우팅되는 중앙 집중식 아키텍처나 메시지가 직접 교환되는 분산 아키텍처로 구현될 수 있습니다.

### 작업 이양
이 패턴은 여러 에이전트가 작업을 서로 이양할 수 있는 애플리케이션을 만들고자 할 때 유용합니다.
이 패턴의 일반적인 사용 사례로는 고객 지원, 작업 관리, 워크플로 자동화 등이 있습니다.
이 패턴에서 각 에이전트는 작업 또는 워크플로의 단계를 나타내며, 에이전트는 미리 정의된 규칙에 따라 작업을 다른 에이전트에게 이양할 수 있습니다.

### 협업 필터링
이 패턴은 여러 에이전트가 협력하여 사용자에게 추천을 제공하는 애플리케이션을 만들고자 할 때 유용합니다.
왜 여러 에이전트가 협력해야 할까요? 각 에이전트가 다른 전문성을 가지고 있어 추천 과정에서 다양한 방식으로 기여할 수 있기 때문입니다.
예를 들어, 사용자가 주식 시장에서 구매할 최고의 주식에 대한 추천을 원한다고 가정해 봅시다.
- **산업 전문가**: 한 에이전트는 특정 산업의 전문가일 수 있습니다.
- **기술적 분석**: 다른 에이전트는 기술적 분석의 전문가일 수 있습니다.
- **기본적 분석**: 또 다른 에이전트는 기본적 분석의 전문가일 수 있습니다. 이러한 에이전트들이 협력하여 사용자에게 더 포괄적인 추천을 제공할 수 있습니다.

## 시나리오: 환불 처리
고객이 제품 환불을 요청하는 시나리오를 고려해 봅시다. 이 과정에는 여러 에이전트가 관여할 수 있으며, 이를 특정 환불 프로세스 전용 에이전트와 다른 프로세스에도 사용할 수 있는 일반 에이전트로 나눌 수 있습니다.
**환불 프로세스 전용 에이전트**:
환불 프로세스에 관여할 수 있는 에이전트는 다음과 같습니다:
- **고객 에이전트**: 고객을 대표하며 환불 프로세스를 시작하는 역할을 합니다.
- **판매자 에이전트**: 판매자를 대표하며 환불을 처리하는 역할을 합니다.
- **결제 에이전트**: 결제 프로세스를 대표하며 고객의 결제를 환불하는 역할을 합니다.
- **해결 에이전트**: 해결 프로세스를 대표하며 환불 과정에서 발생하는 문제를 해결하는 역할을 합니다.
- **준수 에이전트**: 준수 프로세스를 대표하며 환불 과정이 규정과 정책을 준수하도록 보장하는 역할을 합니다.
**일반 에이전트**:
이 에이전트들은 비즈니스의 다른 부분에서도 사용할 수 있습니다.
- **배송 에이전트**: 배송 프로세스를 대표하며 제품을 판매자에게 다시 배송하는 역할을 합니다. 이 에이전트는 환불 프로세스뿐만 아니라 일반적인 제품 배송에도 사용할 수 있습니다.
- **피드백 에이전트**: 피드백 프로세스를 대표하며 고객의 피드백을 수집하는 역할을 합니다. 피드백은 환불 과정뿐만 아니라 언제든지 수집할 수 있습니다.
- **에스컬레이션 에이전트**: 에스컬레이션 프로세스를 대표하며 문제를 상위 지원 수준으로 전달하는 역할을 합니다. 이 유형의 에이전트는 문제를 에스컬레이션해야 하는 모든 프로세스에 사용할 수 있습니다.
- **알림 에이전트**: 알림 프로세스를 대표하며 환불 과정의 다양한 단계에서 고객에게 알림을 보내는 역할을 합니다.
- **분석 에이전트**: 분석 프로세스를 대표하며 환불 과정과 관련된 데이터를 분석하는 역할을 합니다.
- **감사 에이전트**: 감사 프로세스를 대표하며 환불 과정이 올바르게 수행되고 있는지 감사하는 역할을 합니다.
- **보고 에이전트**: 보고 프로세스를 대표하며 환불 과정에 대한 보고서를 생성하는 역할을 합니다.
- **지식 에이전트**: 지식 프로세스를 대표하며 환불 과정과 관련된 정보의 지식 기반을 유지하는 역할을 합니다. 이 에이전트는 환불뿐만 아니라 비즈니스의 다른 부분에 대한 지식을 보유할 수 있습니다.
- **보안 에이전트**: 보안 프로세스를 대표하며 환불 과정의 보안을 보장하는 역할을 합니다.
- **품질 에이전트**: 품질 프로세스를 대표하며 환불 과정의 품질을 보장하는 역할을 합니다.
위에서 나열된 에이전트는 환불 프로세스 전용 에이전트와 비즈니스의 다른 부분에서도 사용할 수 있는 일반 에이전트를 포함하여 꽤 많습니다. 이를 통해 다중 에이전트 시스템에서 사용할 에이전트를 결정하는 방법에 대한 아이디어를 얻을 수 있기를 바랍니다.
## 과제
이번 강의를 위한 좋은 과제는 무엇일까요?
고객 지원 프로세스를 위한 다중 에이전트 시스템을 설계하세요. 프로세스에 관여하는 에이전트, 각 에이전트의 역할과 책임, 에이전트 간의 상호작용 방식을 식별하세요. 고객 지원 프로세스에 특화된 에이전트와 비즈니스의 다른 부분에서도 사용할 수 있는 일반 에이전트를 모두 고려하세요.
> 아래 솔루션을 읽기 전에 스스로 생각해 보세요. 예상보다 더 많은 에이전트가 필요할 수 있습니다.
> TIP: 고객 지원 프로세스의 다양한 단계를 생각해 보고, 시스템에 필요한 에이전트도 고려하세요.
## 솔루션
[솔루션](./solution/solution.md)
## 지식 확인
질문: 언제 다중 에이전트를 고려해야 하나요?
- [] A1: 작업량이 적고 간단한 작업일 때
- [] A2: 작업량이 많을 때
- [] A3: 간단한 작업일 때
[퀴즈 솔루션](./solution/solution-quiz.md)
## 요약
이번 강의에서는 다중 에이전트 설계 패턴에 대해 살펴보았습니다. 다중 에이전트가 적용 가능한 시나리오, 단일 에이전트보다 다중 에이전트를 사용하는 장점, 다중 에이전트 설계 패턴을 구현하기 위한 구성 요소, 여러 에이전트 간 상호작용에 대한 가시성을 확보하는 방법 등을 다루었습니다.
## 추가 자료
- [Autogen design patterns](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/design-patterns/intro.html)
- [Agentic design patterns](https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/)
```
**면책 조항**:
이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 노력하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원문이 작성된 언어의 문서를 신뢰할 수 있는 권위 있는 자료로 간주해야 합니다. 중요한 정보에 대해서는 전문적인 인간 번역을 권장합니다. 이 번역을 사용함으로써 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/08-multi-agent/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/08-multi-agent/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 8222
} |
# AI 에이전트의 메타인지
## 소개
AI 에이전트의 메타인지에 대한 수업에 오신 것을 환영합니다! 이 장은 AI 에이전트가 자신의 사고 과정을 어떻게 인식하고 평가할 수 있는지 궁금해하는 초보자를 위해 설계되었습니다. 이 수업이 끝날 때쯤에는 주요 개념을 이해하고 AI 에이전트 설계에 메타인지를 적용할 수 있는 실용적인 예제를 갖추게 될 것입니다.
## 학습 목표
이 수업을 완료한 후, 다음을 할 수 있습니다:
1. 에이전트 정의에서 추론 루프의 의미를 이해합니다.
2. 자기 수정 에이전트를 돕기 위한 계획 및 평가 기법을 사용합니다.
3. 작업을 수행하기 위해 코드를 조작할 수 있는 자신만의 에이전트를 만듭니다.
## 메타인지 소개
메타인지는 자신의 사고를 생각하는 고차원적인 인지 과정을 의미합니다. AI 에이전트의 경우, 이는 자기 인식과 과거 경험을 기반으로 자신의 행동을 평가하고 조정할 수 있는 능력을 의미합니다.
### 메타인지란 무엇인가?
메타인지, 즉 "생각에 대한 생각"은 자기 인식과 자신의 인지 과정을 자기 조절하는 고차원적인 인지 과정입니다. AI 분야에서 메타인지는 에이전트가 전략과 행동을 평가하고 적응할 수 있는 능력을 부여하여 문제 해결 및 의사 결정 능력을 향상시킵니다. 메타인지를 이해함으로써 더 지능적이고 적응 가능하며 효율적인 AI 에이전트를 설계할 수 있습니다.
### AI 에이전트에서 메타인지의 중요성
메타인지는 다음과 같은 이유로 AI 에이전트 설계에서 중요한 역할을 합니다:

- **자기 성찰**: 에이전트는 자신의 성과를 평가하고 개선이 필요한 영역을 식별할 수 있습니다.
- **적응성**: 에이전트는 과거 경험과 변화하는 환경에 따라 전략을 수정할 수 있습니다.
- **오류 수정**: 에이전트는 오류를 자율적으로 감지하고 수정하여 더 정확한 결과를 제공합니다.
- **자원 관리**: 에이전트는 행동을 계획하고 평가하여 시간 및 계산 자원과 같은 자원의 사용을 최적화할 수 있습니다.
## AI 에이전트의 구성 요소
메타인지 프로세스를 다루기 전에 AI 에이전트의 기본 구성 요소를 이해하는 것이 중요합니다. AI 에이전트는 일반적으로 다음으로 구성됩니다:
- **페르소나**: 사용자와 상호 작용하는 방식을 정의하는 에이전트의 성격 및 특성.
- **도구**: 에이전트가 수행할 수 있는 기능 및 능력.
- **기술**: 에이전트가 보유한 지식과 전문성.
이 구성 요소는 특정 작업을 수행할 수 있는 "전문성 단위"를 만듭니다.
**예제**: 여행 에이전트를 고려해 보세요. 이 에이전트는 사용자의 여행 계획을 세울 뿐만 아니라 실시간 데이터 및 과거 고객 경험을 기반으로 경로를 조정합니다.
### 예제: 여행 에이전트 서비스에서의 메타인지
AI로 구동되는 여행 에이전트 서비스를 설계한다고 상상해보세요. 이 에이전트, "여행 에이전트,"는 사용자가 휴가를 계획하도록 돕습니다. 메타인지를 통합하기 위해 여행 에이전트는 자기 인식과 과거 경험을 기반으로 자신의 행동을 평가하고 조정해야 합니다.
#### 현재 작업
현재 작업은 사용자가 파리로 여행을 계획하도록 돕는 것입니다.
#### 작업 완료 단계
1. **사용자 선호 수집**: 사용자에게 여행 날짜, 예산, 관심사(예: 박물관, 요리, 쇼핑), 특정 요구 사항에 대해 묻습니다.
2. **정보 검색**: 사용자의 선호에 맞는 항공편 옵션, 숙박 시설, 관광 명소 및 레스토랑을 검색합니다.
3. **추천 생성**: 항공편 세부 정보, 호텔 예약 및 제안된 활동이 포함된 개인 맞춤형 일정표를 제공합니다.
4. **피드백에 따라 조정**: 추천에 대한 사용자 피드백을 요청하고 필요한 조정을 합니다.
#### 필요한 자원
- 항공편 및 호텔 예약 데이터베이스에 대한 액세스.
- 파리 관광 명소 및 레스토랑에 대한 정보.
- 이전 상호작용에서의 사용자 피드백 데이터.
#### 경험 및 자기 성찰
여행 에이전트는 성과를 평가하고 과거 경험에서 학습하기 위해 메타인지를 사용합니다. 예를 들어:
1. **사용자 피드백 분석**: 여행 에이전트는 사용자가 긍정적으로 평가한 추천과 그렇지 않은 추천을 검토합니다. 그리고 이를 기반으로 미래의 제안을 조정합니다.
2. **적응성**: 사용자가 이전에 붐비는 장소를 싫어한다고 언급한 경우, 여행 에이전트는 향후 혼잡한 관광지를 피크 시간대에 추천하지 않습니다.
3. **오류 수정**: 과거에 예약이 꽉 찬 호텔을 추천하는 오류를 범했다면, 여행 에이전트는 추천을 하기 전에 가용성을 더 철저히 확인하도록 학습합니다.
#### 실용적인 개발자 예제
다음은 메타인지를 통합할 때 여행 에이전트 코드가 어떻게 보일 수 있는지에 대한 간단한 예입니다:
```python
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):
# Search for flights, hotels, and attractions based on preferences
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)
# Analyze feedback and adjust future recommendations
self.user_preferences = adjust_preferences(self.user_preferences, feedback)
# Example usage
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)
```
#### 메타인지가 중요한 이유
- **자기 성찰**: 에이전트는 성과를 분석하고 개선이 필요한 영역을 식별할 수 있습니다.
- **적응성**: 에이전트는 피드백과 변화하는 조건에 따라 전략을 수정할 수 있습니다.
- **오류 수정**: 에이전트는 자율적으로 실수를 감지하고 수정할 수 있습니다.
- **자원 관리**: 에이전트는 시간 및 계산 자원과 같은 자원의 사용을 최적화할 수 있습니다.
메타인지를 통합함으로써, 여행 에이전트는 더 개인화되고 정확한 여행 추천을 제공하여 전체 사용자 경험을 향상시킬 수 있습니다.
---
## 2. 에이전트의 계획
계획은 AI 에이전트 행동의 중요한 구성 요소입니다. 계획에는 현재 상태, 자원 및 가능한 장애물을 고려하여 목표를 달성하기 위한 단계를 개략적으로 설명하는 것이 포함됩니다.
### 계획의 요소
- **현재 작업**: 작업을 명확히 정의합니다.
- **작업 완료 단계**: 작업을 관리 가능한 단계로 세분화합니다.
- **필요한 자원**: 필요한 자원을 식별합니다.
- **경험**: 계획을 알리기 위해 과거 경험을 활용합니다.
**예제**: 여행 에이전트가 사용자의 여행 계획을 효과적으로 돕기 위해 수행해야 하는 단계는 다음과 같습니다:
### 여행 에이전트를 위한 단계
1. **사용자 선호 수집**
- 사용자에게 여행 날짜, 예산, 관심사 및 특정 요구 사항에 대한 세부 정보를 요청합니다.
- 예: "언제 여행을 계획 중이신가요?" "예산 범위는 얼마인가요?" "휴가에서 어떤 활동을 즐기시나요?"
2. **정보 검색**
- 사용자 선호를 기반으로 관련 여행 옵션을 검색합니다.
- **항공편**: 사용자의 예산 및 선호하는 여행 날짜 내에서 이용 가능한 항공편을 찾습니다.
- **숙박 시설**: 위치, 가격, 편의 시설에 대한 사용자의 선호와 일치하는 호텔 또는 렌탈 숙소를 찾습니다.
- **관광 명소 및 레스토랑**: 사용자의 관심사에 맞는 인기 관광 명소, 활동 및 식사 옵션을 식별합니다.
3. **추천 생성**
- 검색된 정보를 개인 맞춤형 일정표로 컴파일합니다.
- 사용자 선호에 맞게 추천을 조정하여 항공편 옵션, 호텔 예약 및 제안된 활동 세부 정보를 제공합니다.
4. **일정표를 사용자에게 제시**
- 제안된 일정표를 사용자에게 공유하여 검토를 요청합니다.
- 예: "여기 파리 여행을 위한 제안된 일정표가 있습니다. 항공편 세부 정보, 호텔 예약 및 추천 활동 목록이 포함되어 있습니다. 의견을 알려주세요!"
5. **피드백 수집**
- 제안된 일정표에 대한 사용자 피드백을 요청합니다.
- 예: "항공편 옵션이 마음에 드시나요?" "호텔이 필요에 적합한가요?" "추가하거나 제거하고 싶은 활동이 있나요?"
6. **피드백에 따라 조정**
- 사용자의 피드백을 기반으로 일정표를 수정합니다.
- 사용자 선호에 더 잘 맞도록 항공편, 숙박 및 활동 추천을 변경합니다.
7. **최종 확인**
- 업데이트된 일정표를 사용자에게 최종 확인을 위해 제시합니다.
- 예: "피드백을 기반으로 조정을 완료했습니다. 업데이트된 일정표입니다. 모두 괜찮으신가요?"
8. **예약 및 확인**
- 사용자가 일정표를 승인하면 항공편, 숙박 시설 및 사전 계획된 활동 예약을 진행합니다.
- 확인 세부 정보를 사용자에게 보냅니다.
9. **지속적인 지원 제공**
- 여행 전후에 사용자의 변경 요청이나 추가 요청을 돕기 위해 대기합니다.
- 예: "여행 중 추가 도움이 필요하시면 언제든지 연락 주세요!"
### 예제 상호작용
```python
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)
# Example usage within a booing request
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)
```
```
```markdown
여행 에이전트는 사용자 피드백을 기반으로 새로운 검색 쿼리를 작성합니다.
- 예: ```python
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
```
- **도구**: 여행 에이전트는 알고리즘을 사용하여 새로운 검색 결과를 순위 매기고 필터링하며, 사용자 피드백을 기반으로 관련성을 강조합니다.
- 예: ```python
new_attractions = search_attractions(preferences)
new_itinerary = create_itinerary(flights, hotels, new_attractions)
print("Updated Itinerary:", new_itinerary)
```
- **평가**: 여행 에이전트는 사용자 피드백을 분석하고 필요한 조정을 수행하여 추천의 관련성과 정확성을 지속적으로 평가합니다.
- 예: ```python
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)
```
#### 실용적인 예
다음은 여행 에이전트에서 Corrective RAG 접근 방식을 통합한 간단한 Python 코드 예제입니다:
```python
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
# Example usage
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)
```
### 사전 컨텍스트 로드
사전 컨텍스트 로드는 쿼리를 처리하기 전에 관련 컨텍스트 또는 배경 정보를 모델에 로드하는 것을 포함합니다. 이는 모델이 프로세스 중에 추가 데이터를 검색할 필요 없이 더 많은 정보를 바탕으로 응답을 생성할 수 있도록 도와줍니다.
다음은 Python에서 여행 에이전트 애플리케이션에 사전 컨텍스트 로드를 구현하는 간단한 예입니다:
```python
class TravelAgent:
def __init__(self):
# Pre-load popular destinations and their information
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):
# Fetch destination information from pre-loaded context
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}."
# Example usage
travel_agent = TravelAgent()
print(travel_agent.get_destination_info("Paris"))
print(travel_agent.get_destination_info("Tokyo"))
```
#### 설명
1. **초기화 (`__init__` method)**: The `TravelAgent` class pre-loads a dictionary containing information about popular destinations such as Paris, Tokyo, New York, and Sydney. This dictionary includes details like the country, currency, language, and major attractions for each destination.
2. **Retrieving Information (`get_destination_info` method)**: When a user queries about a specific destination, the `get_destination_info` 메서드)**: 이 메서드는 미리 로드된 컨텍스트 사전에서 관련 정보를 검색합니다. 컨텍스트를 미리 로드함으로써, 여행 에이전트 애플리케이션은 실시간으로 외부 소스에서 이 정보를 검색할 필요 없이 사용자 쿼리에 빠르게 응답할 수 있습니다. 이는 애플리케이션을 더 효율적이고 응답성이 높게 만듭니다.
### 목표를 설정한 계획 부트스트래핑 후 반복
목표를 설정한 계획 부트스트래핑은 명확한 목표 또는 원하는 결과를 염두에 두고 시작하는 것을 포함합니다. 이 목표를 사전에 정의함으로써, 모델은 반복 과정 내내 이를 안내 원칙으로 사용할 수 있습니다. 이는 각 반복이 원하는 결과 달성에 한 걸음 더 가까워지도록 보장하여 프로세스를 더 효율적이고 집중되게 만듭니다.
다음은 Python에서 여행 에이전트에 대해 목표를 설정한 여행 계획을 부트스트래핑하는 예입니다:
### 시나리오
여행 에이전트는 고객을 위해 맞춤형 휴가를 계획하려고 합니다. 목표는 고객의 선호도와 예산을 기반으로 고객 만족도를 극대화하는 여행 일정을 만드는 것입니다.
### 단계
1. 고객의 선호도와 예산을 정의합니다.
2. 이러한 선호도를 기반으로 초기 계획을 부트스트래핑합니다.
3. 고객의 만족도를 최적화하기 위해 계획을 반복적으로 개선합니다.
#### Python 코드
```python
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']
# Example usage
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)
```
#### 코드 설명
1. **초기화 (`__init__` method)**: The `TravelAgent` class is initialized with a list of potential destinations, each having attributes like name, cost, and activity type.
2. **Bootstrapping the Plan (`bootstrap_plan` method)**: This method creates an initial travel plan based on the client's preferences and budget. It iterates through the list of destinations and adds them to the plan if they match the client's preferences and fit within the budget.
3. **Matching Preferences (`match_preferences` method)**: This method checks if a destination matches the client's preferences.
4. **Iterating the Plan (`iterate_plan` method)**: This method refines the initial plan by trying to replace each destination in the plan with a better match, considering the client's preferences and budget constraints.
5. **Calculating Cost (`calculate_cost` 메서드)**: 이 메서드는 현재 계획의 총 비용(새로운 목적지를 포함할 수 있음)을 계산합니다.
#### 예제 사용법
- **초기 계획**: 여행 에이전트는 고객의 관광 선호도와 $2000의 예산을 기반으로 초기 계획을 생성합니다.
- **개선된 계획**: 여행 에이전트는 계획을 반복적으로 개선하여 고객의 선호도와 예산을 최적화합니다.
목표(예: 고객 만족 극대화)를 명확히 설정한 상태에서 계획을 부트스트래핑하고 이를 개선하기 위해 반복함으로써, 여행 에이전트는 고객을 위한 맞춤형 최적화된 여행 일정을 생성할 수 있습니다. 이 접근 방식은 여행 계획이 처음부터 고객의 선호도와 예산에 부합하도록 보장하며, 각 반복마다 개선됩니다.
### LLM을 활용한 재순위 매기기 및 점수화
대규모 언어 모델(LLM)은 검색된 문서나 생성된 응답의 관련성과 품질을 평가하여 재순위 매기기 및 점수화에 사용될 수 있습니다. 다음은 그 작동 방식입니다:
**검색:** 초기 검색 단계는 쿼리를 기반으로 후보 문서나 응답 세트를 가져옵니다.
**재순위 매기기:** LLM은 이러한 후보를 평가하고 관련성과 품질에 따라 재순위를 매깁니다. 이 단계는 가장 관련성이 높고 품질이 좋은 정보가 먼저 제공되도록 보장합니다.
**점수화:** LLM은 각 후보에게 관련성과 품질을 반영하는 점수를 할당합니다. 이는 사용자에게 가장 적합한 응답이나 문서를 선택하는 데 도움을 줍니다.
LLM을 재순위 매기기 및 점수화에 활용함으로써 시스템은 더 정확하고 맥락적으로 관련성 있는 정보를 제공하여 전체 사용자 경험을 개선할 수 있습니다.
다음은 여행 에이전트가 사용자 선호도를 기반으로 여행지를 재순위 매기고 점수화하기 위해 대규모 언어 모델(LLM)을 사용하는 방법의 예입니다:
#### 시나리오 - 선호도 기반 여행
여행 에이전트는 사용자 선호도를 기반으로 고객에게 최고의 여행지를 추천하고자 합니다. LLM은 여행지를 재순위 매기고 점수화하여 가장 관련성 높은 옵션을 제공하도록 도와줍니다.
#### 단계:
1. 사용자 선호도를 수집합니다.
2. 잠재적인 여행지 목록을 검색합니다.
3. LLM을 사용하여 사용자 선호도를 기반으로 여행지를 재순위 매기고 점수화합니다.
Azure OpenAI 서비스를 사용하여 이전 예제를 업데이트하는 방법은 다음과 같습니다:
#### 요구 사항
1. Azure 구독이 필요합니다.
2. Azure OpenAI 리소스를 생성하고 API 키를 가져옵니다.
#### Python 코드 예제
```python
import requests
import json
class TravelAgent:
def __init__(self, destinations):
self.destinations = destinations
def get_recommendations(self, preferences, api_key, endpoint):
# Generate a prompt for the Azure OpenAI
prompt = self.generate_prompt(preferences)
# Define headers and payload for the request
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
payload = {
"prompt": prompt,
"max_tokens": 150,
"temperature": 0.7
}
# Call the Azure OpenAI API to get the re-ranked and scored destinations
response = requests.post(endpoint, headers=headers, json=payload)
response_data = response.json()
# Extract and return the recommendations
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
# Example usage
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)
```
#### 코드 설명 - 선호도 기반 추천
1. **초기화**: `TravelAgent` class is initialized with a list of potential travel destinations, each having attributes like name and description.
2. **Getting Recommendations (`get_recommendations` method)**: This method generates a prompt for the Azure OpenAI service based on the user's preferences and makes an HTTP POST request to the Azure OpenAI API to get re-ranked and scored destinations.
3. **Generating Prompt (`generate_prompt` method)**: This method constructs a prompt for the Azure OpenAI, including the user's preferences and the list of destinations. The prompt guides the model to re-rank and score the destinations based on the provided preferences.
4. **API Call**: The `requests` library is used to make an HTTP POST request to the Azure OpenAI API endpoint. The response contains the re-ranked and scored destinations.
5. **Example Usage**: The travel agent collects user preferences (e.g., interest in sightseeing and diverse culture) and uses the Azure OpenAI service to get re-ranked and scored recommendations for travel destinations.
Make sure to replace `your_azure_openai_api_key` with your actual Azure OpenAI API key and `https://your-endpoint.com/...`를 Azure OpenAI 배포의 실제 엔드포인트 URL로 대체합니다.
LLM을 재순위 매기기 및 점수화에 활용함으로써, 여행 에이전트는 고객에게 더 개인화되고 관련성 높은 여행 추천을 제공하여 전체 경험을 향상시킬 수 있습니다.
```
```markdown
파리 최고의 박물관?"). - **탐색 의도**: 사용자가 특정 웹사이트나 페이지로 이동하려고 함 (예: "루브르 박물관 공식 웹사이트"). - **거래 의도**: 사용자가 항공편 예약 또는 구매와 같은 거래를 수행하려고 함 (예: "파리행 항공편 예약"). 2. **컨텍스트 인식**: - 사용자의 쿼리 컨텍스트를 분석하면 의도를 정확하게 식별하는 데 도움이 됨. 여기에는 이전 상호작용, 사용자 선호도, 현재 쿼리의 세부 정보가 포함됨. 3. **자연어 처리 (NLP)**: - NLP 기술을 사용하여 사용자가 제공한 자연어 쿼리를 이해하고 해석함. 여기에는 엔터티 인식, 감정 분석, 쿼리 구문 분석과 같은 작업이 포함됨. 4. **개인화**: - 사용자의 기록, 선호도, 피드백을 기반으로 검색 결과를 개인화하면 검색된 정보의 관련성을 높일 수 있음. #### 실용적인 예: 여행 에이전트에서 의도를 활용한 검색 여행 에이전트를 예로 들어 의도를 활용한 검색이 어떻게 구현될 수 있는지 살펴보자. 1. **사용자 선호도 수집** ```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
``` 2. **사용자 의도 이해** ```python
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"
``` 3. **컨텍스트 인식** ```python
def analyze_context(query, user_history):
# Combine current query with user history to understand context
context = {
"current_query": query,
"user_history": user_history
}
return context
``` 4. **검색 및 결과 개인화** ```python
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):
# Example search logic for informational intent
results = search_web(f"best {preferences['interests']} in {preferences['destination']}")
return results
def search_navigation(query):
# Example search logic for navigational intent
results = search_web(query)
return results
def search_transaction(query, preferences):
# Example search logic for transactional intent
results = search_web(f"book {query} to {preferences['destination']}")
return results
def personalize_results(results, user_history):
# Example personalization logic
personalized = [result for result in results if result not in user_history]
return personalized[:10] # Return top 10 personalized results
``` 5. **예제 사용법** ```python
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)
``` --- ## 4. 도구로서의 코드 생성 코드 생성 에이전트는 AI 모델을 사용하여 코드를 작성하고 실행하며 복잡한 문제를 해결하고 작업을 자동화함. ### 코드 생성 에이전트 코드 생성 에이전트는 생성적 AI 모델을 사용하여 코드를 작성하고 실행함. 이러한 에이전트는 다양한 프로그래밍 언어로 코드를 생성하고 실행하여 복잡한 문제를 해결하고 작업을 자동화하며 귀중한 통찰력을 제공할 수 있음. #### 실용적인 응용 1. **자동 코드 생성**: 데이터 분석, 웹 스크래핑, 기계 학습과 같은 특정 작업에 대한 코드 스니펫 생성. 2. **RAG로서의 SQL**: 데이터베이스에서 데이터를 검색하고 조작하기 위해 SQL 쿼리를 사용. 3. **문제 해결**: 알고리즘 최적화 또는 데이터 분석과 같은 특정 문제를 해결하기 위해 코드 생성 및 실행. #### 예제: 데이터 분석을 위한 코드 생성 에이전트 데이터 분석을 위한 코드 생성 에이전트를 설계한다고 가정해 보자. 작동 방식은 다음과 같음: 1. **작업**: 데이터셋을 분석하여 트렌드와 패턴을 식별. 2. **단계**: - 데이터셋을 데이터 분석 도구에 로드. - 데이터를 필터링하고 집계하기 위한 SQL 쿼리 생성. - 쿼리를 실행하고 결과를 검색. - 결과를 사용하여 시각화 및 인사이트 생성. 3. **필요한 리소스**: 데이터셋, 데이터 분석 도구, SQL 기능에 대한 접근. 4. **경험**: 이전 분석 결과를 사용하여 향후 분석의 정확성과 관련성을 향상. ### 예제: 여행 에이전트를 위한 코드 생성 에이전트 이번 예제에서는 사용자가 여행을 계획할 수 있도록 코드 생성 및 실행을 통해 지원하는 코드 생성 에이전트인 여행 에이전트를 설계함. 이 에이전트는 항공편 옵션 검색, 결과 필터링, 생성적 AI를 사용한 일정 작성과 같은 작업을 처리할 수 있음. #### 코드 생성 에이전트 개요 1. **사용자 선호도 수집**: 목적지, 여행 날짜, 예산, 관심사 등 사용자 입력을 수집. 2. **데이터 검색을 위한 코드 생성**: 항공편, 호텔, 명소에 대한 데이터를 검색하기 위한 코드 스니펫 생성. 3. **생성된 코드 실행**: 생성된 코드를 실행하여 실시간 정보를 검색. 4. **일정 생성**: 검색된 데이터를 개인화된 여행 계획으로 컴파일. 5. **피드백 기반 조정**: 사용자 피드백을 받고 필요하면 코드를 다시 생성하여 결과를 개선. #### 단계별 구현 1. **사용자 선호도 수집** ```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
``` 2. **데이터 검색을 위한 코드 생성** ```python
def generate_code_to_fetch_data(preferences):
# Example: Generate code to search for flights based on user preferences
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):
# Example: Generate code to search for hotels
code = f"""
def search_hotels():
import requests
response = requests.get('https://api.example.com/hotels', params={preferences})
return response.json()
"""
return code
``` 3. **생성된 코드 실행** ```python
def execute_code(code):
# Execute the generated code using 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)
``` 4. **일정 생성** ```python
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)
``` 5. **피드백 기반 조정** ```python
def adjust_based_on_feedback(feedback, preferences):
# Adjust preferences based on user feedback
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)
# Regenerate and execute code with updated preferences
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)
``` ### 환경 인식 및 추론 활용 테이블 스키마 기반으로 쿼리 생성 프로세스를 개선하기 위해 환경 인식 및 추론을 활용할 수 있음. 다음은 이를 구현하는 방법의 예임: 1. **스키마 이해**: 시스템이 테이블 스키마를 이해하고 이를 쿼리 생성에 반영. 2. **피드백 기반 조정**: 시스템이 피드백을 기반으로 사용자 선호도를 조정하고 스키마의 어떤 필드를 업데이트해야 하는지 추론. 3. **쿼리 생성 및 실행**: 새로운 선호도를 기반으로 업데이트된 항공편 및 호텔 데이터를 검색하기 위해 쿼리를 생성 및 실행. 다음은 이러한 개념을 통합한 업데이트된 Python 코드 예제임: ```python
def adjust_based_on_feedback(feedback, preferences, schema):
# Adjust preferences based on user feedback
if "liked" in feedback:
preferences["favorites"] = feedback["liked"]
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
# Reasoning based on schema to adjust other related preferences
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):
# Custom logic to adjust preferences based on schema and feedback
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):
# Generate code to fetch flight data based on updated preferences
return f"fetch_flights(preferences={preferences})"
def generate_code_to_fetch_hotels(preferences):
# Generate code to fetch hotel data based on updated preferences
return f"fetch_hotels(preferences={preferences})"
def execute_code(code):
# Simulate execution of code and return mock data
return {"data": f"Executed: {code}"}
def generate_itinerary(flights, hotels, attractions):
# Generate itinerary based on flights, hotels, and attractions
return {"flights": flights, "hotels": hotels, "attractions": attractions}
# Example schema
schema = {
"favorites": {"positive_adjustment": "increase", "negative_adjustment": "decrease", "default": "neutral"},
"avoid": {"positive_adjustment": "decrease", "negative_adjustment": "increase", "default": "neutral"}
}
# Example usage
preferences = {"favorites": "sightseeing", "avoid": "crowded places"}
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
updated_preferences = adjust_based_on_feedback(feedback, preferences, schema)
# Regenerate and execute code with updated preferences
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)
``` #### 설명 - 피드백 기반 예약 1. **스키마 인식**: `schema` dictionary defines how preferences should be adjusted based on feedback. It includes fields like `favorites` and `avoid`, with corresponding adjustments.
2. **Adjusting Preferences (`adjust_based_on_feedback` method)**: This method adjusts preferences based on user feedback and the schema.
3. **Environment-Based Adjustments (`adjust_based_on_environment` 메서드)**: 이 메서드는 스키마와 피드백을 기반으로 조정을 맞춤화. 4. **쿼리 생성 및 실행**: 조정된 선호도를 기반으로 업데이트된 항공편 및 호텔 데이터를 검색하기 위한 코드를 생성하고 이러한 쿼리 실행을 시뮬레이션. 5. **일정 생성**: 새로운 항공편, 호텔, 명소 데이터를 기반으로 업데이트된 일정을 생성. 시스템을 환경 인식적으로 만들고 스키마를 기반으로 추론함으로써 더 정확하고 관련성 높은 쿼리를 생성할 수 있으며, 이를 통해 더 나은 여행 추천과 개인화된 사용자 경험을 제공할 수 있음. ### RAG 기법으로서의 SQL 사용 SQL(구조적 질의 언어)은 데이터베이스와 상호작용하기 위한 강력한 도구임. RAG(Retrieval-Augmented Generation) 접근 방식의 일부로 사용될 때, SQL은 데이터베이스에서 관련 데이터를 검색하여 AI 에이전트의 응답 또는 작업을 알리고 생성하는 데 활용될 수 있음. 여행 에이전트의 맥락에서 SQL이 RAG 기법으로 어떻게 사용될 수 있는지 살펴보자. #### 핵심 개념 1. **데이터베이스 상호작용**: - SQL은 데이터베이스를 쿼리하고 관련 정보를 검색하며 데이터를 조작하는 데 사용됨. - 예: 항공편 세부 정보, 호텔 정보, 명소를 여행 데이터베이스에서 검색. 2. **RAG와의 통합**: - SQL 쿼리는 사용자 입력 및 선호도를 기반으로 생성됨. - 검색된 데이터는 개인화된 추천 또는 작업을 생성하는 데 사용됨. 3. **동적 쿼리 생성**: - AI 에이전트는 컨텍스트와 사용자 요구에 따라 동적인 SQL 쿼리를 생성. - 예: 예산, 날짜, 관심사를 기반으로 결과를 필터링하도록 SQL 쿼리를 맞춤화. #### 응용 - **자동 코드 생성**: 특정 작업에 대한 코드 스니펫 생성. - **RAG로서의 SQL**: 데이터를 조작하기 위해 SQL 쿼리를 사용. - **문제 해결**: 문제를 해결하기 위해 코드 생성 및 실행. **예제**: 데이터 분석 에이전트: 1. **작업**: 데이터셋을 분석하여 트렌드 찾기. 2. **단계**: - 데이터셋 로드. - 데이터를 필터링하기 위한 SQL 쿼리 생성. - 쿼리를 실행하고 결과 검색. - 시각화 및 인사이트 생성. 3. **리소스**: 데이터셋 접근, SQL 기능. 4. **경험**: 이전 결과를 사용하여 미래 분석 개선. #### 실용적인 예: 여행 에이전트에서 SQL 사용 1. **사용자 선호도 수집** ```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
``` 2. **SQL 쿼리 생성** ```python
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
``` 3. **SQL 쿼리 실행** ```python
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
``` 4. **추천 생성** ```python
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)
``` #### SQL 쿼리 예제 1. **항공편 쿼리** ```sql
SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate';
``` 2. **호텔 쿼리** ```sql
SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate';
``` 3. **명소 쿼리** ```sql
SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine';
``` SQL을 Retrieval-Augmented Generation(RAG) 기법의 일부로 활용하면 여행 에이전트와 같은 AI 에이전트가 관련 데이터를 동적으로 검색하고 활용하여 정확하고 개인화된 추천을 제공할 수 있음. ### 결론 메타인지(Metacognition)는 AI 에이전트의 기능을 크게 향상시킬 수 있는 강력한 도구임. 메타인지 프로세스를 통합함으로써 더 지능적이고 적응력이 뛰어나며 효율적인 에이전트를 설계할 수 있음. 추가 리소스를 사용하여 AI 에이전트의 메타인지라는 흥미로운 세계를 더 탐구해 보세요.
```
**면책 조항**:
이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 노력하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있음을 유의하시기 바랍니다. 원어로 작성된 원본 문서를 신뢰할 수 있는 권위 있는 자료로 간주해야 합니다. 중요한 정보의 경우, 전문 번역가에 의한 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/09-metacognition/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/09-metacognition/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 35114
} |
# 프로덕션 환경에서의 AI 에이전트
## 소개
이 강의에서는 다음을 다룹니다:
- AI 에이전트를 프로덕션 환경에 효과적으로 배포하는 방법.
- AI 에이전트를 프로덕션에 배포할 때 직면할 수 있는 일반적인 실수와 문제.
- 비용을 관리하면서도 AI 에이전트의 성능을 유지하는 방법.
## 학습 목표
이 강의를 완료한 후, 다음을 알게 되고 이해하게 됩니다:
- 프로덕션 환경에서 AI 에이전트 시스템의 성능, 비용, 효율성을 개선하는 기술.
- AI 에이전트를 평가하는 방법과 평가해야 할 요소.
- AI 에이전트를 프로덕션에 배포할 때 비용을 제어하는 방법.
신뢰할 수 있는 AI 에이전트를 배포하는 것이 중요합니다. "신뢰할 수 있는 AI 에이전트 구축" 강의도 확인해 보세요.
## AI 에이전트 평가하기
AI 에이전트를 배포하기 전, 배포 중, 그리고 배포 후에 적절한 평가 시스템을 갖추는 것은 매우 중요합니다. 이를 통해 시스템이 사용자와 여러분의 목표에 부합하는지 확인할 수 있습니다.
AI 에이전트를 평가하려면 에이전트의 출력뿐만 아니라 AI 에이전트가 운영되는 전체 시스템을 평가할 수 있는 능력이 중요합니다. 여기에는 다음이 포함되지만 이에 국한되지는 않습니다:
- 초기 모델 요청.
- 사용자의 의도를 파악하는 에이전트의 능력.
- 작업을 수행하기 위해 적합한 도구를 식별하는 에이전트의 능력.
- 에이전트의 요청에 대한 도구의 응답.
- 도구의 응답을 해석하는 에이전트의 능력.
- 에이전트의 응답에 대한 사용자의 피드백.
이러한 방식으로 개선이 필요한 영역을 보다 모듈식으로 식별할 수 있습니다. 이를 통해 모델, 프롬프트, 도구 및 기타 구성 요소에 대한 변경의 영향을 더 효율적으로 모니터링할 수 있습니다.
## AI 에이전트의 일반적인 문제와 잠재적 해결책
| **문제** | **잠재적 해결책** |
| ------------------------------------------ | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AI 에이전트가 일관되게 작업을 수행하지 않음 | - AI 에이전트에 제공되는 프롬프트를 다듬고 목표를 명확히 설정하세요.<br>- 작업을 하위 작업으로 나누고 여러 에이전트가 이를 처리하도록 하면 도움이 될 수 있는 부분을 식별하세요. |
| AI 에이전트가 연속 루프에 빠짐 | - 프로세스를 종료해야 하는 명확한 조건과 종료 기준을 설정하세요.<br>- 추론 및 계획이 필요한 복잡한 작업의 경우, 추론 작업에 특화된 더 큰 모델을 사용하세요. |
| AI 에이전트의 도구 호출 성능이 저조함 | - 에이전트 시스템 외부에서 도구의 출력을 테스트하고 검증하세요.<br>- 정의된 매개변수, 프롬프트 및 도구의 명칭을 다듬으세요. |
| 멀티 에이전트 시스템이 일관되게 작동하지 않음 | - 각 에이전트에 제공되는 프롬프트를 다듬어 구체적이고 서로 구별되도록 하세요.<br>- "라우팅" 또는 컨트롤러 에이전트를 사용하여 어떤 에이전트가 적합한지 결정하는 계층적 시스템을 구축하세요. |
## 비용 관리
AI 에이전트를 프로덕션 환경에 배포할 때 비용을 관리하기 위한 몇 가지 전략은 다음과 같습니다:
- **응답 캐싱** - 일반적인 요청과 작업을 식별하고, 이를 에이전트 시스템을 거치기 전에 미리 응답하도록 설정하는 것은 유사한 요청의 볼륨을 줄이는 좋은 방법입니다. 더 기본적인 AI 모델을 사용해 요청이 캐싱된 요청과 얼마나 유사한지 식별하는 흐름을 구현할 수도 있습니다.
- **소형 모델 사용** - 소형 언어 모델(SLM)은 특정 에이전트 사용 사례에서 우수한 성능을 발휘할 수 있으며, 비용을 상당히 절감할 수 있습니다. 앞서 언급했듯이, 평가 시스템을 구축하여 대형 모델과 성능을 비교하고 이를 통해 SLM이 사용 사례에서 얼마나 잘 작동하는지 이해하는 것이 가장 좋은 방법입니다.
- **라우터 모델 사용** - 유사한 전략으로 다양한 모델과 크기를 활용하는 방법이 있습니다. LLM/SLM 또는 서버리스 함수를 사용하여 요청의 복잡도에 따라 적합한 모델로 라우팅하면 비용을 절감하면서도 적절한 작업에서 성능을 유지할 수 있습니다.
## 축하합니다
이 강의는 "AI 에이전트 입문"의 마지막 강의입니다.
우리는 이 빠르게 성장하는 업계의 피드백과 변화를 반영하여 지속적으로 강의를 추가할 계획이므로, 가까운 미래에 다시 방문해 주세요.
AI 에이전트를 계속 학습하고 구축하고 싶다면, [Azure AI 커뮤니티 Discord](https://discord.gg/kzRShWzttr)에 참여하세요.
우리는 그곳에서 워크숍, 커뮤니티 라운드테이블, 그리고 "무엇이든 물어보세요" 세션을 진행합니다.
또한, 프로덕션 환경에서 AI 에이전트를 구축하는 데 도움을 줄 수 있는 추가 자료를 모아둔 학습 컬렉션도 제공하고 있습니다.
**면책 조항**:
이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 최선을 다하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원본 문서의 해당 언어 버전이 권위 있는 자료로 간주되어야 합니다. 중요한 정보에 대해서는 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/10-ai-agents-production/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/10-ai-agents-production/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 3345
} |
# Configuração do Curso
## Introdução
Nesta lição, veremos como executar os exemplos de código deste curso.
## Requisitos
- Uma conta no GitHub
- Python 3.12+
## Clonar ou Fazer Fork deste Repositório
Para começar, clone ou faça um fork do repositório no GitHub. Isso criará sua própria versão do material do curso, permitindo que você execute, teste e modifique o código!
Isso pode ser feito clicando no link para [fazer fork do repositório](https://github.com/microsoft/ai-agents-for-beginners/fork).
Agora você deve ter sua própria versão "forkada" deste curso, como mostrado abaixo:

## Obtenha seu Token de Acesso Pessoal (PAT) do GitHub
Atualmente, este curso utiliza o Github Models Marketplace para oferecer acesso gratuito a Modelos de Linguagem de Grande Escala (LLMs) que serão usados para criar Agentes de IA.
Para acessar este serviço, você precisará criar um Token de Acesso Pessoal no GitHub.
Isso pode ser feito acessando as configurações de [Tokens de Acesso Pessoal](https://github.com/settings/personal-access-tokens) na sua conta do GitHub.
Selecione as opções `Fine-grained tokens` no lado esquerdo da sua tela.
Depois, selecione `Generate new token`.

Copie o novo token que você acabou de criar. Agora, adicione-o ao arquivo `.env` incluído neste curso.
## Adicione-o às Variáveis de Ambiente
Para criar seu arquivo `.env`, execute o comando abaixo no terminal:
```bash
cp .env.example .env
```
Isso copiará o arquivo de exemplo e criará um `.env` no seu diretório.
Abra o arquivo e cole o token que você criou no campo `GITHUB_TOKEN=` do arquivo .env.
## Instale os Pacotes Necessários
Para garantir que você tenha todos os pacotes Python necessários para executar o código, execute o comando abaixo no terminal.
Recomendamos criar um ambiente virtual Python para evitar conflitos e problemas.
```bash
pip install -r requirements.txt
```
Isso deve instalar os pacotes Python necessários.
Agora você está pronto para executar o código deste curso. Divirta-se aprendendo mais sobre o mundo dos Agentes de IA!
Se você tiver algum problema durante a configuração, participe do nosso [Discord da Comunidade Azure AI](https://discord.gg/kzRShWzttr) ou [crie um issue](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst).
```
**Aviso Legal**:
Este documento foi traduzido utilizando serviços de tradução baseados em IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte oficial. Para informações críticas, recomenda-se a tradução profissional humana. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/00-course-setup/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/00-course-setup/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 3073
} |
# Introdução a Agentes de IA e Casos de Uso
Bem-vindo ao curso "Agentes de IA para Iniciantes"! Este curso fornece conhecimentos fundamentais e exemplos práticos para a construção de Agentes de IA.
Junte-se à [Comunidade do Discord do Azure AI](https://discord.gg/kzRShWzttr) para conhecer outros alunos, construtores de Agentes de IA e tirar quaisquer dúvidas que você tenha sobre este curso.
Para começar este curso, vamos primeiro entender melhor o que são os Agentes de IA e como podemos utilizá-los em aplicações e fluxos de trabalho que criamos.
## Introdução
Esta lição aborda:
- O que são Agentes de IA e quais são os diferentes tipos de agentes?
- Quais casos de uso são mais indicados para Agentes de IA e como eles podem nos ajudar?
- Quais são alguns dos componentes básicos ao projetar Soluções Agênticas?
## Objetivos de Aprendizado
Após concluir esta lição, você deverá ser capaz de:
- Compreender os conceitos de Agentes de IA e como eles diferem de outras soluções de IA.
- Aplicar Agentes de IA de maneira mais eficiente.
- Projetar soluções agênticas produtivamente para usuários e clientes.
## Definindo Agentes de IA e Tipos de Agentes de IA
### O que são Agentes de IA?
Agentes de IA são **sistemas** que permitem que **Modelos de Linguagem de Grande Escala (LLMs)** **executem ações** ao estender suas capacidades, dando aos LLMs **acesso a ferramentas** e **conhecimento**.
Vamos dividir essa definição em partes menores:
- **Sistema** - É importante pensar nos agentes não apenas como um único componente, mas como um sistema composto por muitos componentes. No nível básico, os componentes de um Agente de IA são:
- **Ambiente** - O espaço definido onde o Agente de IA está operando. Por exemplo, se tivermos um Agente de IA para reservas de viagens, o ambiente pode ser o sistema de reservas de viagens que o agente usa para completar tarefas.
- **Sensores** - Os ambientes possuem informações e fornecem feedback. Agentes de IA usam sensores para coletar e interpretar essas informações sobre o estado atual do ambiente. No exemplo do Agente de Reservas de Viagens, o sistema de reservas pode fornecer informações como disponibilidade de hotéis ou preços de passagens aéreas.
- **Atuadores** - Depois que o Agente de IA recebe o estado atual do ambiente, ele determina qual ação realizar para alterar o ambiente em relação à tarefa atual. No caso do Agente de Reservas de Viagens, isso pode ser reservar um quarto disponível para o usuário.

**Modelos de Linguagem de Grande Escala (LLMs)** - O conceito de agentes existia antes da criação dos LLMs. A vantagem de construir Agentes de IA com LLMs é sua capacidade de interpretar linguagem humana e dados. Essa habilidade permite que os LLMs interpretem informações do ambiente e definam um plano para alterar o ambiente.
**Executar Ações** - Fora dos sistemas de Agentes de IA, os LLMs são limitados a situações onde a ação é gerar conteúdo ou informações com base em um comando do usuário. Dentro dos sistemas de Agentes de IA, os LLMs podem realizar tarefas interpretando o pedido do usuário e utilizando ferramentas disponíveis no ambiente.
**Acesso a Ferramentas** - As ferramentas às quais o LLM tem acesso são definidas por 1) o ambiente em que está operando e 2) o desenvolvedor do Agente de IA. No exemplo do agente de viagens, as ferramentas do agente são limitadas pelas operações disponíveis no sistema de reservas e/ou o desenvolvedor pode limitar o acesso do agente a ferramentas relacionadas a voos.
**Conhecimento** - Além das informações fornecidas pelo ambiente, os Agentes de IA também podem recuperar conhecimento de outros sistemas, serviços, ferramentas e até outros agentes. No exemplo do agente de viagens, esse conhecimento pode incluir informações sobre as preferências de viagem do usuário localizadas em um banco de dados de clientes.
### Os diferentes tipos de agentes
Agora que temos uma definição geral de Agentes de IA, vamos analisar alguns tipos específicos de agentes e como eles seriam aplicados a um agente de reservas de viagens.
| **Tipo de Agente** | **Descrição** | **Exemplo** |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **Agentes de Reflexo Simples**| Executam ações imediatas com base em regras predefinidas. | O agente de viagens interpreta o contexto de um e-mail e encaminha reclamações de viagem para o atendimento ao cliente. |
| **Agentes Baseados em Modelo**| Executam ações com base em um modelo do mundo e mudanças nesse modelo. | O agente de viagens prioriza rotas com mudanças significativas de preço com base no acesso a dados históricos de preços. |
| **Agentes Baseados em Objetivos** | Criam planos para atingir objetivos específicos, interpretando o objetivo e determinando as ações necessárias para alcançá-lo. | O agente de viagens reserva uma jornada determinando os arranjos de viagem necessários (carro, transporte público, voos) do local atual ao destino. |
| **Agentes Baseados em Utilidade** | Consideram preferências e ponderam trade-offs numericamente para determinar como atingir objetivos. | O agente de viagens maximiza a utilidade ao ponderar conveniência versus custo ao reservar viagens. |
| **Agentes de Aprendizado** | Melhoram com o tempo, respondendo a feedbacks e ajustando ações de acordo. | O agente de viagens melhora usando o feedback de clientes de pesquisas pós-viagem para fazer ajustes em reservas futuras. |
| **Agentes Hierárquicos** | Apresentam múltiplos agentes em um sistema hierárquico, com agentes de nível superior dividindo tarefas em subtarefas para agentes de nível inferior completarem. | O agente de viagens cancela uma viagem dividindo a tarefa em subtarefas (por exemplo, cancelar reservas específicas) e permitindo que agentes de nível inferior as concluam, reportando de volta ao agente de nível superior. |
| **Sistemas Multiagentes (MAS)**| Agentes completam tarefas de forma independente, cooperativa ou competitiva. | Cooperativo: Múltiplos agentes reservam serviços específicos de viagem, como hotéis, voos e entretenimento. Competitivo: Múltiplos agentes gerenciam e competem por um calendário compartilhado de reservas de hotel. |
## Quando Usar Agentes de IA
Na seção anterior, usamos o caso de uso do Agente de Viagens para explicar como diferentes tipos de agentes podem ser usados em cenários variados de reservas de viagem. Continuaremos utilizando este exemplo ao longo do curso.
Vamos analisar os tipos de casos de uso que são mais adequados para Agentes de IA:

- **Problemas Abertos** - permitindo que o LLM determine os passos necessários para completar uma tarefa, pois nem sempre é possível codificar isso diretamente em um fluxo de trabalho.
- **Processos com Múltiplas Etapas** - tarefas que exigem um nível de complexidade em que o Agente de IA precisa usar ferramentas ou informações ao longo de várias interações, em vez de uma única busca.
- **Melhoria ao Longo do Tempo** - tarefas onde o agente pode melhorar ao longo do tempo ao receber feedback do ambiente ou dos usuários para oferecer melhor utilidade.
Abordamos mais considerações sobre o uso de Agentes de IA na lição Construindo Agentes de IA Confiáveis.
## Fundamentos das Soluções Agênticas
### Desenvolvimento de Agentes
O primeiro passo ao projetar um sistema de Agente de IA é definir as ferramentas, ações e comportamentos. Neste curso, focamos no uso do **Azure AI Agent Service** para definir nossos Agentes. Ele oferece recursos como:
- Seleção de Modelos Abertos, como OpenAI, Mistral e Llama
- Uso de Dados Licenciados por meio de provedores como Tripadvisor
- Uso de ferramentas padronizadas OpenAPI 3.0
### Padrões Agênticos
A comunicação com LLMs é feita por meio de prompts. Dada a natureza semi-autônoma dos Agentes de IA, nem sempre é possível ou necessário reformular manualmente o prompt do LLM após uma mudança no ambiente. Utilizamos **Padrões Agênticos** que permitem que o LLM seja orientado ao longo de várias etapas de maneira mais escalável.
Este curso é dividido em alguns dos padrões agênticos populares atuais.
### Frameworks Agênticos
Frameworks Agênticos permitem que os desenvolvedores implementem padrões agênticos por meio de código. Esses frameworks oferecem templates, plugins e ferramentas para uma melhor colaboração com Agentes de IA. Esses benefícios proporcionam maior observabilidade e resolução de problemas em sistemas de Agentes de IA.
Neste curso, exploraremos o framework AutoGen, baseado em pesquisa, e o framework Agent, pronto para produção, do Semantic Kernel.
**Aviso Legal**:
Este documento foi traduzido utilizando serviços de tradução baseados em IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte oficial. Para informações críticas, recomenda-se uma tradução humana profissional. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações incorretas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/01-intro-to-ai-agents/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/01-intro-to-ai-agents/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 10882
} |
# Explorar Frameworks de Agentes de IA
Frameworks de agentes de IA são plataformas de software projetadas para simplificar a criação, implantação e gerenciamento de agentes de IA. Esses frameworks fornecem aos desenvolvedores componentes pré-construídos, abstrações e ferramentas que agilizam o desenvolvimento de sistemas complexos de IA.
Eles ajudam os desenvolvedores a se concentrarem nos aspectos únicos de suas aplicações, oferecendo abordagens padronizadas para desafios comuns no desenvolvimento de agentes de IA. Esses frameworks melhoram a escalabilidade, acessibilidade e eficiência na construção de sistemas de IA.
## Introdução
Esta lição abordará:
- O que são frameworks de agentes de IA e o que permitem que os desenvolvedores façam?
- Como as equipes podem usá-los para prototipar rapidamente, iterar e melhorar as capacidades do meu agente?
- Quais são as diferenças entre os frameworks e ferramentas criados pela Microsoft ([Autogen](https://aka.ms/ai-agents/autogen) / [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) / [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service))?
- Posso integrar diretamente minhas ferramentas existentes do ecossistema Azure ou preciso de soluções independentes?
- O que é o serviço Azure AI Agents e como isso me ajuda?
## Objetivos de aprendizado
Os objetivos desta lição são ajudá-lo a entender:
- O papel dos frameworks de agentes de IA no desenvolvimento de IA.
- Como aproveitar frameworks de agentes de IA para construir agentes inteligentes.
- Capacidades principais habilitadas por frameworks de agentes de IA.
- As diferenças entre Autogen, Semantic Kernel e Azure AI Agent Service.
## O que são frameworks de agentes de IA e o que permitem que os desenvolvedores façam?
Frameworks tradicionais de IA podem ajudar você a integrar IA em seus aplicativos e melhorar esses aplicativos das seguintes maneiras:
- **Personalização**: A IA pode analisar o comportamento e as preferências do usuário para fornecer recomendações, conteúdos e experiências personalizadas.
Exemplo: Serviços de streaming como Netflix usam IA para sugerir filmes e séries com base no histórico de visualização, aumentando o engajamento e a satisfação do usuário.
- **Automação e Eficiência**: A IA pode automatizar tarefas repetitivas, otimizar fluxos de trabalho e melhorar a eficiência operacional.
Exemplo: Aplicativos de atendimento ao cliente usam chatbots com IA para lidar com consultas comuns, reduzindo o tempo de resposta e liberando agentes humanos para questões mais complexas.
- **Melhoria na Experiência do Usuário**: A IA pode aprimorar a experiência geral do usuário, fornecendo recursos inteligentes, como reconhecimento de voz, processamento de linguagem natural e texto preditivo.
Exemplo: Assistentes virtuais como Siri e Google Assistant usam IA para entender e responder a comandos de voz, facilitando a interação dos usuários com seus dispositivos.
### Isso tudo parece ótimo, certo? Então por que precisamos de frameworks de agentes de IA?
Frameworks de agentes de IA representam algo além dos frameworks tradicionais de IA. Eles são projetados para permitir a criação de agentes inteligentes que podem interagir com usuários, outros agentes e o ambiente para alcançar objetivos específicos. Esses agentes podem exibir comportamento autônomo, tomar decisões e se adaptar a condições em constante mudança. Vamos examinar algumas capacidades principais habilitadas pelos frameworks de agentes de IA:
- **Colaboração e Coordenação entre Agentes**: Permitem a criação de múltiplos agentes de IA que podem trabalhar juntos, se comunicar e coordenar para resolver tarefas complexas.
- **Automação e Gerenciamento de Tarefas**: Fornecem mecanismos para automatizar fluxos de trabalho de múltiplas etapas, delegação de tarefas e gerenciamento dinâmico de tarefas entre agentes.
- **Compreensão Contextual e Adaptação**: Equipam os agentes com a capacidade de entender o contexto, se adaptar a ambientes em mudança e tomar decisões com base em informações em tempo real.
Em resumo, os agentes permitem que você faça mais, leve a automação para o próximo nível e crie sistemas mais inteligentes que podem se adaptar e aprender com seu ambiente.
## Como prototipar rapidamente, iterar e melhorar as capacidades do agente?
Este é um cenário em rápida evolução, mas existem alguns elementos comuns na maioria dos frameworks de agentes de IA que podem ajudar você a prototipar e iterar rapidamente, como componentes modulares, ferramentas colaborativas e aprendizado em tempo real. Vamos explorar esses elementos:
- **Use Componentes Modulares**: Frameworks de IA oferecem componentes pré-construídos, como prompts, analisadores e gerenciamento de memória.
- **Aproveite Ferramentas Colaborativas**: Projete agentes com papéis e tarefas específicas, permitindo testar e refinar fluxos de trabalho colaborativos.
- **Aprenda em Tempo Real**: Implemente loops de feedback onde os agentes aprendem com interações e ajustam seu comportamento dinamicamente.
### Use Componentes Modulares
Frameworks como LangChain e Microsoft Semantic Kernel oferecem componentes pré-construídos, como prompts, analisadores e gerenciamento de memória.
**Como as equipes podem usá-los**: As equipes podem montar rapidamente esses componentes para criar um protótipo funcional sem começar do zero, permitindo experimentação e iteração rápidas.
**Como funciona na prática**: Você pode usar um analisador pré-construído para extrair informações da entrada do usuário, um módulo de memória para armazenar e recuperar dados e um gerador de prompts para interagir com os usuários, tudo isso sem precisar construir esses componentes do zero.
**Exemplo de código**: Vamos ver um exemplo de como você pode usar um analisador pré-construído para extrair informações da entrada do usuário:
```python
from langchain import Parser
parser = Parser()
user_input = "Book a flight from New York to London on July 15th"
parsed_data = parser.parse(user_input)
print(parsed_data)
# Output: {'origin': 'New York', 'destination': 'London', 'date': 'July 15th'}
```
O que você pode ver neste exemplo é como você pode aproveitar um analisador pré-construído para extrair informações-chave da entrada do usuário, como origem, destino e data de uma solicitação de reserva de voo. Essa abordagem modular permite que você se concentre na lógica de alto nível.
### Aproveite Ferramentas Colaborativas
Frameworks como CrewAI e Microsoft Autogen facilitam a criação de múltiplos agentes que podem trabalhar juntos.
**Como as equipes podem usá-los**: As equipes podem projetar agentes com funções e tarefas específicas, permitindo testar e refinar fluxos de trabalho colaborativos e melhorar a eficiência geral do sistema.
**Como funciona na prática**: Você pode criar uma equipe de agentes onde cada agente tem uma função especializada, como recuperação de dados, análise ou tomada de decisão. Esses agentes podem se comunicar e compartilhar informações para alcançar um objetivo comum, como responder a uma consulta do usuário ou concluir uma tarefa.
**Exemplo de código (Autogen)**:
```python
# creating agents, then create a round robin schedule where they can work together, in this case in order
# Data Retrieval Agent
# Data Analysis Agent
# Decision Making Agent
agent_retrieve = AssistantAgent(
name="dataretrieval",
model_client=model_client,
tools=[retrieve_tool],
system_message="Use tools to solve tasks."
)
agent_analyze = AssistantAgent(
name="dataanalysis",
model_client=model_client,
tools=[analyze_tool],
system_message="Use tools to solve tasks."
)
# conversation ends when user says "APPROVE"
termination = TextMentionTermination("APPROVE")
user_proxy = UserProxyAgent("user_proxy", input_func=input)
team = RoundRobinGroupChat([agent_retrieve, agent_analyze, user_proxy], termination_condition=termination)
stream = team.run_stream(task="Analyze data", max_turns=10)
# Use asyncio.run(...) when running in a script.
await Console(stream)
```
O que você vê no código acima é como você pode criar uma tarefa que envolve múltiplos agentes trabalhando juntos para analisar dados. Cada agente desempenha uma função específica, e a tarefa é executada coordenando os agentes para alcançar o resultado desejado. Criando agentes dedicados com funções especializadas, você pode melhorar a eficiência e o desempenho das tarefas.
### Aprenda em Tempo Real
Frameworks avançados fornecem capacidades para compreensão de contexto em tempo real e adaptação.
**Como as equipes podem usá-los**: As equipes podem implementar loops de feedback onde os agentes aprendem com interações e ajustam seu comportamento dinamicamente, levando a uma melhoria contínua e refinamento das capacidades.
**Como funciona na prática**: Agentes podem analisar o feedback do usuário, dados do ambiente e resultados de tarefas para atualizar sua base de conhecimento, ajustar algoritmos de tomada de decisão e melhorar o desempenho ao longo do tempo. Esse processo de aprendizado iterativo permite que os agentes se adaptem a condições em mudança e preferências dos usuários, melhorando a eficácia geral do sistema.
## Quais são as diferenças entre os frameworks Autogen, Semantic Kernel e Azure AI Agent Service?
Existem várias formas de comparar esses frameworks, mas vamos analisar algumas diferenças principais em termos de design, capacidades e casos de uso:
### Autogen
Framework de código aberto desenvolvido pelo AI Frontiers Lab da Microsoft Research. Focado em aplicações *agênticas* distribuídas e orientadas a eventos, permitindo múltiplos LLMs e SLMs, ferramentas e padrões avançados de design multi-agente.
Autogen é baseado no conceito central de agentes, que são entidades autônomas capazes de perceber seu ambiente, tomar decisões e realizar ações para alcançar objetivos específicos. Os agentes se comunicam por meio de mensagens assíncronas, permitindo que trabalhem de forma independente e em paralelo, melhorando a escalabilidade e a capacidade de resposta do sistema.
Os agentes são baseados no [modelo de ator](https://en.wikipedia.org/wiki/Actor_model). Segundo a Wikipedia, um ator é _a unidade básica de computação concorrente. Em resposta a uma mensagem recebida, um ator pode: tomar decisões locais, criar mais atores, enviar mais mensagens e determinar como responder à próxima mensagem recebida_.
**Casos de Uso**: Automação de geração de código, tarefas de análise de dados e construção de agentes personalizados para funções de planejamento e pesquisa.
...
com base nas metas do projeto. Ideal para compreensão de linguagem natural, geração de conteúdo. - **Azure AI Agent Service**: Modelos flexíveis, mecanismos de segurança empresarial, métodos de armazenamento de dados. Ideal para implantação segura, escalável e flexível de agentes de IA em aplicações empresariais. ## Posso integrar diretamente minhas ferramentas existentes do ecossistema Azure ou preciso de soluções independentes? A resposta é sim, você pode integrar diretamente suas ferramentas existentes do ecossistema Azure com o Azure AI Agent Service, especialmente porque ele foi projetado para funcionar perfeitamente com outros serviços Azure. Você poderia, por exemplo, integrar Bing, Azure AI Search e Azure Functions. Há também uma integração profunda com o Azure AI Foundry. Para Autogen e Semantic Kernel, você também pode integrar com serviços Azure, mas pode ser necessário chamar os serviços Azure a partir do seu código. Outra maneira de integrar é usar os SDKs do Azure para interagir com os serviços Azure a partir dos seus agentes. Além disso, como foi mencionado, você pode usar o Azure AI Agent Service como um orquestrador para seus agentes construídos no Autogen ou Semantic Kernel, o que proporcionaria fácil acesso ao ecossistema Azure. ## Referências - [1] - [Azure Agent Service](https://techcommunity.microsoft.com/blog/azure-ai-services-blog/introducing-azure-ai-agent-service/4298357) - [2] - [Semantic Kernel and Autogen](https://devblogs.microsoft.com/semantic-kernel/microsofts-agentic-ai-frameworks-autogen-and-semantic-kernel/) - [3] - [Semantic Kernel Agent Framework](https://learn.microsoft.com/semantic-kernel/frameworks/agent/?pivots=programming-language-csharp) - [4] - [Azure AI Agent service](https://learn.microsoft.com/azure/ai-services/agents/overview) - [5] - [Using Azure AI Agent Service with AutoGen / Semantic Kernel to build a multi-agent's solution](https://techcommunity.microsoft.com/blog/educatordeveloperblog/using-azure-ai-agent-service-with-autogen--semantic-kernel-to-build-a-multi-agen/4363121)
**Aviso Legal**:
Este documento foi traduzido utilizando serviços de tradução automática baseados em IA. Embora nos esforcemos para alcançar precisão, esteja ciente de que traduções automáticas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte autoritária. Para informações críticas, recomenda-se uma tradução humana profissional. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/02-explore-agentic-frameworks/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/02-explore-agentic-frameworks/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 13169
} |
# Princípios de Design de Agentes de IA
## Introdução
Existem muitas maneiras de pensar na construção de Sistemas de Agentes de IA. Considerando que a ambiguidade é uma característica, e não um defeito, no design de IA Generativa, às vezes é difícil para os engenheiros saberem por onde começar. Criamos um conjunto de Princípios de Design centrados no ser humano para permitir que os desenvolvedores construam sistemas de agentes centrados no cliente, capazes de atender às suas necessidades de negócios. Esses princípios de design não são uma arquitetura prescritiva, mas sim um ponto de partida para equipes que estão definindo e desenvolvendo experiências com agentes.
Em geral, os agentes devem:
- Ampliar e escalar as capacidades humanas (brainstorming, resolução de problemas, automação, etc.)
- Preencher lacunas de conhecimento (me atualizar em áreas de conhecimento, tradução, etc.)
- Facilitar e apoiar a colaboração nas formas como preferimos trabalhar com outras pessoas
- Nos tornar melhores versões de nós mesmos (por exemplo, coach de vida/gestor de tarefas, ajudando-nos a aprender habilidades de regulação emocional e mindfulness, construindo resiliência, etc.)
## Esta Aula Abrangerá
- O que são os Princípios de Design de Agentes
- Quais são algumas diretrizes a seguir ao implementar esses princípios de design
- Alguns exemplos de uso dos princípios de design
## Objetivos de Aprendizado
Após completar esta aula, você será capaz de:
1. Explicar o que são os Princípios de Design de Agentes
2. Explicar as diretrizes para o uso dos Princípios de Design de Agentes
3. Entender como construir um agente utilizando os Princípios de Design de Agentes
## Os Princípios de Design de Agentes

### Agente (Espaço)
Este é o ambiente no qual o agente opera. Esses princípios orientam como projetamos agentes para interagir nos mundos físico e digital.
- **Conectar, não substituir** – ajudar a conectar pessoas a outras pessoas, eventos e conhecimentos acionáveis para permitir colaboração e conexão.
- Agentes ajudam a conectar eventos, conhecimentos e pessoas.
- Agentes aproximam as pessoas. Eles não são projetados para substituir ou diminuir o papel das pessoas.
- **Facilmente acessível, mas ocasionalmente invisível** – o agente opera em grande parte em segundo plano e só nos alerta quando é relevante e apropriado.
- O agente é facilmente descoberto e acessível para usuários autorizados em qualquer dispositivo ou plataforma.
- O agente suporta entradas e saídas multimodais (som, voz, texto, etc.).
- O agente pode alternar perfeitamente entre primeiro plano e segundo plano; entre proativo e reativo, dependendo da percepção das necessidades do usuário.
- O agente pode operar de forma invisível, mas o caminho de seus processos em segundo plano e a colaboração com outros agentes são transparentes e controláveis pelo usuário.
### Agente (Tempo)
Este é o modo como o agente opera ao longo do tempo. Esses princípios orientam como projetamos agentes que interagem através do passado, presente e futuro.
- **Passado**: Refletindo sobre o histórico que inclui tanto estado quanto contexto.
- O agente fornece resultados mais relevantes com base na análise de dados históricos mais ricos, indo além do evento, pessoas ou estados isolados.
- O agente cria conexões a partir de eventos passados e reflete ativamente sobre a memória para lidar com situações atuais.
- **Agora**: Mais estímulos do que notificações.
- O agente adota uma abordagem abrangente ao interagir com pessoas. Quando um evento ocorre, o agente vai além de uma notificação estática ou formalidade. Ele pode simplificar fluxos ou gerar dinamicamente dicas para direcionar a atenção do usuário no momento certo.
- O agente entrega informações com base no ambiente contextual, mudanças sociais e culturais, e adaptadas à intenção do usuário.
- A interação com o agente pode ser gradual, evoluindo/crescendo em complexidade para capacitar os usuários a longo prazo.
- **Futuro**: Adaptando-se e evoluindo.
- O agente se adapta a vários dispositivos, plataformas e modalidades.
- O agente se adapta ao comportamento do usuário, necessidades de acessibilidade e é totalmente personalizável.
- O agente é moldado e evolui por meio da interação contínua com o usuário.
### Agente (Núcleo)
Esses são os elementos-chave no núcleo do design de um agente.
- **Aceitar incertezas, mas estabelecer confiança**.
- Um certo nível de incerteza do agente é esperado. A incerteza é um elemento-chave no design de agentes.
- Confiança e transparência são camadas fundamentais no design de agentes.
- Os humanos têm controle sobre quando o agente está ativado/desativado, e o status do agente é claramente visível em todos os momentos.
## Diretrizes Para Implementar Esses Princípios
Ao usar os princípios de design acima, siga as seguintes diretrizes:
1. **Transparência**: Informe o usuário que a IA está envolvida, como ela funciona (incluindo ações passadas) e como fornecer feedback e modificar o sistema.
2. **Controle**: Permita que o usuário personalize, especifique preferências e personalize, tendo controle sobre o sistema e seus atributos (incluindo a capacidade de esquecer).
3. **Consistência**: Busque experiências consistentes e multimodais em dispositivos e pontos de contato. Use elementos familiares de UI/UX sempre que possível (por exemplo, ícone de microfone para interação por voz) e reduza a carga cognitiva do cliente tanto quanto possível (por exemplo, respostas concisas, recursos visuais e conteúdo "Saiba Mais").
## Como Projetar um Agente de Viagem Usando Esses Princípios e Diretrizes
Imagine que você está projetando um Agente de Viagem. Aqui está como você poderia pensar em usar os Princípios de Design e Diretrizes:
1. **Transparência** – Informe ao usuário que o Agente de Viagem é um Agente habilitado por IA. Forneça algumas instruções básicas sobre como começar (por exemplo, uma mensagem de "Olá", prompts de exemplo). Documente isso claramente na página do produto. Mostre a lista de prompts que o usuário fez no passado. Deixe claro como fornecer feedback (botões de curtir/descurtir, botão "Enviar Feedback", etc.). Articule claramente se o Agente tem restrições de uso ou tópicos.
2. **Controle** – Certifique-se de que esteja claro como o usuário pode modificar o Agente após sua criação, com coisas como o Prompt do Sistema. Permita que o usuário escolha o quão detalhado o Agente deve ser, seu estilo de escrita e quaisquer limitações sobre o que o Agente não deve abordar. Permita que o usuário visualize e exclua quaisquer arquivos ou dados associados, prompts e conversas anteriores.
3. **Consistência** – Certifique-se de que os ícones para Compartilhar Prompt, adicionar um arquivo ou foto e marcar alguém ou algo sejam padrões e reconhecíveis. Use o ícone de clipe de papel para indicar upload/compartilhamento de arquivos com o Agente, e um ícone de imagem para indicar upload de gráficos.
## Recursos Adicionais
- [Práticas para Governança de Sistemas de IA Agentes | OpenAI](https://openai.com)
- [O Projeto HAX Toolkit - Microsoft Research](https://microsoft.com)
- [Caixa de Ferramentas de IA Responsável](https://responsibleaitoolbox.ai)
```
**Aviso Legal**:
Este documento foi traduzido utilizando serviços de tradução baseados em IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte oficial. Para informações críticas, recomenda-se a tradução humana profissional. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/03-agentic-design-patterns/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/03-agentic-design-patterns/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 7920
} |
# Padrão de Design para Uso de Ferramentas
## Introdução
Nesta lição, vamos buscar responder às seguintes perguntas:
- O que é o padrão de design para uso de ferramentas?
- Quais são os casos de uso em que ele pode ser aplicado?
- Quais são os elementos/blocos de construção necessários para implementar esse padrão de design?
- Quais são as considerações especiais ao usar o padrão de design para uso de ferramentas para criar agentes de IA confiáveis?
## Objetivos de Aprendizado
Após concluir esta lição, você será capaz de:
- Definir o Padrão de Design para Uso de Ferramentas e seu propósito.
- Identificar casos de uso onde o padrão de design para uso de ferramentas é aplicável.
- Compreender os principais elementos necessários para implementar o padrão de design.
- Reconhecer considerações para garantir a confiabilidade de agentes de IA que utilizam esse padrão de design.
## O que é o Padrão de Design para Uso de Ferramentas?
O **Padrão de Design para Uso de Ferramentas** se concentra em fornecer aos LLMs a capacidade de interagir com ferramentas externas para atingir objetivos específicos. Ferramentas são códigos que podem ser executados por um agente para realizar ações. Uma ferramenta pode ser uma função simples, como uma calculadora, ou uma chamada de API para um serviço de terceiros, como consulta de preços de ações ou previsão do tempo. No contexto de agentes de IA, as ferramentas são projetadas para serem executadas por agentes em resposta a **chamadas de função geradas pelo modelo**.
## Quais são os casos de uso em que ele pode ser aplicado?
Agentes de IA podem aproveitar ferramentas para concluir tarefas complexas, recuperar informações ou tomar decisões. O padrão de design para uso de ferramentas é frequentemente usado em cenários que exigem interação dinâmica com sistemas externos, como bancos de dados, serviços web ou interpretadores de código. Essa capacidade é útil para diversos casos de uso, incluindo:
- **Recuperação Dinâmica de Informações:** Agentes podem consultar APIs externas ou bancos de dados para buscar dados atualizados (por exemplo, consultar um banco de dados SQLite para análise de dados, buscar preços de ações ou informações meteorológicas).
- **Execução e Interpretação de Código:** Agentes podem executar códigos ou scripts para resolver problemas matemáticos, gerar relatórios ou realizar simulações.
- **Automação de Fluxos de Trabalho:** Automatizar fluxos de trabalho repetitivos ou de múltiplas etapas integrando ferramentas como agendadores de tarefas, serviços de e-mail ou pipelines de dados.
- **Suporte ao Cliente:** Agentes podem interagir com sistemas CRM, plataformas de tickets ou bases de conhecimento para resolver dúvidas dos usuários.
- **Geração e Edição de Conteúdo:** Agentes podem usar ferramentas como verificadores gramaticais, resumos de texto ou avaliadores de segurança de conteúdo para auxiliar em tarefas de criação de conteúdo.
## Quais são os elementos/blocos de construção necessários para implementar o padrão de design para uso de ferramentas?
### Chamada de Função/Ferramenta
A chamada de função é a principal forma de permitir que Modelos de Linguagem de Grande Escala (LLMs) interajam com ferramentas. Muitas vezes, você verá "Função" e "Ferramenta" sendo usados de forma intercambiável, pois "funções" (blocos de código reutilizáveis) são as "ferramentas" que os agentes usam para realizar tarefas. Para que o código de uma função seja invocado, um LLM deve comparar a solicitação do usuário com a descrição da função. Para isso, um esquema contendo as descrições de todas as funções disponíveis é enviado ao LLM. O LLM seleciona a função mais apropriada para a tarefa e retorna seu nome e argumentos. A função selecionada é invocada, sua resposta é enviada de volta ao LLM, que usa as informações para responder à solicitação do usuário.
Para que os desenvolvedores implementem a chamada de função para agentes, você precisará de:
1. Um modelo LLM que suporte chamadas de função
2. Um esquema contendo descrições das funções
3. O código para cada função descrita
Vamos usar o exemplo de obter a hora atual em uma cidade para ilustrar:
- **Inicializar um LLM que suporte chamadas de função:**
Nem todos os modelos suportam chamadas de função, então é importante verificar se o LLM que você está usando suporta. [Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/how-to/function-calling) suporta chamadas de função. Podemos começar iniciando o cliente Azure OpenAI.
```python
# Initialize the Azure OpenAI client
client = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2024-05-01-preview"
)
```
- **Criar um Esquema de Função:**
Em seguida, definiremos um esquema JSON que contém o nome da função, uma descrição do que a função faz, e os nomes e descrições dos parâmetros da função. Depois, passaremos esse esquema ao cliente criado acima, juntamente com a solicitação do usuário para encontrar a hora em São Francisco. O que é importante notar é que uma **chamada de ferramenta** é o que é retornado, **não** a resposta final à pergunta. Como mencionado anteriormente, o LLM retorna o nome da função que selecionou para a tarefa e os argumentos que serão passados a ela.
```python
# Function description for the model to read
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Get the current time in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
},
"required": ["location"],
},
}
}
]
```
```python
# Initial user message
messages = [{"role": "user", "content": "What's the current time in San Francisco"}]
# First API call: Ask the model to use the function
response = client.chat.completions.create(
model=deployment_name,
messages=messages,
tools=tools,
tool_choice="auto",
)
# Process the model's response
response_message = response.choices[0].message
messages.append(response_message)
print("Model's response:")
print(response_message)
```
```bash
Model's response:
ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_pOsKdUlqvdyttYB67MOj434b', function=Function(arguments='{"location":"San Francisco"}', name='get_current_time'), type='function')])
```
- **O código da função necessário para realizar a tarefa:**
Agora que o LLM escolheu qual função precisa ser executada, o código que realiza a tarefa precisa ser implementado e executado. Podemos implementar o código para obter a hora atual em Python. Também precisaremos escrever o código para extrair o nome e os argumentos da `response_message` para obter o resultado final.
```python
def get_current_time(location):
"""Get the current time for a given location"""
print(f"get_current_time called with location: {location}")
location_lower = location.lower()
for key, timezone in TIMEZONE_DATA.items():
if key in location_lower:
print(f"Timezone found for {key}")
current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p")
return json.dumps({
"location": location,
"current_time": current_time
})
print(f"No timezone data found for {location_lower}")
return json.dumps({"location": location, "current_time": "unknown"})
```
```python
# Handle function calls
if response_message.tool_calls:
for tool_call in response_message.tool_calls:
if tool_call.function.name == "get_current_time":
function_args = json.loads(tool_call.function.arguments)
time_response = get_current_time(
location=function_args.get("location")
)
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": "get_current_time",
"content": time_response,
})
else:
print("No tool calls were made by the model.")
# Second API call: Get the final response from the model
final_response = client.chat.completions.create(
model=deployment_name,
messages=messages,
)
return final_response.choices[0].message.content
```
```bash
get_current_time called with location: San Francisco
Timezone found for san francisco
The current time in San Francisco is 09:24 AM.
```
A chamada de função está no coração de grande parte, se não de toda, a concepção de uso de ferramentas por agentes. No entanto, implementá-la do zero pode ser desafiador. Como aprendemos na [Lição 2](../../../02-explore-agentic-frameworks), frameworks agentivos nos fornecem blocos de construção pré-configurados para implementar o uso de ferramentas.
### Exemplos de Uso de Ferramentas com Frameworks Agentivos
- ### **[Semantic Kernel](https://learn.microsoft.com/azure/ai-services/agents/overview)**
O Semantic Kernel é um framework de IA de código aberto para desenvolvedores que trabalham com Modelos de Linguagem de Grande Escala (LLMs) em .NET, Python e Java. Ele simplifica o processo de uso de chamadas de função, descrevendo automaticamente suas funções e seus parâmetros para o modelo por meio de um processo chamado [serialização](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions). Ele também gerencia a comunicação entre o modelo e seu código. Outra vantagem de usar um framework agentivo como o Semantic Kernel é que ele permite acessar ferramentas pré-configuradas, como [Busca de Arquivos](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step4_assistant_tool_file_search.py) e [Interpretador de Código](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py).
O diagrama a seguir ilustra o processo de chamadas de função com o Semantic Kernel:

No Semantic Kernel, funções/ferramentas são chamadas de [Plugins](https://learn.microsoft.com/semantic-kernel/concepts/plugins/?pivots=programming-language-python). Podemos converter o `get_current_time` function we saw earlier into a plugin by turning it into a class with the function in it. We can also import the `kernel_function` decorator, que recebe a descrição da função. Quando você cria um kernel com o GetCurrentTimePlugin, o kernel automaticamente serializa a função e seus parâmetros, criando o esquema a ser enviado ao LLM no processo.
```python
from semantic_kernel.functions import kernel_function
class GetCurrentTimePlugin:
async def __init__(self, location):
self.location = location
@kernel_function(
description="Get the current time for a given location"
)
def get_current_time(location: str = ""):
...
```
```python
from semantic_kernel import Kernel
# Create the kernel
kernel = Kernel()
# Create the plugin
get_current_time_plugin = GetCurrentTimePlugin(location)
# Add the plugin to the kernel
kernel.add_plugin(get_current_time_plugin)
```
- ### **[Azure AI Agent Service](https://learn.microsoft.com/azure/ai-services/agents/overview)**
O Azure AI Agent Service é um framework agentivo mais recente, projetado para capacitar desenvolvedores a criar, implantar e escalar agentes de IA de alta qualidade e extensíveis de forma segura, sem a necessidade de gerenciar recursos de computação e armazenamento subjacentes. Ele é particularmente útil para aplicações empresariais, pois é um serviço totalmente gerenciado com segurança de nível corporativo.
Quando comparado ao desenvolvimento diretamente com a API LLM, o Azure AI Agent Service oferece algumas vantagens, incluindo:
- Chamadas de ferramenta automáticas – não é necessário analisar uma chamada de ferramenta, invocar a ferramenta e lidar com a resposta; tudo isso agora é feito no lado do servidor.
- Gerenciamento seguro de dados – em vez de gerenciar seu próprio estado de conversação, você pode contar com threads para armazenar todas as informações necessárias.
- Ferramentas prontas para uso – Ferramentas que você pode usar para interagir com suas fontes de dados, como Bing, Azure AI Search e Azure Functions.
As ferramentas disponíveis no Azure AI Agent Service podem ser divididas em duas categorias:
1. Ferramentas de Conhecimento:
- [Grounding com Bing Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/bing-grounding?tabs=python&pivots=overview)
- [Busca de Arquivos](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/file-search?tabs=python&pivots=overview)
- [Azure AI Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-ai-search?tabs=azurecli%2Cpython&pivots=overview-azure-ai-search)
2. Ferramentas de Ação:
- [Chamada de Função](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/function-calling?tabs=python&pivots=overview)
- [Interpretador de Código](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/code-interpreter?tabs=python&pivots=overview)
- [Ferramentas definidas pelo OpenAI](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/openapi-spec?tabs=python&pivots=overview)
- [Azure Functions](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-functions?pivots=overview)
O Agent Service nos permite usar essas ferramentas juntas como um `toolset`. It also utilizes `threads` which keep track of the history of messages from a particular conversation.
Imagine you are a sales agent at a company called Contoso. You want to develop a conversational agent that can answer questions about your sales data.
The image below illustrates how you could use Azure AI Agent Service to analyze your sales data:

To use any of these tools with the service we can create a client and define a tool or toolset. To implement this practically we can use the Python code below. The LLM will be able to look at the toolset and decide whether to use the user created function, `fetch_sales_data_using_sqlite_query`, ou o Interpretador de Código pré-configurado dependendo da solicitação do usuário.
```python
import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from fecth_sales_data_functions import fetch_sales_data_using_sqlite_query # fetch_sales_data_using_sqlite_query function which can be found in a fecth_sales_data_functions.py file.
from azure.ai.projects.models import ToolSet, FunctionTool, CodeInterpreterTool
project_client = AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(),
conn_str=os.environ["PROJECT_CONNECTION_STRING"],
)
# Initialize function calling agent with the fetch_sales_data_using_sqlite_query function and adding it to the toolset
fetch_data_function = FunctionTool(fetch_sales_data_using_sqlite_query)
toolset = ToolSet()
toolset.add(fetch_data_function)
# Initialize Code Interpreter tool and adding it to the toolset.
code_interpreter = code_interpreter = CodeInterpreterTool()
toolset = ToolSet()
toolset.add(code_interpreter)
agent = project_client.agents.create_agent(
model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent",
toolset=toolset
)
```
## Quais são as considerações especiais ao usar o Padrão de Design para Uso de Ferramentas para criar agentes de IA confiáveis?
Uma preocupação comum com SQL gerado dinamicamente por LLMs é a segurança, particularmente o risco de injeção de SQL ou ações maliciosas, como excluir ou alterar o banco de dados. Embora essas preocupações sejam válidas, elas podem ser mitigadas de forma eficaz configurando corretamente as permissões de acesso ao banco de dados. Para a maioria dos bancos de dados, isso envolve configurá-los como somente leitura. Para serviços de banco de dados como PostgreSQL ou Azure SQL, o aplicativo deve receber uma função de somente leitura (SELECT).
Executar o aplicativo em um ambiente seguro aumenta ainda mais a proteção. Em cenários empresariais, os dados geralmente são extraídos e transformados de sistemas operacionais para um banco de dados somente leitura ou data warehouse com um esquema amigável ao usuário. Essa abordagem garante que os dados sejam seguros, otimizados para desempenho e acessibilidade, e que o aplicativo tenha acesso restrito e somente leitura.
## Recursos Adicionais
- [Workshop do Azure AI Agents Service](https://microsoft.github.io/build-your-first-agent-with-azure-ai-agent-service-workshop/)
- [Workshop Multi-Agente do Contoso Creative Writer](https://github.com/Azure-Samples/contoso-creative-writer/tree/main/docs/workshop)
- [Tutorial de Chamadas de Função do Semantic Kernel](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions)
- [Interpretador de Código do Semantic Kernel](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py)
- [Ferramentas Autogen](https://microsoft.github.io/autogen/dev/user-guide/core-user-guide/components/tools.html)
```
**Aviso Legal**:
Este documento foi traduzido usando serviços de tradução baseados em IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte autoritativa. Para informações críticas, recomenda-se a tradução profissional feita por humanos. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/04-tool-use/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/04-tool-use/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 19246
} |
# Agentic RAG
Esta lição oferece uma visão abrangente do Agentic Retrieval-Augmented Generation (Agentic RAG), um paradigma emergente de IA onde grandes modelos de linguagem (LLMs) planejam autonomamente seus próximos passos enquanto buscam informações de fontes externas. Diferente dos padrões estáticos de "recuperar e depois ler", o Agentic RAG envolve chamadas iterativas ao LLM, intercaladas com chamadas de ferramentas ou funções e saídas estruturadas. O sistema avalia os resultados, refina consultas, invoca ferramentas adicionais se necessário e continua esse ciclo até alcançar uma solução satisfatória.
## Introdução
Esta lição abordará:
- **Entender o Agentic RAG:** Conheça o paradigma emergente em IA onde grandes modelos de linguagem (LLMs) planejam autonomamente seus próximos passos enquanto buscam informações de fontes externas.
- **Compreender o Estilo Iterativo Maker-Checker:** Entenda o ciclo de chamadas iterativas ao LLM, intercaladas com chamadas de ferramentas ou funções e saídas estruturadas, projetado para melhorar a precisão e lidar com consultas malformadas.
- **Explorar Aplicações Práticas:** Identifique cenários onde o Agentic RAG se destaca, como ambientes onde a precisão é prioritária, interações complexas com bancos de dados e fluxos de trabalho prolongados.
## Objetivos de Aprendizado
Após concluir esta lição, você será capaz de:
- **Compreender o Agentic RAG:** Conhecer o paradigma emergente em IA onde grandes modelos de linguagem (LLMs) planejam autonomamente seus próximos passos enquanto buscam informações de fontes externas.
- **Estilo Iterativo Maker-Checker:** Assimilar o conceito de um ciclo de chamadas iterativas ao LLM, intercaladas com chamadas de ferramentas ou funções e saídas estruturadas, projetado para melhorar a precisão e lidar com consultas malformadas.
- **Assumir o Processo de Raciocínio:** Entender a capacidade do sistema de assumir seu processo de raciocínio, tomando decisões sobre como abordar problemas sem depender de caminhos predefinidos.
- **Fluxo de Trabalho:** Compreender como um modelo agentic decide independentemente recuperar relatórios de tendências de mercado, identificar dados de concorrentes, correlacionar métricas internas de vendas, sintetizar conclusões e avaliar a estratégia.
- **Loops Iterativos, Integração de Ferramentas e Memória:** Aprender sobre a dependência do sistema em um padrão de interação em loop, mantendo estado e memória entre etapas para evitar loops repetitivos e tomar decisões informadas.
- **Lidar com Modos de Falha e Auto-Correção:** Explorar os mecanismos robustos de auto-correção do sistema, incluindo iteração e reconsultas, uso de ferramentas de diagnóstico e recurso à supervisão humana.
- **Limites da Agência:** Entender as limitações do Agentic RAG, focando na autonomia específica do domínio, dependência de infraestrutura e respeito a limites de segurança.
- **Casos de Uso Práticos e Valor:** Identificar cenários onde o Agentic RAG se destaca, como ambientes de alta precisão, interações complexas com bancos de dados e fluxos de trabalho prolongados.
- **Governança, Transparência e Confiança:** Aprender sobre a importância da governança e transparência, incluindo raciocínio explicável, controle de vieses e supervisão humana.
## O que é Agentic RAG?
Agentic Retrieval-Augmented Generation (Agentic RAG) é um paradigma emergente de IA onde grandes modelos de linguagem (LLMs) planejam autonomamente seus próximos passos enquanto buscam informações de fontes externas. Diferente dos padrões estáticos de "recuperar e depois ler", o Agentic RAG envolve chamadas iterativas ao LLM, intercaladas com chamadas de ferramentas ou funções e saídas estruturadas. O sistema avalia resultados, refina consultas, invoca ferramentas adicionais se necessário e continua esse ciclo até alcançar uma solução satisfatória. Este estilo iterativo “maker-checker” melhora a precisão, lida com consultas malformadas e garante resultados de alta qualidade.
O sistema assume ativamente seu processo de raciocínio, reescrevendo consultas falhas, escolhendo diferentes métodos de recuperação e integrando várias ferramentas—como busca vetorial no Azure AI Search, bancos de dados SQL ou APIs personalizadas—antes de finalizar sua resposta. A qualidade distintiva de um sistema agentic é sua capacidade de assumir o processo de raciocínio. Implementações tradicionais de RAG dependem de caminhos predefinidos, mas um sistema agentic determina autonomamente a sequência de passos com base na qualidade da informação encontrada.
## Definindo Agentic Retrieval-Augmented Generation (Agentic RAG)
Agentic Retrieval-Augmented Generation (Agentic RAG) é um paradigma emergente no desenvolvimento de IA onde LLMs não apenas buscam informações de fontes externas de dados, mas também planejam autonomamente seus próximos passos. Diferente dos padrões estáticos de "recuperar e depois ler" ou sequências de prompts cuidadosamente roteirizadas, o Agentic RAG envolve um ciclo de chamadas iterativas ao LLM, intercaladas com chamadas de ferramentas ou funções e saídas estruturadas. A cada etapa, o sistema avalia os resultados obtidos, decide se deve refinar suas consultas, invoca ferramentas adicionais se necessário e continua esse ciclo até alcançar uma solução satisfatória.
Este estilo iterativo “maker-checker” foi projetado para melhorar a precisão, lidar com consultas malformadas para bancos de dados estruturados (ex.: NL2SQL) e garantir resultados equilibrados e de alta qualidade. Em vez de depender exclusivamente de cadeias de prompts cuidadosamente elaboradas, o sistema assume ativamente seu processo de raciocínio. Ele pode reescrever consultas que falham, escolher diferentes métodos de recuperação e integrar várias ferramentas—como busca vetorial no Azure AI Search, bancos de dados SQL ou APIs personalizadas—antes de finalizar sua resposta. Isso elimina a necessidade de estruturas de orquestração excessivamente complexas. Em vez disso, um loop relativamente simples de “chamada LLM → uso de ferramenta → chamada LLM → …” pode produzir saídas sofisticadas e bem fundamentadas.

## Assumindo o Processo de Raciocínio
A qualidade distintiva que torna um sistema “agentic” é sua capacidade de assumir seu processo de raciocínio. Implementações tradicionais de RAG frequentemente dependem de humanos para predefinir um caminho para o modelo: uma cadeia de raciocínio que descreve o que recuperar e quando. Mas quando um sistema é verdadeiramente agentic, ele decide internamente como abordar o problema. Não está apenas executando um script; está determinando autonomamente a sequência de passos com base na qualidade da informação que encontra.
Por exemplo, se solicitado a criar uma estratégia de lançamento de produto, ele não depende apenas de um prompt que descreva todo o fluxo de trabalho de pesquisa e tomada de decisão. Em vez disso, o modelo agentic decide independentemente:
1. Recuperar relatórios de tendências de mercado atuais usando Bing Web Grounding.
2. Identificar dados relevantes de concorrentes usando Azure AI Search.
3. Correlacionar métricas históricas internas de vendas usando Azure SQL Database.
4. Sintetizar as descobertas em uma estratégia coesa orquestrada via Azure OpenAI Service.
5. Avaliar a estratégia em busca de lacunas ou inconsistências, promovendo outra rodada de recuperação se necessário.
Todas essas etapas—refinar consultas, escolher fontes, iterar até “ficar satisfeito” com a resposta—são decididas pelo modelo, não roteirizadas previamente por um humano.
## Loops Iterativos, Integração de Ferramentas e Memória

Um sistema agentic depende de um padrão de interação em loop:
- **Chamada Inicial:** O objetivo do usuário (também conhecido como prompt do usuário) é apresentado ao LLM.
- **Invocação de Ferramenta:** Se o modelo identificar informações ausentes ou instruções ambíguas, ele seleciona uma ferramenta ou método de recuperação—como uma consulta a um banco de dados vetorial (ex.: Azure AI Search Hybrid search sobre dados privados) ou uma chamada SQL estruturada—para obter mais contexto.
- **Avaliação e Refinamento:** Após revisar os dados retornados, o modelo decide se a informação é suficiente. Caso contrário, refina a consulta, tenta uma ferramenta diferente ou ajusta sua abordagem.
- **Repetir Até Satisfação:** Este ciclo continua até que o modelo determine que tem clareza e evidências suficientes para entregar uma resposta final bem fundamentada.
- **Memória e Estado:** Como o sistema mantém estado e memória entre etapas, ele pode lembrar tentativas anteriores e seus resultados, evitando loops repetitivos e tomando decisões mais informadas à medida que avança.
Com o tempo, isso cria um senso de entendimento evolutivo, permitindo que o modelo navegue por tarefas complexas e em várias etapas sem exigir que um humano intervenha constantemente ou reformule o prompt.
## Lidando com Modos de Falha e Auto-Correção
A autonomia do Agentic RAG também envolve mecanismos robustos de auto-correção. Quando o sistema encontra impasses—como recuperação de documentos irrelevantes ou consultas malformadas—ele pode:
- **Iterar e Reconsultar:** Em vez de retornar respostas de baixo valor, o modelo tenta novas estratégias de busca, reescreve consultas a bancos de dados ou examina conjuntos de dados alternativos.
- **Usar Ferramentas de Diagnóstico:** O sistema pode invocar funções adicionais projetadas para ajudá-lo a depurar seus passos de raciocínio ou confirmar a precisão dos dados recuperados. Ferramentas como Azure AI Tracing serão importantes para possibilitar observabilidade e monitoramento robustos.
- **Recorrer à Supervisão Humana:** Para cenários críticos ou falhas recorrentes, o modelo pode sinalizar incertezas e solicitar orientação humana. Uma vez que o humano forneça feedback corretivo, o modelo pode incorporar essa lição para seguir em frente.
Essa abordagem iterativa e dinâmica permite que o modelo melhore continuamente, garantindo que ele não seja apenas um sistema de tentativa única, mas sim um que aprende com seus erros durante uma sessão específica.

## Limites da Agência
Apesar de sua autonomia dentro de uma tarefa, o Agentic RAG não é equivalente à Inteligência Artificial Geral. Suas capacidades “agentic” estão confinadas às ferramentas, fontes de dados e políticas fornecidas pelos desenvolvedores humanos. Ele não pode inventar suas próprias ferramentas ou ultrapassar os limites do domínio que foram estabelecidos. Em vez disso, destaca-se ao orquestrar dinamicamente os recursos disponíveis.
Diferenças importantes em relação a formas mais avançadas de IA incluem:
1. **Autonomia Específica do Domínio:** Sistemas Agentic RAG são focados em alcançar objetivos definidos pelo usuário dentro de um domínio conhecido, empregando estratégias como reescrita de consultas ou seleção de ferramentas para melhorar os resultados.
2. **Dependência de Infraestrutura:** As capacidades do sistema dependem das ferramentas e dados integrados pelos desenvolvedores. Ele não pode ultrapassar esses limites sem intervenção humana.
3. **Respeito aos Limites:** Diretrizes éticas, regras de conformidade e políticas empresariais permanecem muito importantes. A liberdade do agente é sempre limitada por medidas de segurança e mecanismos de supervisão (esperançosamente?).
## Casos de Uso Práticos e Valor
O Agentic RAG se destaca em cenários que exigem refinamento iterativo e precisão:
1. **Ambientes de Alta Precisão:** Em verificações de conformidade, análises regulatórias ou pesquisas jurídicas, o modelo agentic pode verificar repetidamente fatos, consultar múltiplas fontes e reescrever consultas até produzir uma resposta minuciosamente validada.
2. **Interações Complexas com Bancos de Dados:** Ao lidar com dados estruturados, onde consultas frequentemente falham ou precisam de ajustes, o sistema pode refinar autonomamente suas consultas usando Azure SQL ou Microsoft Fabric OneLake, garantindo que a recuperação final esteja alinhada com a intenção do usuário.
3. **Fluxos de Trabalho Prolongados:** Sessões mais longas podem evoluir à medida que novas informações surgem. O Agentic RAG pode incorporar continuamente novos dados, ajustando estratégias conforme aprende mais sobre o problema.
## Governança, Transparência e Confiança
À medida que esses sistemas se tornam mais autônomos em seu raciocínio, a governança e a transparência são cruciais:
- **Raciocínio Explicável:** O modelo pode fornecer um registro auditável das consultas feitas, das fontes consultadas e dos passos de raciocínio seguidos para chegar à conclusão. Ferramentas como Azure AI Content Safety e Azure AI Tracing / GenAIOps podem ajudar a manter a transparência e mitigar riscos.
- **Controle de Viés e Recuperação Balanceada:** Desenvolvedores podem ajustar estratégias de recuperação para garantir que fontes de dados equilibradas e representativas sejam consideradas, auditando regularmente as saídas para detectar vieses ou padrões enviesados usando modelos personalizados para organizações avançadas de ciência de dados com Azure Machine Learning.
- **Supervisão Humana e Conformidade:** Para tarefas sensíveis, a revisão humana continua sendo essencial. O Agentic RAG não substitui o julgamento humano em decisões críticas—ele o complementa ao oferecer opções mais minuciosamente validadas.
Ter ferramentas que forneçam um registro claro das ações é essencial. Sem elas, depurar um processo em várias etapas pode ser muito difícil. Veja abaixo um exemplo da Literal AI (empresa por trás do Chainlit) para uma execução de agente:


## Conclusão
O Agentic RAG representa uma evolução natural na forma como sistemas de IA lidam com tarefas complexas e intensivas em dados. Ao adotar um padrão de interação em loop, selecionar ferramentas autonomamente e refinar consultas até alcançar um resultado de alta qualidade, o sistema vai além do simples seguimento de prompts estáticos, tornando-se um tomador de decisões mais adaptável e consciente do contexto. Embora ainda limitado por infraestruturas definidas por humanos e diretrizes éticas, essas capacidades agentic permitem interações de IA mais ricas, dinâmicas e, em última análise, mais úteis para empresas e usuários finais.
## Recursos Adicionais
- Implementar Retrieval Augmented Generation (RAG) com Azure OpenAI Service: Saiba como usar seus próprios dados com o Azure OpenAI Service. [Este módulo do Microsoft Learn oferece um guia abrangente sobre como implementar RAG](https://learn.microsoft.com/training/modules/use-own-data-azure-openai)
- Avaliação de aplicativos de IA generativa com Azure AI Foundry: Este artigo aborda a avaliação e comparação de modelos em conjuntos de dados públicos, incluindo [aplicativos de IA agentic e arquiteturas RAG](https://learn.microsoft.com/azure/ai-studio/concepts/evaluation-approach-gen-ai)
- [What is Agentic RAG | Weaviate](https://weaviate.io/blog/what-is-agentic-rag)
- [Agentic RAG: A Complete Guide to Agent-Based Retrieval Augmented Generation – News from generation RAG](https://ragaboutit.com/agentic-rag-a-complete-guide-to-agent-based-retrieval-augmented-generation/)
- [Agentic RAG: turbocharge your RAG with query reformulation and self-query! Hugging Face Open-Source AI Cookbook](https://huggingface.co/learn/cookbook/agent_rag)
- [Adding Agentic Layers to RAG](https://youtu.be/aQ4yQXeB1Ss?si=2HUqBzHoeB5tR04U)
- [The Future of Knowledge Assistants: Jerry Liu](https://www.youtube.com/watch?v=zeAyuLc_f3Q&t=244s)
- [How to Build Agentic RAG Systems](https://www.youtube.com/watch?v=AOSjiXP1jmQ)
- [Using Azure AI Foundry Agent Service to scale your AI agents](https://ignite.microsoft.com/sessions/BRK102?source=sessions)
### Artigos Acadêmicos
- [2303.17651 Self-Refine: Iterative Refinement with Self-Feedback](https://arxiv.org/abs/2303.17651)
- [2303.11366 Reflexion: Language Agents with Verbal Reinforcement Learning](https://arxiv.org/abs/2303.11366)
- [2305.11738 CRITIC: Large Language Models Can Self-Correct with Tool-Interactive Critiquing](https://arxiv.org/abs/2305.11738)
```
**Aviso Legal**:
Este documento foi traduzido utilizando serviços de tradução baseados em IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte oficial. Para informações críticas, recomenda-se uma tradução profissional feita por humanos. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/05-agentic-rag/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/05-agentic-rag/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 16975
} |
# Construindo Agentes de IA Confiáveis
## Introdução
Esta lição abordará:
- Como construir e implementar agentes de IA seguros e eficazes.
- Considerações importantes de segurança ao desenvolver agentes de IA.
- Como manter a privacidade de dados e usuários ao desenvolver agentes de IA.
## Objetivos de Aprendizagem
Após concluir esta lição, você saberá como:
- Identificar e mitigar riscos ao criar agentes de IA.
- Implementar medidas de segurança para garantir que os dados e acessos sejam gerenciados corretamente.
- Criar agentes de IA que mantenham a privacidade de dados e proporcionem uma experiência de qualidade ao usuário.
## Segurança
Vamos começar analisando como construir aplicações agentivas seguras. Segurança significa que o agente de IA atua conforme projetado. Como criadores de aplicações agentivas, temos métodos e ferramentas para maximizar a segurança:
### Construindo um Sistema de Meta Prompting
Se você já criou uma aplicação de IA usando Modelos de Linguagem de Grande Escala (LLMs), sabe da importância de projetar um prompt ou mensagem de sistema robusta. Esses prompts estabelecem as regras, instruções e diretrizes gerais para como o LLM interagirá com o usuário e os dados.
Para agentes de IA, o prompt do sistema é ainda mais importante, pois os agentes precisarão de instruções altamente específicas para realizar as tarefas que projetamos para eles.
Para criar prompts de sistema escaláveis, podemos usar um sistema de meta prompting para construir um ou mais agentes em nossa aplicação:

#### Etapa 1: Criar um Meta Prompt ou Prompt Modelo
O meta prompt será usado por um LLM para gerar os prompts de sistema para os agentes que criarmos. Projetamos isso como um modelo para que possamos criar múltiplos agentes de maneira eficiente, se necessário.
Aqui está um exemplo de um meta prompt que forneceríamos ao LLM:
```plaintext
You are an expert at creating AI agent assitants.
You will be provided a company name, role, responsibilites and other
information that you will use to provide a system prompt for.
To create the system prompt, be descriptive as possible and provide a structure that a system using an LLM can better understand the role and responsibilites of the AI assistant.
```
#### Etapa 2: Criar um Prompt Básico
A próxima etapa é criar um prompt básico para descrever o agente de IA. Você deve incluir o papel do agente, as tarefas que ele realizará e quaisquer outras responsabilidades atribuídas ao agente.
Aqui está um exemplo:
```plaintext
You are a travel agent for Contoso Travel with that is great at booking flights for customers. To help customers you can perform the following tasks: lookup available flights, book flights, ask for preferences in seating and times for flights, cancel any previously booked flights and alert customers on any delays or cancellations of flights.
```
#### Etapa 3: Fornecer o Prompt Básico ao LLM
Agora podemos otimizar este prompt fornecendo o meta prompt como o prompt de sistema e nosso prompt básico.
Isso produzirá um prompt melhor projetado para guiar nossos agentes de IA:
```markdown
**Company Name:** Contoso Travel
**Role:** Travel Agent Assistant
**Objective:**
You are an AI-powered travel agent assistant for Contoso Travel, specializing in booking flights and providing exceptional customer service. Your main goal is to assist customers in finding, booking, and managing their flights, all while ensuring that their preferences and needs are met efficiently.
**Key Responsibilities:**
1. **Flight Lookup:**
- Assist customers in searching for available flights based on their specified destination, dates, and any other relevant preferences.
- Provide a list of options, including flight times, airlines, layovers, and pricing.
2. **Flight Booking:**
- Facilitate the booking of flights for customers, ensuring that all details are correctly entered into the system.
- Confirm bookings and provide customers with their itinerary, including confirmation numbers and any other pertinent information.
3. **Customer Preference Inquiry:**
- Actively ask customers for their preferences regarding seating (e.g., aisle, window, extra legroom) and preferred times for flights (e.g., morning, afternoon, evening).
- Record these preferences for future reference and tailor suggestions accordingly.
4. **Flight Cancellation:**
- Assist customers in canceling previously booked flights if needed, following company policies and procedures.
- Notify customers of any necessary refunds or additional steps that may be required for cancellations.
5. **Flight Monitoring:**
- Monitor the status of booked flights and alert customers in real-time about any delays, cancellations, or changes to their flight schedule.
- Provide updates through preferred communication channels (e.g., email, SMS) as needed.
**Tone and Style:**
- Maintain a friendly, professional, and approachable demeanor in all interactions with customers.
- Ensure that all communication is clear, informative, and tailored to the customer's specific needs and inquiries.
**User Interaction Instructions:**
- Respond to customer queries promptly and accurately.
- Use a conversational style while ensuring professionalism.
- Prioritize customer satisfaction by being attentive, empathetic, and proactive in all assistance provided.
**Additional Notes:**
- Stay updated on any changes to airline policies, travel restrictions, and other relevant information that could impact flight bookings and customer experience.
- Use clear and concise language to explain options and processes, avoiding jargon where possible for better customer understanding.
This AI assistant is designed to streamline the flight booking process for customers of Contoso Travel, ensuring that all their travel needs are met efficiently and effectively.
```
#### Etapa 4: Iterar e Melhorar
O valor desse sistema de meta prompting é poder escalar a criação de prompts para múltiplos agentes de forma mais fácil, além de melhorar seus prompts ao longo do tempo. É raro que você tenha um prompt que funcione perfeitamente na primeira tentativa para todo o seu caso de uso. Ser capaz de fazer pequenos ajustes e melhorias alterando o prompt básico e executando-o no sistema permitirá que você compare e avalie os resultados.
## Entendendo as Ameaças
Para construir agentes de IA confiáveis, é importante entender e mitigar os riscos e ameaças aos seus agentes de IA. Vamos analisar algumas das diferentes ameaças aos agentes de IA e como você pode planejar e se preparar melhor para elas.

### Tarefa e Instrução
**Descrição:** Atacantes tentam alterar as instruções ou objetivos do agente de IA por meio de prompts ou manipulação de entradas.
**Mitigação:** Execute verificações de validação e filtros de entrada para detectar prompts potencialmente perigosos antes que sejam processados pelo agente de IA. Como esses ataques geralmente requerem interação frequente com o agente, limitar o número de interações em uma conversa é outra maneira de prevenir esses tipos de ataques.
### Acesso a Sistemas Críticos
**Descrição:** Se um agente de IA tem acesso a sistemas e serviços que armazenam dados sensíveis, atacantes podem comprometer a comunicação entre o agente e esses serviços. Esses ataques podem ser diretos ou tentativas indiretas de obter informações sobre esses sistemas por meio do agente.
**Mitigação:** Agentes de IA devem ter acesso a sistemas apenas quando absolutamente necessário para evitar esses tipos de ataques. A comunicação entre o agente e o sistema também deve ser segura. Implementar autenticação e controle de acesso é outra maneira de proteger essas informações.
### Sobrecarga de Recursos e Serviços
**Descrição:** Agentes de IA podem acessar diferentes ferramentas e serviços para concluir tarefas. Atacantes podem usar essa habilidade para atacar esses serviços enviando um grande volume de solicitações por meio do agente de IA, o que pode resultar em falhas no sistema ou altos custos.
**Mitigação:** Implemente políticas para limitar o número de solicitações que um agente de IA pode fazer a um serviço. Limitar o número de interações e solicitações ao seu agente de IA também é uma maneira de prevenir esses tipos de ataques.
### Envenenamento da Base de Conhecimento
**Descrição:** Esse tipo de ataque não visa diretamente o agente de IA, mas sim a base de conhecimento e outros serviços que o agente utilizará. Isso pode envolver a corrupção dos dados ou informações que o agente usará para concluir uma tarefa, levando a respostas tendenciosas ou não intencionais ao usuário.
**Mitigação:** Realize verificações regulares dos dados que o agente de IA usará em seus fluxos de trabalho. Certifique-se de que o acesso a esses dados seja seguro e que apenas pessoas confiáveis possam alterá-los para evitar esse tipo de ataque.
### Erros em Cascata
**Descrição:** Agentes de IA acessam várias ferramentas e serviços para concluir tarefas. Erros causados por atacantes podem levar a falhas em outros sistemas aos quais o agente de IA está conectado, tornando o ataque mais disseminado e difícil de solucionar.
**Mitigação:** Uma maneira de evitar isso é fazer com que o agente de IA opere em um ambiente limitado, como executar tarefas em um contêiner Docker, para evitar ataques diretos ao sistema. Criar mecanismos de fallback e lógica de repetição quando certos sistemas respondem com erro é outra maneira de evitar falhas maiores no sistema.
## Humano no Ciclo
Outra maneira eficaz de construir sistemas de agentes de IA confiáveis é usar um Humano no Ciclo. Isso cria um fluxo onde os usuários podem fornecer feedback aos agentes durante a execução. Os usuários essencialmente atuam como agentes em um sistema multiagente, fornecendo aprovação ou encerrando o processo em execução.

Aqui está um trecho de código usando AutoGen para mostrar como esse conceito é implementado:
```python
# Create the agents.
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
assistant = AssistantAgent("assistant", model_client=model_client)
user_proxy = UserProxyAgent("user_proxy", input_func=input) # Use input() to get user input from console.
# Create the termination condition which will end the conversation when the user says "APPROVE".
termination = TextMentionTermination("APPROVE")
# Create the team.
team = RoundRobinGroupChat([assistant, user_proxy], termination_condition=termination)
# Run the conversation and stream to the console.
stream = team.run_stream(task="Write a 4-line poem about the ocean.")
# Use asyncio.run(...) when running in a script.
await Console(stream)
```
**Aviso Legal**:
Este documento foi traduzido usando serviços de tradução automática baseados em IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte oficial. Para informações críticas, recomenda-se a tradução humana profissional. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/06-building-trustworthy-agents/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/06-building-trustworthy-agents/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 11662
} |
# Planejamento de Design
## Introdução
Esta lição abordará:
* Definir um objetivo geral claro e dividir uma tarefa complexa em tarefas gerenciáveis.
* Aproveitar saídas estruturadas para respostas mais confiáveis e legíveis por máquinas.
* Aplicar uma abordagem orientada a eventos para lidar com tarefas dinâmicas e entradas inesperadas.
## Objetivos de Aprendizagem
Após concluir esta lição, você terá um entendimento sobre:
* Identificar e estabelecer um objetivo geral para um agente de IA, garantindo que ele saiba claramente o que precisa ser alcançado.
* Dividir uma tarefa complexa em subtarefas gerenciáveis e organizá-las em uma sequência lógica.
* Equipar agentes com as ferramentas certas (por exemplo, ferramentas de busca ou de análise de dados), decidir quando e como usá-las e lidar com situações inesperadas que surgirem.
* Avaliar os resultados das subtarefas, medir o desempenho e iterar nas ações para melhorar o resultado final.
## Definindo o Objetivo Geral e Dividindo uma Tarefa

A maioria das tarefas do mundo real é muito complexa para ser resolvida em um único passo. Um agente de IA precisa de um objetivo conciso para guiar seu planejamento e ações. Por exemplo, considere o objetivo:
"Gerar um roteiro de viagem de 3 dias."
Embora seja simples de enunciar, ainda precisa de refinamento. Quanto mais claro for o objetivo, melhor o agente (e quaisquer colaboradores humanos) poderá se concentrar em alcançar o resultado certo, como criar um roteiro abrangente com opções de voos, recomendações de hotéis e sugestões de atividades.
### Decomposição de Tarefas
Tarefas grandes ou complexas tornam-se mais gerenciáveis quando divididas em subtarefas menores e orientadas a objetivos.
No exemplo do roteiro de viagem, você poderia decompor o objetivo em:
* Reserva de Voos
* Reserva de Hotéis
* Aluguel de Carro
* Personalização
Cada subtarefa pode ser abordada por agentes ou processos dedicados. Um agente pode se especializar em buscar as melhores ofertas de voos, outro pode focar nas reservas de hotéis, e assim por diante. Um agente coordenador ou "downstream" pode então compilar esses resultados em um roteiro coeso para o usuário final.
Essa abordagem modular também permite melhorias incrementais. Por exemplo, você poderia adicionar agentes especializados em Recomendações de Restaurantes ou Sugestões de Atividades Locais, refinando o roteiro ao longo do tempo.
### Saída Estruturada
Modelos de Linguagem Extensa (LLMs) podem gerar saídas estruturadas (por exemplo, JSON) que são mais fáceis de serem interpretadas e processadas por agentes ou serviços subsequentes. Isso é especialmente útil em um contexto multiagente, onde podemos executar essas tarefas após receber a saída do planejamento. Consulte este [blogpost](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/cookbook/structured-output-agent.html) para uma visão geral rápida.
Abaixo está um exemplo de trecho de código Python que demonstra um agente de planejamento simples decompondo um objetivo em subtarefas e gerando um plano estruturado:
### Agente de Planejamento com Orquestração Multiagente
Neste exemplo, um Agente de Roteamento Semântico recebe uma solicitação do usuário (por exemplo, "Eu preciso de um plano de hotel para minha viagem.").
O planejador então:
* Recebe o Plano de Hotel: O planejador recebe a mensagem do usuário e, com base em um prompt do sistema (incluindo detalhes dos agentes disponíveis), gera um plano de viagem estruturado.
* Lista os Agentes e Suas Ferramentas: O registro de agentes mantém uma lista de agentes (por exemplo, para voos, hotéis, aluguel de carros e atividades) juntamente com as funções ou ferramentas que eles oferecem.
* Encaminha o Plano para os Agentes Respectivos: Dependendo do número de subtarefas, o planejador envia a mensagem diretamente para um agente dedicado (para cenários de tarefa única) ou coordena via um gerenciador de chat em grupo para colaboração multiagente.
* Resume o Resultado: Finalmente, o planejador resume o plano gerado para maior clareza.
Abaixo está o exemplo de código Python ilustrando essas etapas:
```python
from pydantic import BaseModel
from enum import Enum
from typing import List, Optional, Union
class AgentEnum(str, Enum):
FlightBooking = "flight_booking"
HotelBooking = "hotel_booking"
CarRental = "car_rental"
ActivitiesBooking = "activities_booking"
DestinationInfo = "destination_info"
DefaultAgent = "default_agent"
GroupChatManager = "group_chat_manager"
# Travel SubTask Model
class TravelSubTask(BaseModel):
task_details: str
assigned_agent: AgentEnum # we want to assign the task to the agent
class TravelPlan(BaseModel):
main_task: str
subtasks: List[TravelSubTask]
is_greeting: bool
import json
import os
from typing import Optional
from autogen_core.models import UserMessage, SystemMessage, AssistantMessage
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient
# Create the client with type-checked environment variables
client = AzureOpenAIChatCompletionClient(
azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
)
from pprint import pprint
# Define the user message
messages = [
SystemMessage(content="""You are an planner agent.
Your job is to decide which agents to run based on the user's request.
Below are the available agents specialised in different tasks:
- FlightBooking: For booking flights and providing flight information
- HotelBooking: For booking hotels and providing hotel information
- CarRental: For booking cars and providing car rental information
- ActivitiesBooking: For booking activities and providing activity information
- DestinationInfo: For providing information about destinations
- DefaultAgent: For handling general requests""", source="system"),
UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melbourne", source="user"),
]
response = await client.create(messages=messages, extra_create_args={"response_format": TravelPlan})
# Ensure the response content is a valid JSON string before loading it
response_content: Optional[str] = response.content if isinstance(response.content, str) else None
if response_content is None:
raise ValueError("Response content is not a valid JSON string")
# Print the response content after loading it as JSON
pprint(json.loads(response_content))
```
Abaixo está a saída do código acima, e você pode usar essa saída estruturada para encaminhar para `assigned_agent` e resumir o plano de viagem para o usuário final:
```json
{
"is_greeting": "False",
"main_task": "Plan a family trip from Singapore to Melbourne.",
"subtasks": [
{
"assigned_agent": "flight_booking",
"task_details": "Book round-trip flights from Singapore to Melbourne."
},
{
"assigned_agent": "hotel_booking",
"task_details": "Find family-friendly hotels in Melbourne."
},
{
"assigned_agent": "car_rental",
"task_details": "Arrange a car rental suitable for a family of four in Melbourne."
},
{
"assigned_agent": "activities_booking",
"task_details": "List family-friendly activities in Melbourne."
},
{
"assigned_agent": "destination_info",
"task_details": "Provide information about Melbourne as a travel destination."
}
]
}
```
Um notebook de exemplo com o código acima está disponível [aqui](../../../07-planning-design/code_samples/07-autogen.ipynb).
### Planejamento Iterativo
Algumas tarefas requerem um processo de ida e volta ou replanejamento, onde o resultado de uma subtarefa influencia a próxima. Por exemplo, se o agente encontrar um formato de dados inesperado ao reservar voos, ele pode precisar adaptar sua estratégia antes de prosseguir com as reservas de hotéis.
Além disso, o feedback do usuário (por exemplo, um humano decidindo que prefere um voo mais cedo) pode desencadear um replanejamento parcial. Essa abordagem dinâmica e iterativa garante que a solução final esteja alinhada com as restrições do mundo real e com as preferências em evolução do usuário.
Exemplo de código:
```python
from autogen_core.models import UserMessage, SystemMessage, AssistantMessage
#.. same as previous code and pass on the user history, current plan
messages = [
SystemMessage(content="""You are a planner agent to optimize the
Your job is to decide which agents to run based on the user's request.
Below are the available agents specialised in different tasks:
- FlightBooking: For booking flights and providing flight information
- HotelBooking: For booking hotels and providing hotel information
- CarRental: For booking cars and providing car rental information
- ActivitiesBooking: For booking activities and providing activity information
- DestinationInfo: For providing information about destinations
- DefaultAgent: For handling general requests""", source="system"),
UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melboune", source="user"),
AssistantMessage(content=f"Previous travel plan - {TravelPlan}", source="assistant")
]
# .. re-plan and send the tasks to respective agents
```
Para um planejamento mais abrangente, confira o [Blogpost Magnetic One](https://www.microsoft.com/research/articles/magentic-one-a-generalist-multi-agent-system-for-solving-complex-tasks) para resolver tarefas complexas.
## Resumo
Neste artigo, analisamos um exemplo de como criar um planejador que pode selecionar dinamicamente os agentes disponíveis definidos. A saída do Planejador decompõe as tarefas e atribui os agentes para que elas sejam executadas. Assume-se que os agentes têm acesso às funções/ferramentas necessárias para realizar a tarefa. Além dos agentes, você pode incluir outros padrões, como reflexão, sumarização e chat round robin, para personalizar ainda mais.
## Recursos Adicionais
* Usar modelos de raciocínio o1 tem se mostrado bastante avançado no planejamento de tarefas complexas - TODO: Compartilhar exemplo?
* Autogen Magnetic One - Um sistema multiagente generalista para resolver tarefas complexas que alcançou resultados impressionantes em vários benchmarks desafiadores de agentes. Referência: [autogen-magentic-one](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-magentic-one). Nesta implementação, o orquestrador cria um plano específico para a tarefa e delega essas tarefas aos agentes disponíveis. Além do planejamento, o orquestrador também emprega um mecanismo de rastreamento para monitorar o progresso da tarefa e replanejar conforme necessário.
**Aviso Legal**:
Este documento foi traduzido utilizando serviços de tradução automática baseados em IA. Embora nos esforcemos para alcançar precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte oficial. Para informações críticas, recomenda-se a tradução profissional humana. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/07-planning-design/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/07-planning-design/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 11740
} |
# Padrões de Design para Multiagentes
Assim que você começar a trabalhar em um projeto que envolve múltiplos agentes, será necessário considerar o padrão de design para multiagentes. No entanto, pode não ser imediatamente claro quando mudar para um sistema multiagente e quais são as vantagens disso.
## Introdução
Nesta lição, buscamos responder às seguintes perguntas:
- Quais são os cenários onde os multiagentes são aplicáveis?
- Quais são as vantagens de usar multiagentes em vez de um único agente realizando múltiplas tarefas?
- Quais são os componentes fundamentais para implementar o padrão de design para multiagentes?
- Como podemos ter visibilidade sobre como os múltiplos agentes estão interagindo entre si?
## Objetivos de Aprendizagem
Após esta lição, você deverá ser capaz de:
- Identificar cenários onde os multiagentes são aplicáveis.
- Reconhecer as vantagens de usar multiagentes em vez de um único agente.
- Compreender os componentes fundamentais para implementar o padrão de design para multiagentes.
Qual é o panorama geral?
*Multiagentes são um padrão de design que permite que múltiplos agentes trabalhem juntos para alcançar um objetivo comum.*
Esse padrão é amplamente utilizado em diversos campos, incluindo robótica, sistemas autônomos e computação distribuída.
## Cenários Onde Multiagentes São Aplicáveis
Então, em quais cenários o uso de multiagentes é uma boa escolha? A resposta é que há muitos cenários onde empregar múltiplos agentes é benéfico, especialmente nos seguintes casos:
- **Grandes volumes de trabalho**: Tarefas extensas podem ser divididas em partes menores e atribuídas a diferentes agentes, permitindo processamento paralelo e conclusão mais rápida. Um exemplo disso é no caso de uma tarefa de processamento de dados em larga escala.
- **Tarefas complexas**: Tarefas complexas, assim como grandes volumes de trabalho, podem ser divididas em subtarefas menores e atribuídas a diferentes agentes, cada um especializado em um aspecto específico da tarefa. Um bom exemplo disso é no caso de veículos autônomos, onde diferentes agentes gerenciam navegação, detecção de obstáculos e comunicação com outros veículos.
- **Diversidade de especialização**: Diferentes agentes podem ter especializações distintas, permitindo que lidem com diferentes aspectos de uma tarefa de forma mais eficaz do que um único agente. Um bom exemplo disso é no setor de saúde, onde agentes podem gerenciar diagnósticos, planos de tratamento e monitoramento de pacientes.
## Vantagens de Usar Multiagentes em Comparação a um Único Agente
Um sistema com um único agente pode funcionar bem para tarefas simples, mas para tarefas mais complexas, usar múltiplos agentes pode oferecer várias vantagens:
- **Especialização**: Cada agente pode ser especializado para uma tarefa específica. A falta de especialização em um único agente significa que ele pode fazer de tudo, mas pode se confundir ao lidar com tarefas complexas. Ele pode, por exemplo, acabar realizando uma tarefa para a qual não é o mais adequado.
- **Escalabilidade**: É mais fácil escalar sistemas adicionando mais agentes em vez de sobrecarregar um único agente.
- **Tolerância a falhas**: Se um agente falhar, outros podem continuar funcionando, garantindo a confiabilidade do sistema.
Vamos a um exemplo: reservar uma viagem para um usuário. Um sistema com um único agente teria que lidar com todos os aspectos do processo de reserva, desde encontrar voos até reservar hotéis e carros de aluguel. Para fazer isso com um único agente, ele precisaria de ferramentas para lidar com todas essas tarefas. Isso poderia levar a um sistema complexo e monolítico, difícil de manter e escalar. Um sistema multiagente, por outro lado, poderia ter diferentes agentes especializados em encontrar voos, reservar hotéis e carros de aluguel. Isso tornaria o sistema mais modular, fácil de manter e escalável.
Compare isso a uma agência de viagens administrada como um pequeno negócio familiar versus uma agência operada como uma franquia. O negócio familiar teria um único agente lidando com todos os aspectos do processo de reserva, enquanto a franquia teria diferentes agentes responsáveis por diferentes aspectos do processo.
## Componentes Fundamentais para Implementar o Padrão de Design para Multiagentes
Antes de implementar o padrão de design para multiagentes, é necessário entender os componentes que compõem esse padrão.
Vamos tornar isso mais concreto analisando novamente o exemplo de reservar uma viagem para um usuário. Nesse caso, os componentes fundamentais incluiriam:
- **Comunicação entre agentes**: Agentes responsáveis por encontrar voos, reservar hotéis e carros de aluguel precisam se comunicar e compartilhar informações sobre as preferências e restrições do usuário. É necessário decidir os protocolos e métodos para essa comunicação. Concretamente, isso significa que o agente responsável por encontrar voos precisa se comunicar com o agente de reservas de hotéis para garantir que o hotel seja reservado para as mesmas datas do voo. Isso significa que os agentes precisam compartilhar informações sobre as datas de viagem do usuário, ou seja, você precisa decidir *quais agentes compartilham informações e como fazem isso*.
- **Mecanismos de coordenação**: Os agentes precisam coordenar suas ações para garantir que as preferências e restrições do usuário sejam atendidas. Por exemplo, uma preferência do usuário pode ser ficar em um hotel próximo ao aeroporto, enquanto uma restrição pode ser que carros de aluguel só estejam disponíveis no aeroporto. Isso significa que o agente de reservas de hotéis precisa coordenar-se com o agente de aluguel de carros para atender às preferências e restrições do usuário. Isso implica decidir *como os agentes coordenam suas ações*.
- **Arquitetura dos agentes**: Os agentes precisam ter uma estrutura interna para tomar decisões e aprender com as interações com o usuário. Por exemplo, o agente responsável por encontrar voos precisa ter a capacidade interna de decidir quais voos recomendar ao usuário. Isso significa que você precisa decidir *como os agentes tomam decisões e aprendem com as interações com o usuário*. Um exemplo de como um agente pode aprender e melhorar seria o uso de um modelo de aprendizado de máquina para recomendar voos com base nas preferências anteriores do usuário.
- **Visibilidade nas interações entre agentes**: É essencial ter visibilidade sobre como os múltiplos agentes estão interagindo entre si. Isso requer ferramentas e técnicas para rastrear as atividades e interações dos agentes. Isso pode incluir ferramentas de registro e monitoramento, ferramentas de visualização e métricas de desempenho.
- **Padrões para sistemas multiagentes**: Existem diferentes padrões para implementar sistemas multiagentes, como arquiteturas centralizadas, descentralizadas e híbridas. É necessário escolher o padrão que melhor se adapta ao seu caso de uso.
- **Humano no ciclo**: Na maioria dos casos, haverá um humano no ciclo, e será necessário instruir os agentes sobre quando pedir intervenção humana. Isso pode incluir, por exemplo, um usuário solicitando um hotel ou voo específico que os agentes não recomendaram ou pedindo confirmação antes de reservar um voo ou hotel.
## Visibilidade nas Interações entre Multiagentes
É importante ter visibilidade sobre como os múltiplos agentes estão interagindo entre si. Essa visibilidade é essencial para depurar, otimizar e garantir a eficácia geral do sistema. Para isso, é necessário ter ferramentas e técnicas para rastrear as atividades e interações dos agentes. Isso pode incluir ferramentas de registro e monitoramento, ferramentas de visualização e métricas de desempenho.
Por exemplo, no caso de reservar uma viagem para um usuário, você poderia ter um painel que mostra o status de cada agente, as preferências e restrições do usuário e as interações entre os agentes. Esse painel poderia exibir as datas de viagem do usuário, os voos recomendados pelo agente de voos, os hotéis recomendados pelo agente de hotéis e os carros de aluguel recomendados pelo agente de aluguel de carros. Isso daria uma visão clara de como os agentes estão interagindo entre si e se as preferências e restrições do usuário estão sendo atendidas.
Vamos analisar cada um desses aspectos com mais detalhes:
- **Ferramentas de Registro e Monitoramento**: É importante registrar cada ação tomada por um agente. Um registro pode armazenar informações sobre o agente que realizou a ação, a ação realizada, o horário em que a ação foi realizada e o resultado da ação. Essas informações podem ser usadas para depuração, otimização e mais.
- **Ferramentas de Visualização**: Ferramentas de visualização podem ajudar a entender as interações entre os agentes de forma mais intuitiva. Por exemplo, um gráfico que mostra o fluxo de informações entre os agentes pode ajudar a identificar gargalos, ineficiências e outros problemas no sistema.
- **Métricas de Desempenho**: Métricas de desempenho ajudam a monitorar a eficácia do sistema multiagente. Por exemplo, você pode rastrear o tempo necessário para concluir uma tarefa, o número de tarefas concluídas por unidade de tempo e a precisão das recomendações feitas pelos agentes. Essas informações podem ajudar a identificar áreas de melhoria e otimizar o sistema.
## Padrões para Multiagentes
Vamos explorar alguns padrões concretos que podem ser usados para criar aplicativos multiagentes. Aqui estão alguns padrões interessantes a considerar:
### Chat em Grupo
Esse padrão é útil quando você deseja criar um aplicativo de chat em grupo onde múltiplos agentes possam se comunicar entre si. Casos típicos de uso incluem colaboração em equipe, suporte ao cliente e redes sociais.
Nesse padrão, cada agente representa um usuário no chat em grupo, e as mensagens são trocadas entre os agentes usando um protocolo de mensagens. Os agentes podem enviar mensagens ao chat em grupo, receber mensagens do chat em grupo e responder a mensagens de outros agentes.
Esse padrão pode ser implementado usando uma arquitetura centralizada, onde todas as mensagens passam por um servidor central, ou uma arquitetura descentralizada, onde as mensagens são trocadas diretamente.

### Transferência de Tarefas
Esse padrão é útil quando você deseja criar um aplicativo onde múltiplos agentes possam transferir tarefas entre si.
Casos típicos de uso incluem suporte ao cliente, gerenciamento de tarefas e automação de fluxos de trabalho.
Nesse padrão, cada agente representa uma tarefa ou etapa em um fluxo de trabalho, e os agentes podem transferir tarefas para outros agentes com base em regras predefinidas.

### Filtragem Colaborativa
Esse padrão é útil quando você deseja criar um aplicativo onde múltiplos agentes possam colaborar para fazer recomendações aos usuários.
A razão para ter múltiplos agentes colaborando é que cada agente pode ter uma especialização diferente e contribuir de maneiras distintas para o processo de recomendação.
Vamos tomar como exemplo um usuário que deseja uma recomendação sobre a melhor ação para comprar no mercado financeiro.
- **Especialista em indústria**: Um agente pode ser especialista em um setor específico.
- **Análise técnica**: Outro agente pode ser especialista em análise técnica.
- **Análise fundamentalista**: E outro agente pode ser especialista em análise fundamentalista. Colaborando, esses agentes podem fornecer uma recomendação mais abrangente ao usuário.

## Cenário: Processo de Reembolso
Considere um cenário em que um cliente está tentando obter o reembolso de um produto. Pode haver diversos agentes envolvidos nesse processo, mas vamos dividi-los entre agentes específicos para esse processo e agentes gerais que podem ser usados em outros processos.
**Agentes específicos para o processo de reembolso**:
Abaixo estão alguns agentes que poderiam estar envolvidos no processo de reembolso:
- **Agente do cliente**: Representa o cliente e é responsável por iniciar o processo de reembolso.
- **Agente do vendedor**: Representa o vendedor e é responsável por processar o reembolso.
- **Agente de pagamento**: Representa o processo de pagamento e é responsável por reembolsar o pagamento do cliente.
- **Agente de resolução**: Representa o processo de resolução e é responsável por resolver quaisquer problemas que surjam durante o processo de reembolso.
- **Agente de conformidade**: Representa o processo de conformidade e é responsável por garantir que o processo de reembolso esteja em conformidade com regulamentos e políticas.
**Agentes gerais**:
Esses agentes podem ser usados em outras partes do seu negócio.
- **Agente de envio**: Representa o processo de envio e é responsável por enviar o produto de volta ao vendedor. Esse agente pode ser usado tanto no processo de reembolso quanto no envio geral de um produto, como em uma compra.
- **Agente de feedback**: Representa o processo de feedback e é responsável por coletar feedback do cliente. O feedback pode ser coletado a qualquer momento, não apenas durante o processo de reembolso.
- **Agente de escalonamento**: Representa o processo de escalonamento e é responsável por escalar problemas para um nível superior de suporte. Esse tipo de agente pode ser usado em qualquer processo onde seja necessário escalar um problema.
- **Agente de notificações**: Representa o processo de notificações e é responsável por enviar notificações ao cliente em várias etapas do processo de reembolso.
- **Agente de análise**: Representa o processo de análise e é responsável por analisar dados relacionados ao processo de reembolso.
- **Agente de auditoria**: Representa o processo de auditoria e é responsável por auditar o processo de reembolso para garantir que ele esteja sendo conduzido corretamente.
- **Agente de relatórios**: Representa o processo de relatórios e é responsável por gerar relatórios sobre o processo de reembolso.
- **Agente de conhecimento**: Representa o processo de conhecimento e é responsável por manter uma base de conhecimento com informações relacionadas ao processo de reembolso. Esse agente pode ser útil tanto para reembolsos quanto para outras partes do seu negócio.
- **Agente de segurança**: Representa o processo de segurança e é responsável por garantir a segurança do processo de reembolso.
- **Agente de qualidade**: Representa o processo de qualidade e é responsável por garantir a qualidade do processo de reembolso.
Há uma grande variedade de agentes listados acima, tanto para o processo específico de reembolso quanto para os agentes gerais que podem ser usados em outras partes do seu negócio. Esperamos que isso lhe dê uma ideia de como decidir quais agentes usar em seu sistema multiagente.
## Tarefa
Qual seria uma boa tarefa para esta lição?
Projete um sistema multiagente para um processo de suporte ao cliente. Identifique os agentes envolvidos no processo, seus papéis e responsabilidades, e como eles interagem entre si. Considere tanto os agentes específicos para o processo de suporte ao cliente quanto os agentes gerais que podem ser usados em outras partes do seu negócio.
> Pense um pouco antes de ler a solução abaixo; você pode precisar de mais agentes do que imagina.
> TIP: Pense nas diferentes etapas do processo de suporte ao cliente e também considere os agentes necessários para qualquer sistema.
## Solução
[Solução](./solution/solution.md)
## Verificações de Conhecimento
Pergunta: Quando você deve considerar o uso de multiagentes?
- [] A1: Quando você tem uma carga de trabalho pequena e uma tarefa simples.
- [] A2: Quando você tem uma grande carga de trabalho.
- [] A3: Quando você tem uma tarefa simples.
[Quiz de solução](./solution/solution-quiz.md)
## Resumo
Nesta lição, exploramos o padrão de design para multiagentes, incluindo os cenários onde os multiagentes são aplicáveis, as vantagens de usar multiagentes em vez de um único agente, os componentes fundamentais para implementar o padrão de design para multiagentes e como ter visibilidade sobre como os múltiplos agentes estão interagindo entre si.
## Recursos adicionais
- [Padrões de design Autogen](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/design-patterns/intro.html)
- [Padrões de design agentic](https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/)
```
**Aviso Legal**:
Este documento foi traduzido usando serviços de tradução automática baseados em IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte autoritária. Para informações críticas, recomenda-se a tradução profissional feita por humanos. Não nos responsabilizamos por mal-entendidos ou interpretações incorretas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/08-multi-agent/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/08-multi-agent/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 17277
} |
# Metacognição em Agentes de IA
## Introdução
Bem-vindo à lição sobre metacognição em agentes de IA! Este capítulo foi projetado para iniciantes curiosos sobre como agentes de IA podem pensar sobre seus próprios processos de pensamento. Ao final desta lição, você entenderá os conceitos-chave e estará equipado com exemplos práticos para aplicar metacognição no design de agentes de IA.
## Objetivos de Aprendizagem
Após completar esta lição, você será capaz de:
1. Compreender as implicações de loops de raciocínio em definições de agentes.
2. Usar técnicas de planejamento e avaliação para ajudar agentes a se autocorrigirem.
3. Criar seus próprios agentes capazes de manipular código para realizar tarefas.
## Introdução à Metacognição
Metacognição refere-se aos processos cognitivos de ordem superior que envolvem pensar sobre o próprio pensamento. Para agentes de IA, isso significa ser capaz de avaliar e ajustar suas ações com base na autoconsciência e em experiências passadas.
### O que é Metacognição?
Metacognição, ou "pensar sobre o pensamento", é um processo cognitivo de ordem superior que envolve autoconsciência e autorregulação dos próprios processos cognitivos. No domínio da IA, a metacognição capacita agentes a avaliar e adaptar suas estratégias e ações, levando a capacidades aprimoradas de resolução de problemas e tomada de decisão. Ao entender a metacognição, você pode projetar agentes de IA que sejam não apenas mais inteligentes, mas também mais adaptáveis e eficientes.
### Importância da Metacognição em Agentes de IA
A metacognição desempenha um papel crucial no design de agentes de IA por várias razões:

- **Autorreflexão**: Agentes podem avaliar seu próprio desempenho e identificar áreas para melhoria.
- **Adaptabilidade**: Agentes podem modificar suas estratégias com base em experiências passadas e ambientes em mudança.
- **Correção de Erros**: Agentes podem detectar e corrigir erros de forma autônoma, levando a resultados mais precisos.
- **Gestão de Recursos**: Agentes podem otimizar o uso de recursos, como tempo e poder computacional, planejando e avaliando suas ações.
## Componentes de um Agente de IA
Antes de mergulhar nos processos metacognitivos, é essencial entender os componentes básicos de um agente de IA. Um agente de IA normalmente consiste em:
- **Persona**: A personalidade e características do agente, que definem como ele interage com os usuários.
- **Ferramentas**: As capacidades e funções que o agente pode executar.
- **Habilidades**: O conhecimento e a expertise que o agente possui.
Esses componentes trabalham juntos para criar uma "unidade de expertise" que pode realizar tarefas específicas.
**Exemplo**: Considere um agente de viagens, que não apenas planeja suas férias, mas também ajusta seu percurso com base em dados em tempo real e experiências de jornadas de clientes anteriores.
### Exemplo: Metacognição em um Serviço de Agente de Viagens
Imagine que você está projetando um serviço de agente de viagens movido por IA. Este agente, "Agente de Viagens", auxilia os usuários no planejamento de suas férias. Para incorporar metacognição, o Agente de Viagens precisa avaliar e ajustar suas ações com base na autoconsciência e em experiências passadas. Veja como a metacognição pode desempenhar um papel:
#### Tarefa Atual
A tarefa atual é ajudar um usuário a planejar uma viagem para Paris.
#### Etapas para Completar a Tarefa
1. **Coletar Preferências do Usuário**: Perguntar ao usuário sobre suas datas de viagem, orçamento, interesses (por exemplo, museus, culinária, compras) e quaisquer requisitos específicos.
2. **Recuperar Informações**: Buscar opções de voos, acomodações, atrações e restaurantes que correspondam às preferências do usuário.
3. **Gerar Recomendações**: Fornecer um itinerário personalizado com detalhes de voos, reservas de hotéis e atividades sugeridas.
4. **Ajustar com Base no Feedback**: Solicitar feedback do usuário sobre as recomendações e fazer os ajustes necessários.
#### Recursos Necessários
- Acesso a bancos de dados de reservas de voos e hotéis.
- Informações sobre atrações e restaurantes em Paris.
- Dados de feedback de usuários de interações anteriores.
#### Experiência e Autorreflexão
O Agente de Viagens usa metacognição para avaliar seu desempenho e aprender com experiências passadas. Por exemplo:
1. **Analisando Feedback do Usuário**: O Agente de Viagens revisa o feedback do usuário para determinar quais recomendações foram bem recebidas e quais não foram. Ele ajusta suas sugestões futuras de acordo.
2. **Adaptabilidade**: Se um usuário mencionou anteriormente que não gosta de lugares lotados, o Agente de Viagens evitará recomendar pontos turísticos populares durante horários de pico no futuro.
3. **Correção de Erros**: Se o Agente de Viagens cometeu um erro em uma reserva anterior, como sugerir um hotel que estava totalmente reservado, ele aprende a verificar a disponibilidade de forma mais rigorosa antes de fazer recomendações.
#### Exemplo Prático para Desenvolvedores
Aqui está um exemplo simplificado de como o código do Agente de Viagens poderia ser estruturado ao incorporar metacognição:
```python
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):
# Search for flights, hotels, and attractions based on preferences
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)
# Analyze feedback and adjust future recommendations
self.user_preferences = adjust_preferences(self.user_preferences, feedback)
# Example usage
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)
```
#### Por que a Metacognição é Importante
- **Autorreflexão**: Agentes podem analisar seu desempenho e identificar áreas para melhoria.
- **Adaptabilidade**: Agentes podem modificar estratégias com base em feedback e condições em mudança.
- **Correção de Erros**: Agentes podem detectar e corrigir erros de forma autônoma.
- **Gestão de Recursos**: Agentes podem otimizar o uso de recursos, como tempo e poder computacional.
Ao incorporar metacognição, o Agente de Viagens pode fornecer recomendações de viagem mais personalizadas e precisas, melhorando a experiência geral do usuário.
---
## 2. Planejamento em Agentes
Planejamento é um componente crítico do comportamento de agentes de IA. Envolve delinear os passos necessários para alcançar um objetivo, considerando o estado atual, recursos e possíveis obstáculos.
### Elementos do Planejamento
- **Tarefa Atual**: Definir claramente a tarefa.
- **Etapas para Completar a Tarefa**: Dividir a tarefa em etapas gerenciáveis.
- **Recursos Necessários**: Identificar os recursos necessários.
- **Experiência**: Utilizar experiências passadas para informar o planejamento.
**Exemplo**: Aqui estão os passos que o Agente de Viagens precisa seguir para ajudar um usuário a planejar sua viagem de forma eficaz:
### Etapas para o Agente de Viagens
1. **Coletar Preferências do Usuário**
- Perguntar ao usuário detalhes sobre suas datas de viagem, orçamento, interesses e quaisquer requisitos específicos.
- Exemplos: "Quando você planeja viajar?" "Qual é a sua faixa de orçamento?" "Quais atividades você gosta de fazer nas férias?"
2. **Recuperar Informações**
- Buscar opções de viagem relevantes com base nas preferências do usuário.
- **Voos**: Procurar voos disponíveis dentro do orçamento e datas preferidas do usuário.
- **Acomodações**: Encontrar hotéis ou propriedades para aluguel que correspondam às preferências do usuário em localização, preço e comodidades.
- **Atrações e Restaurantes**: Identificar atrações populares, atividades e opções de refeições que estejam alinhadas com os interesses do usuário.
3. **Gerar Recomendações**
- Compilar as informações recuperadas em um itinerário personalizado.
- Fornecer detalhes como opções de voos, reservas de hotéis e atividades sugeridas, garantindo que as recomendações sejam adaptadas às preferências do usuário.
4. **Apresentar o Itinerário ao Usuário**
- Compartilhar o itinerário proposto com o usuário para sua revisão.
- Exemplo: "Aqui está um itinerário sugerido para sua viagem a Paris. Inclui detalhes de voos, reservas de hotéis e uma lista de atividades e restaurantes recomendados. Deixe-me saber o que acha!"
5. **Coletar Feedback**
- Perguntar ao usuário sobre o itinerário proposto.
- Exemplos: "Você gostou das opções de voos?" "O hotel é adequado às suas necessidades?" "Há alguma atividade que você gostaria de adicionar ou remover?"
6. **Ajustar com Base no Feedback**
- Modificar o itinerário com base no feedback do usuário.
- Fazer as alterações necessárias nas recomendações de voos, acomodações e atividades para melhor atender às preferências do usuário.
7. **Confirmação Final**
- Apresentar o itinerário atualizado ao usuário para confirmação final.
- Exemplo: "Fiz os ajustes com base no seu feedback. Aqui está o itinerário atualizado. Tudo parece bom para você?"
8. **Reservar e Confirmar**
- Após a aprovação do usuário, proceder com a reserva de voos, acomodações e quaisquer atividades pré-planejadas.
- Enviar os detalhes de confirmação ao usuário.
9. **Fornecer Suporte Contínuo**
- Permanecer disponível para ajudar o usuário com quaisquer alterações ou solicitações adicionais antes e durante a viagem.
- Exemplo: "Se precisar de mais assistência durante sua viagem, sinta-se à vontade para entrar em contato comigo a qualquer momento!"
### Exemplo de Interação
```python
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)
# Example usage within a booing request
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)
```
```
```markdown
O Agente de Viagens formula novas consultas de pesquisa com base no feedback do usuário.
- Exemplo: ```python
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
```
- **Ferramenta**: O Agente de Viagens utiliza algoritmos para classificar e filtrar novos resultados de pesquisa, enfatizando a relevância com base no feedback do usuário.
- Exemplo: ```python
new_attractions = search_attractions(preferences)
new_itinerary = create_itinerary(flights, hotels, new_attractions)
print("Updated Itinerary:", new_itinerary)
```
- **Avaliação**: O Agente de Viagens avalia continuamente a relevância e a precisão de suas recomendações, analisando o feedback do usuário e fazendo os ajustes necessários.
- Exemplo: ```python
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)
```
#### Exemplo Prático
Aqui está um exemplo simplificado de código Python que incorpora a abordagem RAG Corretiva no Agente de Viagens:
```python
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
# Example usage
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)
```
### Carregamento de Contexto Pré-Emptivo
O Carregamento de Contexto Pré-Emptivo envolve carregar informações de contexto ou antecedentes relevantes no modelo antes de processar uma consulta. Isso significa que o modelo tem acesso a essas informações desde o início, o que pode ajudá-lo a gerar respostas mais informadas sem a necessidade de recuperar dados adicionais durante o processo.
Aqui está um exemplo simplificado de como um carregamento de contexto pré-emptivo pode ser implementado em uma aplicação de agente de viagens em Python:
```python
class TravelAgent:
def __init__(self):
# Pre-load popular destinations and their information
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):
# Fetch destination information from pre-loaded context
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}."
# Example usage
travel_agent = TravelAgent()
print(travel_agent.get_destination_info("Paris"))
print(travel_agent.get_destination_info("Tokyo"))
```
#### Explicação
1. **Inicialização (`__init__` method)**: The `TravelAgent` class pre-loads a dictionary containing information about popular destinations such as Paris, Tokyo, New York, and Sydney. This dictionary includes details like the country, currency, language, and major attractions for each destination.
2. **Retrieving Information (`get_destination_info` method)**: When a user queries about a specific destination, the `get_destination_info` method)**: Este método busca as informações relevantes no dicionário de contexto pré-carregado. Ao pré-carregar o contexto, a aplicação do agente de viagens pode responder rapidamente às consultas do usuário sem precisar recuperar essas informações de uma fonte externa em tempo real. Isso torna a aplicação mais eficiente e responsiva.
### Inicializando o Plano com um Objetivo Antes de Iterar
Inicializar um plano com um objetivo envolve começar com um objetivo claro ou resultado desejado em mente. Definindo esse objetivo desde o início, o modelo pode usá-lo como um princípio orientador ao longo do processo iterativo. Isso ajuda a garantir que cada iteração avance em direção ao resultado desejado, tornando o processo mais eficiente e focado.
Aqui está um exemplo de como você pode inicializar um plano de viagem com um objetivo antes de iterar para um agente de viagens em Python:
### Cenário
Um agente de viagens deseja planejar umas férias personalizadas para um cliente. O objetivo é criar um itinerário de viagem que maximize a satisfação do cliente com base em suas preferências e orçamento.
### Etapas
1. Defina as preferências e o orçamento do cliente.
2. Inicialize o plano inicial com base nessas preferências.
3. Itere para refinar o plano, otimizando a satisfação do cliente.
#### Código Python
```python
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']
# Example usage
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)
```
#### Explicação do Código
1. **Inicialização (`__init__` method)**: The `TravelAgent` class is initialized with a list of potential destinations, each having attributes like name, cost, and activity type.
2. **Bootstrapping the Plan (`bootstrap_plan` method)**: This method creates an initial travel plan based on the client's preferences and budget. It iterates through the list of destinations and adds them to the plan if they match the client's preferences and fit within the budget.
3. **Matching Preferences (`match_preferences` method)**: This method checks if a destination matches the client's preferences.
4. **Iterating the Plan (`iterate_plan` method)**: This method refines the initial plan by trying to replace each destination in the plan with a better match, considering the client's preferences and budget constraints.
5. **Calculating Cost (`calculate_cost` method)**: Este método calcula o custo total do plano atual, incluindo um possível novo destino.
#### Uso de Exemplo
- **Plano Inicial**: O agente de viagens cria um plano inicial com base nas preferências do cliente por pontos turísticos e um orçamento de $2000.
- **Plano Refinado**: O agente de viagens itera o plano, otimizando para as preferências e o orçamento do cliente.
Ao inicializar o plano com um objetivo claro (por exemplo, maximizar a satisfação do cliente) e iterar para refiná-lo, o agente de viagens pode criar um itinerário de viagem personalizado e otimizado para o cliente. Essa abordagem garante que o plano de viagem esteja alinhado com as preferências e o orçamento do cliente desde o início e melhore a cada iteração.
### Aproveitando LLM para Reclassificação e Pontuação
Modelos de Linguagem de Grande Escala (LLMs) podem ser usados para reclassificação e pontuação ao avaliar a relevância e a qualidade de documentos recuperados ou respostas geradas. Veja como funciona:
**Recuperação:** A etapa inicial de recuperação busca um conjunto de documentos ou respostas candidatas com base na consulta.
**Reclassificação:** O LLM avalia esses candidatos e os reclassifica com base em sua relevância e qualidade. Essa etapa garante que as informações mais relevantes e de alta qualidade sejam apresentadas primeiro.
**Pontuação:** O LLM atribui pontuações a cada candidato, refletindo sua relevância e qualidade. Isso ajuda na seleção da melhor resposta ou documento para o usuário.
Ao aproveitar os LLMs para reclassificação e pontuação, o sistema pode fornecer informações mais precisas e contextualmente relevantes, melhorando a experiência geral do usuário.
Aqui está um exemplo de como um agente de viagens pode usar um Modelo de Linguagem de Grande Escala (LLM) para reclassificar e pontuar destinos de viagem com base nas preferências do usuário em Python:
#### Cenário - Viagem com Base nas Preferências
Um agente de viagens deseja recomendar os melhores destinos de viagem para um cliente com base em suas preferências. O LLM ajudará a reclassificar e pontuar os destinos para garantir que as opções mais relevantes sejam apresentadas.
#### Etapas:
1. Coletar as preferências do usuário.
2. Recuperar uma lista de destinos de viagem potenciais.
3. Usar o LLM para reclassificar e pontuar os destinos com base nas preferências do usuário.
Aqui está como você pode atualizar o exemplo anterior para usar os Serviços Azure OpenAI:
#### Requisitos
1. Você precisa de uma assinatura do Azure.
2. Criar um recurso Azure OpenAI e obter sua chave de API.
#### Código Python de Exemplo
```python
import requests
import json
class TravelAgent:
def __init__(self, destinations):
self.destinations = destinations
def get_recommendations(self, preferences, api_key, endpoint):
# Generate a prompt for the Azure OpenAI
prompt = self.generate_prompt(preferences)
# Define headers and payload for the request
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
payload = {
"prompt": prompt,
"max_tokens": 150,
"temperature": 0.7
}
# Call the Azure OpenAI API to get the re-ranked and scored destinations
response = requests.post(endpoint, headers=headers, json=payload)
response_data = response.json()
# Extract and return the recommendations
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
# Example usage
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)
```
#### Explicação do Código - Preference Booker
1. **Inicialização**: Substitua `TravelAgent` class is initialized with a list of potential travel destinations, each having attributes like name and description.
2. **Getting Recommendations (`get_recommendations` method)**: This method generates a prompt for the Azure OpenAI service based on the user's preferences and makes an HTTP POST request to the Azure OpenAI API to get re-ranked and scored destinations.
3. **Generating Prompt (`generate_prompt` method)**: This method constructs a prompt for the Azure OpenAI, including the user's preferences and the list of destinations. The prompt guides the model to re-rank and score the destinations based on the provided preferences.
4. **API Call**: The `requests` library is used to make an HTTP POST request to the Azure OpenAI API endpoint. The response contains the re-ranked and scored destinations.
5. **Example Usage**: The travel agent collects user preferences (e.g., interest in sightseeing and diverse culture) and uses the Azure OpenAI service to get re-ranked and scored recommendations for travel destinations.
Make sure to replace `your_azure_openai_api_key` with your actual Azure OpenAI API key and `https://your-endpoint.com/...` pela URL do endpoint real de sua implantação do Azure OpenAI.
Ao aproveitar o LLM para reclassificação e pontuação, o agente de viagens pode fornecer recomendações de viagem mais personalizadas e relevantes para os clientes, melhorando sua experiência geral.
### RAG: Técnica de Prompt vs Ferramenta
A Geração Incrementada por Recuperação (RAG) pode ser tanto uma técnica de prompt quanto uma ferramenta no desenvolvimento de agentes de IA. Compreender a distinção entre os dois pode ajudá-lo a aproveitar o RAG de forma mais eficaz em seus projetos.
#### RAG como Técnica de Prompt
**O que é?**
- Como técnica de prompt, o RAG envolve a formulação de consultas ou prompts específicos para guiar a recuperação de informações relevantes de um grande corpus ou banco de dados. Essas informações são então usadas para gerar respostas ou ações.
**Como funciona:**
1. **Formular Prompts**: Crie prompts ou consultas bem estruturados com base na tarefa ou na entrada do usuário.
2. **Recuperar Informações**: Use os prompts para buscar dados relevantes de uma base de conhecimento ou conjunto de dados preexistente.
3. **Gerar Resposta**: Combine as informações recuperadas com modelos de IA generativos para produzir uma resposta abrangente e coerente.
**Exemplo em Agente de Viagens**:
- Entrada do Usuário: "Quero visitar museus em Paris."
- Prompt: "Encontre os principais museus em Paris."
- Informações Recuperadas: Detalhes sobre o Museu do Louvre, Musée d'Orsay, etc.
- Resposta Gerada: "Aqui estão alguns dos principais museus em Paris: Museu do Louvre, Musée d'Orsay e Centro Pompidou."
#### RAG como Ferramenta
**O que é?**
- Como ferramenta, o RAG é um sistema integrado que automatiza o processo de recuperação e geração, facilitando a implementação de funcionalidades complexas de IA sem a necessidade de criar prompts manualmente para cada consulta.
**Como funciona:**
1. **Integração**: Incorpore o RAG na arquitetura do agente de IA, permitindo que ele lide automaticamente com as tarefas de recuperação e geração.
2. **Automação**: A ferramenta gerencia todo o processo, desde receber a entrada do usuário até gerar a resposta final, sem exigir prompts explícitos para cada etapa.
3. **Eficiência**: Melhora o desempenho do agente ao simplificar o processo de recuperação e geração, permitindo respostas mais rápidas e precisas.
**Exemplo em Agente de Viagens**:
- Entrada do Usuário: "Quero visitar museus em Paris."
- Ferramenta RAG: Recupera automaticamente informações sobre museus e gera uma resposta.
- Resposta Gerada: "Aqui estão alguns dos principais museus em Paris: Museu do Louvre, Musée d'Orsay e Centro Pompidou."
### Comparação
| Aspecto | Técnica de Prompt | Ferramenta |
|------------------------|----------------------------------------------------------|-----------------------------------------------------|
| **Manual vs Automático** | Formulação manual de prompts para cada consulta. | Processo automatizado para recuperação e geração. |
| **Controle** | Oferece mais controle sobre o processo de recuperação. | Simplifica e automatiza a recuperação e geração. |
| **Flexibilidade** | Permite prompts personalizados com base em necessidades específicas. | Mais eficiente para implementações em larga escala. |
| **Complexidade** | Requer criação e ajuste de prompts. | Mais fácil de integrar na arquitetura de um agente de IA. |
### Exemplos Práticos
**Exemplo de Técnica de Prompt:**
```python
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)
```
**Exemplo de Ferramenta:**
```python
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)
```
### Avaliando Relevância
Avaliar relevância é um aspecto crucial do desempenho de agentes de IA. Isso garante que as informações recuperadas e geradas pelo agente sejam apropriadas, precisas e úteis para o usuário. Vamos explorar como avaliar relevância em agentes de IA, incluindo exemplos práticos e técnicas.
#### Conceitos-Chave na Avaliação de Relevância
1. **Consciência de Contexto**:
- O agente deve entender o contexto da consulta do usuário para recuperar e gerar informações relevantes.
- Exemplo: Se um usuário perguntar "melhores restaurantes em Paris", o agente deve considerar as preferências do usuário, como tipo de cozinha e orçamento.
2. **Precisão**:
- As informações fornecidas pelo agente devem ser factualmente corretas e atualizadas.
- Exemplo: Recomendar restaurantes abertos atualmente com boas avaliações em vez de opções desatualizadas ou fechadas.
3. **Intenção do Usuário**:
- O agente deve inferir a intenção do usuário por trás da consulta para fornecer as informações mais relevantes.
- Exemplo: Se um usuário perguntar por "hotéis econômicos", o agente deve priorizar opções acessíveis.
4. **Ciclo de Feedback**:
- Coletar e analisar continuamente o feedback do usuário ajuda o agente a refinar seu processo de avaliação de relevância.
- Exemplo: Incorporar classificações e feedback de usuários sobre recomendações anteriores para melhorar respostas futuras.
#### Técnicas Práticas para Avaliação de Relevância
1. **Pontuação de Relevância**:
- Atribuir uma pontuação de relevância a cada item recuperado com base em quão bem ele corresponde à consulta e preferências do usuário.
- Exemplo: ```python
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
```
2. **Filtragem e Classificação**:
- Filtrar itens irrelevantes e classificar os restantes com base em suas pontuações de relevância.
- Exemplo: ```python
def filter_and_rank(items, query):
ranked_items = sorted(items, key=lambda item: relevance_score(item, query), reverse=True)
return ranked_items[:10] # Return top 10 relevant items
```
3. **Processamento de Linguagem Natural (NLP)**:
- Usar técnicas de NLP para entender a consulta do usuário e recuperar informações relevantes.
- Exemplo: ```python
def process_query(query):
# Use NLP to extract key information from the user's query
processed_query = nlp(query)
return processed_query
```
4. **Integração de Feedback do Usuário**:
- Coletar feedback do usuário sobre as recomendações fornecidas e usá-lo para ajustar avaliações futuras de relevância.
- Exemplo: ```python
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
```
#### Exemplo: Avaliando Relevância no Agente de Viagens
Aqui está um exemplo prático de como o Agente de Viagens pode avaliar a relevância de recomendações de viagem:
```python
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] # Return top 10 relevant items
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
# Example usage
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)
```
### Pesquisa com Intenção
Pesquisar com intenção envolve entender e interpretar o propósito ou objetivo subjacente à consulta do usuário para recuperar e gerar as informações mais relevantes e úteis. Essa abordagem vai além de simplesmente corresponder palavras-chave, focando em compreender as reais necessidades e contexto do usuário.
#### Conceitos-Chave na Pesquisa com Intenção
1. **Compreensão da Intenção do Usuário**:
- A intenção do usuário pode ser categorizada em três tipos principais: informacional, navegacional e transacional.
- **Intenção Informacional**: O usuário busca informações sobre um tópico (ex.: "Quais são...").
```
```markdown
os melhores museus em Paris?"). - **Intenção de Navegação**: O usuário deseja navegar para um site ou página específica (por exemplo, "site oficial do Museu do Louvre"). - **Intenção Transacional**: O usuário pretende realizar uma transação, como reservar um voo ou fazer uma compra (por exemplo, "Reservar um voo para Paris"). 2. **Consciência de Contexto**: - Analisar o contexto da consulta do usuário ajuda a identificar com precisão sua intenção. Isso inclui considerar interações anteriores, preferências do usuário e os detalhes específicos da consulta atual. 3. **Processamento de Linguagem Natural (PLN)**: - Técnicas de PLN são empregadas para entender e interpretar as consultas em linguagem natural fornecidas pelos usuários. Isso inclui tarefas como reconhecimento de entidades, análise de sentimentos e interpretação de consultas. 4. **Personalização**: - Personalizar os resultados da pesquisa com base no histórico, nas preferências e no feedback do usuário aumenta a relevância das informações recuperadas. #### Exemplo Prático: Pesquisa com Intenção no Agente de Viagem Vamos usar o Agente de Viagem como exemplo para ver como a pesquisa com intenção pode ser implementada. 1. **Coleta de Preferências do Usuário** ```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
``` 2. **Entendimento da Intenção do Usuário** ```python
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"
``` 3. **Consciência de Contexto** ```python
def analyze_context(query, user_history):
# Combine current query with user history to understand context
context = {
"current_query": query,
"user_history": user_history
}
return context
``` 4. **Pesquisar e Personalizar Resultados** ```python
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):
# Example search logic for informational intent
results = search_web(f"best {preferences['interests']} in {preferences['destination']}")
return results
def search_navigation(query):
# Example search logic for navigational intent
results = search_web(query)
return results
def search_transaction(query, preferences):
# Example search logic for transactional intent
results = search_web(f"book {query} to {preferences['destination']}")
return results
def personalize_results(results, user_history):
# Example personalization logic
personalized = [result for result in results if result not in user_history]
return personalized[:10] # Return top 10 personalized results
``` 5. **Exemplo de Uso** ```python
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)
``` --- ## 4. Gerando Código como uma Ferramenta Agentes geradores de código usam modelos de IA para escrever e executar código, resolvendo problemas complexos e automatizando tarefas. ### Agentes Geradores de Código Agentes geradores de código usam modelos de IA generativa para escrever e executar código. Esses agentes podem resolver problemas complexos, automatizar tarefas e fornecer insights valiosos gerando e executando código em várias linguagens de programação. #### Aplicações Práticas 1. **Geração Automática de Código**: Gerar trechos de código para tarefas específicas, como análise de dados, web scraping ou aprendizado de máquina. 2. **SQL como RAG**: Usar consultas SQL para recuperar e manipular dados de bancos de dados. 3. **Resolução de Problemas**: Criar e executar código para resolver problemas específicos, como otimização de algoritmos ou análise de dados. #### Exemplo: Agente Gerador de Código para Análise de Dados Imagine que você está projetando um agente gerador de código. Veja como ele pode funcionar: 1. **Tarefa**: Analisar um conjunto de dados para identificar tendências e padrões. 2. **Etapas**: - Carregar o conjunto de dados em uma ferramenta de análise de dados. - Gerar consultas SQL para filtrar e agregar os dados. - Executar as consultas e recuperar os resultados. - Usar os resultados para gerar visualizações e insights. 3. **Recursos Necessários**: Acesso ao conjunto de dados, ferramentas de análise de dados e capacidades SQL. 4. **Experiência**: Usar resultados de análises anteriores para melhorar a precisão e a relevância das análises futuras. ### Exemplo: Agente Gerador de Código para Agente de Viagem Neste exemplo, projetaremos um agente gerador de código, Agente de Viagem, para ajudar os usuários a planejar suas viagens gerando e executando código. Este agente pode lidar com tarefas como buscar opções de viagem, filtrar resultados e compilar um itinerário usando IA generativa. #### Visão Geral do Agente Gerador de Código 1. **Coleta de Preferências do Usuário**: Coleta entradas do usuário, como destino, datas de viagem, orçamento e interesses. 2. **Geração de Código para Buscar Dados**: Gera trechos de código para recuperar dados sobre voos, hotéis e atrações. 3. **Execução do Código Gerado**: Executa o código gerado para buscar informações em tempo real. 4. **Geração de Itinerário**: Compila os dados recuperados em um plano de viagem personalizado. 5. **Ajuste com Base no Feedback**: Recebe feedback do usuário e regenera o código, se necessário, para refinar os resultados. #### Implementação Passo a Passo 1. **Coleta de Preferências do Usuário** ```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
``` 2. **Geração de Código para Buscar Dados** ```python
def generate_code_to_fetch_data(preferences):
# Example: Generate code to search for flights based on user preferences
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):
# Example: Generate code to search for hotels
code = f"""
def search_hotels():
import requests
response = requests.get('https://api.example.com/hotels', params={preferences})
return response.json()
"""
return code
``` 3. **Execução do Código Gerado** ```python
def execute_code(code):
# Execute the generated code using 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)
``` 4. **Geração de Itinerário** ```python
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)
``` 5. **Ajuste com Base no Feedback** ```python
def adjust_based_on_feedback(feedback, preferences):
# Adjust preferences based on user feedback
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)
# Regenerate and execute code with updated preferences
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)
``` ### Aproveitando a Consciência do Ambiente e o Raciocínio Com base no esquema da tabela, é possível melhorar o processo de geração de consultas aproveitando a consciência do ambiente e o raciocínio. Aqui está um exemplo de como isso pode ser feito: 1. **Entendimento do Esquema**: O sistema entenderá o esquema da tabela e usará essas informações para fundamentar a geração de consultas. 2. **Ajuste com Base no Feedback**: O sistema ajustará as preferências do usuário com base no feedback e raciocinará sobre quais campos no esquema precisam ser atualizados. 3. **Geração e Execução de Consultas**: O sistema gerará e executará consultas para buscar dados atualizados de voos e hotéis com base nas novas preferências. Aqui está um exemplo atualizado de código Python que incorpora esses conceitos: ```python
def adjust_based_on_feedback(feedback, preferences, schema):
# Adjust preferences based on user feedback
if "liked" in feedback:
preferences["favorites"] = feedback["liked"]
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
# Reasoning based on schema to adjust other related preferences
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):
# Custom logic to adjust preferences based on schema and feedback
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):
# Generate code to fetch flight data based on updated preferences
return f"fetch_flights(preferences={preferences})"
def generate_code_to_fetch_hotels(preferences):
# Generate code to fetch hotel data based on updated preferences
return f"fetch_hotels(preferences={preferences})"
def execute_code(code):
# Simulate execution of code and return mock data
return {"data": f"Executed: {code}"}
def generate_itinerary(flights, hotels, attractions):
# Generate itinerary based on flights, hotels, and attractions
return {"flights": flights, "hotels": hotels, "attractions": attractions}
# Example schema
schema = {
"favorites": {"positive_adjustment": "increase", "negative_adjustment": "decrease", "default": "neutral"},
"avoid": {"positive_adjustment": "decrease", "negative_adjustment": "increase", "default": "neutral"}
}
# Example usage
preferences = {"favorites": "sightseeing", "avoid": "crowded places"}
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
updated_preferences = adjust_based_on_feedback(feedback, preferences, schema)
# Regenerate and execute code with updated preferences
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)
``` #### Explicação - Reserva com Base no Feedback 1. **Consciência do Esquema**: O método `schema` dictionary defines how preferences should be adjusted based on feedback. It includes fields like `favorites` and `avoid`, with corresponding adjustments.
2. **Adjusting Preferences (`adjust_based_on_feedback` method)**: This method adjusts preferences based on user feedback and the schema.
3. **Environment-Based Adjustments (`adjust_based_on_environment`): Este método personaliza os ajustes com base no esquema e no feedback. 4. **Geração e Execução de Consultas**: O sistema gera código para buscar dados atualizados de voos e hotéis com base nas preferências ajustadas e simula a execução dessas consultas. 5. **Geração de Itinerário**: O sistema cria um itinerário atualizado com base nos novos dados de voos, hotéis e atrações. Ao tornar o sistema ciente do ambiente e raciocinar com base no esquema, ele pode gerar consultas mais precisas e relevantes, levando a melhores recomendações de viagem e uma experiência mais personalizada para o usuário. ### Usando SQL como uma Técnica de Recuperação-Baseada em Geração (RAG) SQL (Structured Query Language) é uma ferramenta poderosa para interagir com bancos de dados. Quando usada como parte de uma abordagem de Recuperação-Baseada em Geração (RAG), o SQL pode recuperar dados relevantes de bancos de dados para informar e gerar respostas ou ações em agentes de IA. Vamos explorar como o SQL pode ser usado como uma técnica RAG no contexto do Agente de Viagem. #### Conceitos-Chave 1. **Interação com Banco de Dados**: - O SQL é usado para consultar bancos de dados, recuperar informações relevantes e manipular dados. - Exemplo: Buscar detalhes de voos, informações de hotéis e atrações de um banco de dados de viagens. 2. **Integração com RAG**: - Consultas SQL são geradas com base nas entradas e preferências do usuário. - Os dados recuperados são então usados para gerar recomendações ou ações personalizadas. 3. **Geração Dinâmica de Consultas**: - O agente de IA gera consultas SQL dinâmicas com base no contexto e nas necessidades do usuário. - Exemplo: Personalizar consultas SQL para filtrar resultados com base no orçamento, datas e interesses. #### Aplicações - **Geração Automática de Código**: Gerar trechos de código para tarefas específicas. - **SQL como RAG**: Usar consultas SQL para manipular dados. - **Resolução de Problemas**: Criar e executar código para resolver problemas. **Exemplo**: Um agente de análise de dados: 1. **Tarefa**: Analisar um conjunto de dados para encontrar tendências. 2. **Etapas**: - Carregar o conjunto de dados. - Gerar consultas SQL para filtrar dados. - Executar consultas e recuperar resultados. - Gerar visualizações e insights. 3. **Recursos**: Acesso ao conjunto de dados, capacidades SQL. 4. **Experiência**: Usar resultados anteriores para melhorar análises futuras. #### Exemplo Prático: Usando SQL no Agente de Viagem 1. **Coleta de Preferências do Usuário** ```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
``` 2. **Geração de Consultas SQL** ```python
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
``` 3. **Execução de Consultas SQL** ```python
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
``` 4. **Geração de Recomendações** ```python
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)
``` #### Exemplos de Consultas SQL 1. **Consulta de Voo** ```sql
SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate';
``` 2. **Consulta de Hotel** ```sql
SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate';
``` 3. **Consulta de Atração** ```sql
SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine';
``` Ao aproveitar o SQL como parte da técnica de Recuperação-Baseada em Geração (RAG), agentes de IA como o Agente de Viagem podem recuperar e utilizar dinamicamente dados relevantes para fornecer recomendações precisas e personalizadas. ### Conclusão A metacognição é uma ferramenta poderosa que pode melhorar significativamente as capacidades dos agentes de IA. Ao incorporar processos metacognitivos, você pode projetar agentes mais inteligentes, adaptáveis e eficientes. Use os recursos adicionais para explorar mais sobre o fascinante mundo da metacognição em agentes de IA.
```
**Aviso Legal**:
Este documento foi traduzido utilizando serviços de tradução automática por IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte oficial. Para informações críticas, recomenda-se a tradução profissional humana. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/09-metacognition/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/09-metacognition/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 57027
} |
# Agentes de IA em Produção
## Introdução
Esta lição abordará:
- Como planejar de forma eficaz a implantação do seu Agente de IA em produção.
- Erros e problemas comuns que você pode enfrentar ao implantar seu Agente de IA em produção.
- Como gerenciar custos mantendo o desempenho do seu Agente de IA.
## Objetivos de Aprendizado
Após concluir esta lição, você saberá/entenderá:
- Técnicas para melhorar o desempenho, os custos e a eficácia de um sistema de Agente de IA em produção.
- O que avaliar e como avaliar seus Agentes de IA.
- Como controlar custos ao implantar Agentes de IA em produção.
É importante implantar Agentes de IA que sejam confiáveis. Confira a lição "Construindo Agentes de IA Confiáveis" para saber mais.
## Avaliando Agentes de IA
Antes, durante e depois de implantar Agentes de IA, é fundamental ter um sistema adequado para avaliá-los. Isso garantirá que seu sistema esteja alinhado com seus objetivos e os de seus usuários.
Para avaliar um Agente de IA, é importante ter a capacidade de avaliar não apenas o resultado do agente, mas todo o sistema em que ele opera. Isso inclui, mas não se limita a:
- A solicitação inicial ao modelo.
- A capacidade do agente de identificar a intenção do usuário.
- A capacidade do agente de identificar a ferramenta certa para realizar a tarefa.
- A resposta da ferramenta à solicitação do agente.
- A capacidade do agente de interpretar a resposta da ferramenta.
- O feedback do usuário à resposta do agente.
Isso permite identificar áreas de melhoria de forma mais modular. Assim, você pode monitorar o impacto de mudanças nos modelos, prompts, ferramentas e outros componentes com maior eficiência.
## Problemas Comuns e Soluções Potenciais com Agentes de IA
| **Problema** | **Solução Potencial** |
| ---------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Agente de IA não realiza tarefas de forma consistente | - Refinar o prompt fornecido ao Agente de IA; seja claro sobre os objetivos.<br>- Identificar onde dividir as tarefas em subtarefas e delegá-las a múltiplos agentes pode ser útil. |
| Agente de IA entrando em loops contínuos | - Certifique-se de ter condições e termos de encerramento claros para que o Agente saiba quando parar o processo.<br>- Para tarefas complexas que exigem raciocínio e planejamento, utilize um modelo maior especializado nessas tarefas. |
| Chamadas de ferramentas pelo Agente de IA não estão funcionando bem | - Teste e valide a saída da ferramenta fora do sistema do agente.<br>- Refine os parâmetros definidos, prompts e nomes das ferramentas. |
| Sistema de múltiplos agentes não está funcionando de forma consistente | - Refinar os prompts fornecidos a cada agente para garantir que sejam específicos e distintos entre si.<br>- Construir um sistema hierárquico usando um agente "roteador" ou controlador para determinar qual agente é o mais adequado. |
## Gerenciamento de Custos
Aqui estão algumas estratégias para gerenciar os custos ao implantar Agentes de IA em produção:
- **Cachear Respostas** - Identificar solicitações e tarefas comuns e fornecer as respostas antes que elas passem pelo seu sistema de agentes é uma boa maneira de reduzir o volume de solicitações semelhantes. Você pode até implementar um fluxo para identificar quão semelhante uma solicitação é em relação às solicitações em cache, usando modelos de IA mais básicos.
- **Usar Modelos Menores** - Modelos de Linguagem Pequenos (SLMs) podem ter um bom desempenho em certos casos de uso de agentes e reduzirão significativamente os custos. Como mencionado anteriormente, construir um sistema de avaliação para determinar e comparar o desempenho em relação a modelos maiores é a melhor maneira de entender quão bem um SLM funcionará no seu caso de uso.
- **Usar um Modelo Roteador** - Uma estratégia semelhante é usar uma diversidade de modelos e tamanhos. Você pode usar um LLM/SLM ou uma função serverless para rotear solicitações com base na complexidade para os modelos mais adequados. Isso ajudará a reduzir custos enquanto garante o desempenho nas tarefas certas.
## Parabéns
Esta é, atualmente, a última lição de "Agentes de IA para Iniciantes".
Planejamos continuar adicionando lições com base no feedback e nas mudanças desta indústria em constante crescimento, então volte a nos visitar em breve.
Se você deseja continuar aprendendo e desenvolvendo com Agentes de IA, participe do [Azure AI Community Discord](https://discord.gg/kzRShWzttr).
Realizamos workshops, mesas-redondas da comunidade e sessões de "pergunte-me qualquer coisa" por lá.
Também temos uma coleção de aprendizado com materiais adicionais que podem ajudar você a começar a construir Agentes de IA em produção.
**Aviso Legal**:
Este documento foi traduzido utilizando serviços de tradução baseados em IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte oficial. Para informações críticas, recomenda-se uma tradução profissional feita por humanos. Não nos responsabilizamos por quaisquer mal-entendidos ou interpretações equivocadas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/10-ai-agents-production/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/10-ai-agents-production/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 5782
} |
# 課程設置
## 簡介
本課程將介紹如何運行本課程中的程式範例。
## 需求
- 一個 GitHub 帳號
- Python 3.12+ 版本
## 複製或分叉這個倉庫
首先,請複製(clone)或分叉(fork)GitHub 倉庫。這樣可以建立您自己的課程資料副本,方便您運行、測試以及調整程式碼!
您可以透過點擊此連結 [fork the repo](https://github.com/microsoft/ai-agents-for-beginners/fork) 來完成操作。
完成後,您應該會有一個如下所示的分叉版本:

## 獲取您的 GitHub 個人訪問令牌(PAT)
目前,本課程使用 GitHub Models Marketplace 提供免費的大型語言模型(LLMs)存取權,這些模型將用於創建 AI Agents。
要使用此服務,您需要建立一個 GitHub 個人訪問令牌(Personal Access Token)。
您可以前往您的 GitHub 帳號中的 [Personal Access Tokens settings](https://github.com/settings/personal-access-tokens) 進行設定。
在螢幕左側選擇 `Fine-grained tokens` 選項。
接著選擇 `Generate new token`。

複製您剛剛建立的新令牌。接下來,您需要將它添加到課程中提供的 `.env` 文件中。
## 將令牌添加到環境變數
要建立您的 `.env` 文件,請在終端機中運行以下指令:
```bash
cp .env.example .env
```
這將複製範例文件並在您的目錄中建立一個 `.env` 文件。
打開該文件,將您創建的令牌粘貼到 .env 文件的 `GITHUB_TOKEN=` 欄位中。
## 安裝必要的套件
為了確保您擁有運行程式所需的所有 Python 套件,請在終端機中運行以下指令。
我們建議建立一個 Python 虛擬環境,以避免任何衝突或問題。
```bash
pip install -r requirements.txt
```
這應該會安裝所有必要的 Python 套件。
現在,您已準備好運行程式碼,祝您學習 AI Agents 的世界愉快!
如果您在設置過程中遇到任何問題,請加入我們的 [Azure AI 社群 Discord](https://discord.gg/kzRShWzttr) 或 [建立問題單](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst)。
```
**免責聲明**:
本文檔是使用機器翻譯的人工智慧翻譯服務完成的。我們雖然努力確保翻譯的準確性,但請注意,自動翻譯可能會包含錯誤或不精確之處。應以原文檔的原始語言版本作為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或誤讀概不負責。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/00-course-setup/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/00-course-setup/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 1660
} |
# AI代理與應用案例介紹
歡迎來到「AI代理入門」課程!本課程旨在為您提供AI代理的基礎知識以及應用範例,幫助您學習如何構建AI代理。
加入 [Azure AI Discord 社群](https://discord.gg/kzRShWzttr),與其他學員以及AI代理開發者交流,並隨時提出您在學習過程中的問題。
在開始本課程之前,我們將首先了解什麼是AI代理,以及如何將它們應用於我們的應用程式和工作流程中。
## 課程介紹
本課程涵蓋以下內容:
- 什麼是AI代理?有哪些不同類型的代理?
- AI代理最適合的應用場景有哪些?它們如何幫助我們?
- 設計代理解決方案時需要考慮的基本組成部分有哪些?
## 學習目標
完成本課程後,您應該能夠:
- 理解AI代理的概念,並了解它們與其他AI解決方案的不同之處。
- 有效地應用AI代理。
- 為用戶與客戶高效設計代理解決方案。
## 定義AI代理與代理類型
### 什麼是AI代理?
AI代理是**系統**,它通過為**大型語言模型(LLMs)**提供**工具**和**知識的訪問權限**,使其能夠執行**操作**,從而擴展其能力。
讓我們將這個定義分解為更小的部分:
- **系統** - AI代理不僅僅是單一組件,而是一個由多個組件組成的系統。基本上,AI代理的組件包括:
- **環境** - 定義AI代理運行的空間。例如,若我們有一個旅行預訂AI代理,環境可能是AI代理用來完成任務的旅行預訂系統。
- **感應器** - 環境提供信息和反饋。AI代理使用感應器來收集並解讀環境當前狀態的信息。在旅行預訂代理的例子中,旅行預訂系統可以提供如酒店空房情況或機票價格等信息。
- **執行器** - 當AI代理獲取環境的當前狀態後,針對當前任務決定執行的操作,以改變環境。對於旅行預訂代理來說,可能的操作是為用戶預訂一間可用的房間。
)
**大型語言模型** - 代理的概念早於LLMs的誕生而存在。使用LLMs構建AI代理的優勢在於它們能夠解讀人類語言和數據的能力。這種能力使LLMs能夠解讀環境信息並制定改變環境的計劃。
**執行操作** - 在AI代理系統之外,LLMs的操作通常限於根據用戶提示生成內容或信息。而在AI代理系統內,LLMs能夠通過解讀用戶請求並使用環境中可用的工具來完成任務。
**工具的訪問權限** - LLM可訪問的工具由以下兩個因素決定:1)它運行的環境,2)AI代理的開發者。例如,在旅行代理的案例中,代理的工具可能受限於預訂系統中的操作,或者開發者可以限制代理只能訪問航班相關的工具。
**知識** - 除了環境提供的信息外,AI代理還可以從其他系統、服務、工具甚至其他代理中獲取知識。在旅行代理的例子中,這些知識可能是存儲在客戶數據庫中的用戶旅行偏好信息。
### 不同類型的代理
現在我們已經了解了AI代理的一般定義,接下來讓我們看看一些具體的代理類型,以及它們如何應用於旅行預訂AI代理。
| **代理類型** | **描述** | **範例** |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **簡單反射代理** | 根據預定義規則執行即時操作。 | 旅行代理解讀電子郵件內容,並將旅行投訴轉發給客戶服務部門。 |
| **基於模型的反射代理** | 根據世界模型及其變化執行操作。 | 旅行代理根據歷史價格數據的訪問權限,優先處理價格有重大變動的路線。 |
| **目標導向代理** | 通過解讀目標並確定達成目標所需的行動,來制定計劃實現特定目標。 | 旅行代理根據當前位置到目的地,確定所需的旅行安排(如汽車、公共交通、航班)並完成預訂。 |
| **效用導向代理** | 考慮偏好並數值化權衡,以確定如何達成目標。 | 旅行代理在便利性與成本之間進行權衡,以最大化效用並完成旅行預訂。 |
| **學習代理** | 通過回應反饋並相應地調整行動來不斷改進。 | 旅行代理根據客戶在旅行後調查中的反饋,改進未來的預訂策略。 |
| **分層代理** | 包含多個代理的分層系統,高層代理將任務分解為子任務,由低層代理完成。 | 旅行代理通過將任務分解為子任務(例如取消具體預訂),由低層代理完成並回報給高層代理來實現取消行程。 |
| **多代理系統(MAS)** | 多個代理獨立完成任務,可以是合作或競爭關係。 | 合作:多個代理分別預訂具體的旅行服務,如酒店、航班和娛樂活動。競爭:多個代理管理並競爭共享的酒店預訂日曆,以為客戶安排酒店入住。 |
## 何時使用AI代理
在之前的部分中,我們使用旅行代理的案例說明了不同類型的代理如何應用於旅行預訂的不同場景。在整個課程中,我們將繼續使用這個應用作為示例。
接下來,讓我們看看AI代理最適合的應用場景:

- **開放性問題** - 允許LLM自行決定完成任務所需的步驟,因為這些步驟無法總是硬編碼到工作流程中。
- **多步驟流程** - 涉及一定複雜度的任務,AI代理需要在多次交互中使用工具或信息,而不是一次性檢索。
- **隨時間改進** - 任務需要代理通過來自環境或用戶的反饋,不斷改進以提供更高的效用。
在《構建可信任的AI代理》課程中,我們將更深入探討使用AI代理的考量因素。
## 代理解決方案的基礎
### 代理開發
設計AI代理系統的第一步是定義工具、行動和行為。在本課程中,我們專注於使用 **Azure AI Agent Service** 來定義我們的代理。該服務提供以下功能:
- 選擇開放模型,例如OpenAI、Mistral和Llama。
- 通過Tripadvisor等提供商使用授權數據。
- 使用標準化的OpenAPI 3.0工具。
### 代理模式
與LLM的交互是通過提示完成的。由於AI代理的半自主性質,並非總是需要或可能在環境變化後手動重新提示LLM。我們使用 **代理模式**,允許我們在多個步驟中以更具規模化的方式提示LLM。
本課程將介紹當前一些流行的代理模式。
### 代理框架
代理框架允許開發者通過代碼實現代理模式。這些框架提供模板、插件和工具,幫助實現更好的AI代理協作。這些優勢使得AI代理系統更易於觀察和排查問題。
在本課程中,我們將探討基於研究的AutoGen框架,以及Semantic Kernel提供的生產級Agent框架。
**免責聲明**:
本文件是使用機器翻譯AI服務進行翻譯的。我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文文件為最具權威性的來源。對於關鍵信息,建議尋求專業人工翻譯。我們對因使用此翻譯而產生的任何誤解或誤讀概不負責。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/01-intro-to-ai-agents/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/01-intro-to-ai-agents/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 5373
} |
# 探索 AI Agent 框架
AI Agent 框架是為了簡化 AI agent 的創建、部署和管理而設計的軟體平台。這些框架為開發者提供了預先構建的組件、抽象層和工具,從而加速複雜 AI 系統的開發過程。
透過提供標準化的方法來解決 AI agent 開發中的常見挑戰,這些框架讓開發者能專注於應用程式的獨特面向。同時,它們提升了 AI 系統的可擴展性、可存取性和效率。
## 簡介
本課程將涵蓋以下內容:
- 什麼是 AI Agent 框架?它能讓開發者完成哪些事情?
- 團隊如何利用這些框架快速原型化、迭代和提升 agent 的能力?
- 微軟的框架與工具([Autogen](https://aka.ms/ai-agents/autogen)、[Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel)、[Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service))之間的差異是什麼?
- 我可以直接整合現有的 Azure 生態系統工具,還是需要獨立的解決方案?
- 什麼是 Azure AI Agents 服務,它能如何幫助我?
## 學習目標
本課程的目標是幫助您了解:
- AI Agent 框架在 AI 開發中的角色。
- 如何利用 AI Agent 框架來構建智慧型 agent。
- AI Agent 框架所啟用的核心功能。
- Autogen、Semantic Kernel 和 Azure AI Agent Service 的差異。
## 什麼是 AI Agent 框架?它能讓開發者完成哪些事情?
傳統的 AI 框架可以幫助您將 AI 整合到應用程式中,並透過以下方式提升應用程式的功能:
- **個性化**:AI 能分析用戶行為和偏好,提供個性化的推薦、內容和體驗。
範例:像 Netflix 這樣的串流服務利用 AI 根據觀看歷史推薦電影和節目,提升用戶參與度和滿意度。
- **自動化與效率**:AI 能自動化重複性任務、簡化工作流程並提升運營效率。
範例:客戶服務應用程式利用 AI 驅動的聊天機器人處理常見問題,縮短回應時間,讓人類客服專注於更複雜的問題。
- **提升用戶體驗**:AI 能提供智慧功能,例如語音識別、自然語言處理和預測性文字輸入,改善整體用戶體驗。
範例:像 Siri 和 Google Assistant 這樣的虛擬助手利用 AI 理解並回應語音指令,讓用戶更輕鬆地與裝置互動。
### 聽起來很棒對吧,那為什麼我們還需要 AI Agent 框架?
AI Agent 框架不僅僅是 AI 框架,它們旨在創建能與用戶、其他 agent 和環境互動以達成特定目標的智慧型 agent。這些 agent 能展現自主行為、做出決策並適應變化中的環境。我們來看看 AI Agent 框架啟用的一些關鍵功能:
- **Agent 的協作與協調**:能創建多個 AI agent,它們可以協作、溝通並共同解決複雜任務。
- **任務自動化與管理**:提供機制來自動化多步驟的工作流程、任務分配和動態任務管理。
- **上下文理解與適應**:讓 agent 具備理解上下文、適應變化環境並根據即時資訊做出決策的能力。
總而言之,這些 agent 能幫助您完成更多工作,將自動化提升到新層次,並創建能從環境中學習和適應的智慧系統。
## 如何快速原型化、迭代並提升 agent 的能力?
這是一個快速變化的領域,但大多數 AI Agent 框架中有一些共同的元素,能幫助您快速原型化和迭代,主要包括模組化組件、協作工具和即時學習。我們來深入了解這些元素:
- **使用模組化組件**:AI 框架提供預構建的組件,例如提示、解析器和記憶管理。
- **利用協作工具**:設計具有特定角色和任務的 agent,測試並完善協作工作流程。
- **即時學習**:實施反饋循環,讓 agent 從互動中學習並動態調整行為。
### 使用模組化組件
像 LangChain 和 Microsoft Semantic Kernel 這樣的框架提供了預構建的組件,例如提示、解析器和記憶管理。
**團隊如何使用**:團隊可以快速組裝這些組件來創建功能原型,無需從零開始,從而進行快速實驗和迭代。
**實際運作方式**:您可以使用預構建的解析器從用戶輸入中提取資訊,使用記憶模組來儲存和檢索數據,並使用提示生成器與用戶互動,無需自行構建這些組件。
**範例代碼**:以下是如何使用預構建的解析器從用戶輸入中提取資訊的範例:
```python
from langchain import Parser
parser = Parser()
user_input = "Book a flight from New York to London on July 15th"
parsed_data = parser.parse(user_input)
print(parsed_data)
# Output: {'origin': 'New York', 'destination': 'London', 'date': 'July 15th'}
```
從這個範例可以看出,如何利用預構建的解析器從用戶輸入中提取關鍵資訊,例如航班預訂請求的出發地、目的地和日期。這種模組化方法讓您能專注於高層次邏輯。
### 利用協作工具
像 CrewAI 和 Microsoft Autogen 這樣的框架可以幫助創建多個能協作的 agent。
**團隊如何使用**:團隊可以設計具有特定功能和任務的 agent,測試並完善協作工作流程,提升整體系統效率。
**實際運作方式**:您可以創建一組 agent,其中每個 agent 都有專門的功能,例如數據檢索、分析或決策。這些 agent 能溝通並分享資訊,以完成共同目標,例如回答用戶查詢或完成任務。
**範例代碼(Autogen)**:
```python
# creating agents, then create a round robin schedule where they can work together, in this case in order
# Data Retrieval Agent
# Data Analysis Agent
# Decision Making Agent
agent_retrieve = AssistantAgent(
name="dataretrieval",
model_client=model_client,
tools=[retrieve_tool],
system_message="Use tools to solve tasks."
)
agent_analyze = AssistantAgent(
name="dataanalysis",
model_client=model_client,
tools=[analyze_tool],
system_message="Use tools to solve tasks."
)
# conversation ends when user says "APPROVE"
termination = TextMentionTermination("APPROVE")
user_proxy = UserProxyAgent("user_proxy", input_func=input)
team = RoundRobinGroupChat([agent_retrieve, agent_analyze, user_proxy], termination_condition=termination)
stream = team.run_stream(task="Analyze data", max_turns=10)
# Use asyncio.run(...) when running in a script.
await Console(stream)
```
上述代碼展示了如何創建一個任務,涉及多個 agent 協作完成數據分析。每個 agent 執行特定功能,透過協調這些 agent 的行動來實現目標。透過創建具有專業角色的專屬 agent,您可以提升任務效率和性能。
### 即時學習
進階框架提供了即時上下文理解和適應的能力。
**團隊如何使用**:團隊可以實施反饋循環,讓 agent 從互動中學習並動態調整行為,實現持續改進和能力優化。
**實際運作方式**:agent 可以分析用戶反饋、環境數據和任務結果,更新其知識庫、調整決策演算法並提升性能。這種迭代學習過程讓 agent 能適應變化的條件和用戶偏好,增強整體系統的效能。
## Autogen、Semantic Kernel 和 Azure AI Agent Service 之間有什麼差異?
這些框架之間有許多比較方式,但我們可以從設計、功能和目標使用案例的角度來看一些關鍵差異:
### Autogen
這是一個由微軟研究院 AI Frontiers Lab 開發的開源框架,專注於事件驅動的分散式 *agentic* 應用程式,支持多個 LLM 和 SLM、工具以及進階的多 agent 設計模式。
Autogen 的核心概念是 agent,也就是能感知環境、做出決策並採取行動以達成特定目標的自主實體。agent 透過非同步訊息進行溝通,使其能獨立且並行工作,提升系統的可擴展性和響應性。
... (請參閱原始文件中的完整詳細說明,內容過多,無法一次列出)
### Semantic Kernel + Agent Framework
Semantic Kernel 包含兩部分:Semantic Kernel Agent Framework 和 Semantic Kernel 本身。
... (請參閱原始文件中的完整詳細說明)
### Azure AI Agent Service
Azure AI Agent Service 是最近推出的服務(於 Microsoft Ignite 2024 發表)。它允許使用更靈活的模型來開發和部署 AI agent,例如直接調用開源 LLM(如 Llama 3、Mistral 和 Cohere)。
... (請參閱原始文件中的完整詳細說明)
---
### 哪個框架適合您的使用案例?
以下是一些常見使用案例的建議:
> **Q**: 我的團隊正在開發一個涉及自動化代碼生成和數據分析任務的項目,我們應該使用哪個框架?
> **A**: Autogen 是一個不錯的選擇,因為它專注於事件驅動的分散式 *agentic* 應用程式,並支持進階的多 agent 設計模式。
... (請參閱原始文件中的完整對話內容)
---
希望這些資訊能幫助您更好地選擇適合您需求的 AI Agent 框架!
根據項目目標。適用於自然語言理解和內容生成。
- **Azure AI Agent Service**:靈活的模型、企業安全機制、數據存儲方法。適用於在企業應用中部署安全、可擴展且靈活的 AI 代理。
## 我可以直接整合現有的 Azure 生態系統工具,還是需要獨立的解決方案?
答案是肯定的,您可以直接將現有的 Azure 生態系統工具與 Azure AI Agent Service 整合,特別是因為它被設計為能與其他 Azure 服務無縫協作。例如,您可以整合 Bing、Azure AI Search 和 Azure Functions。此外,還可以與 Azure AI Foundry 深度整合。
對於 Autogen 和 Semantic Kernel,您也可以與 Azure 服務整合,但可能需要從您的代碼中調用 Azure 服務。另一種整合方式是使用 Azure SDK 從您的代理與 Azure 服務交互。此外,如前所述,您可以使用 Azure AI Agent Service 作為基於 Autogen 或 Semantic Kernel 構建的代理的協調器,從而輕鬆訪問 Azure 生態系統。
## 參考資料
- [1] - [Azure Agent Service](https://techcommunity.microsoft.com/blog/azure-ai-services-blog/introducing-azure-ai-agent-service/4298357)
- [2] - [Semantic Kernel and Autogen](https://devblogs.microsoft.com/semantic-kernel/microsofts-agentic-ai-frameworks-autogen-and-semantic-kernel/)
- [3] - [Semantic Kernel Agent Framework](https://learn.microsoft.com/semantic-kernel/frameworks/agent/?pivots=programming-language-csharp)
- [4] - [Azure AI Agent service](https://learn.microsoft.com/azure/ai-services/agents/overview)
- [5] - [Using Azure AI Agent Service with AutoGen / Semantic Kernel to build a multi-agent's solution](https://techcommunity.microsoft.com/blog/educatordeveloperblog/using-azure-ai-agent-service-with-autogen--semantic-kernel-to-build-a-multi-agen/4363121)
**免責聲明**:
本文件使用基於機器的人工智能翻譯服務進行翻譯。儘管我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。原文檔的母語版本應被視為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對使用此翻譯所引起的任何誤解或錯誤解讀概不負責。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/02-explore-agentic-frameworks/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/02-explore-agentic-frameworks/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 6351
} |
# AI 代理設計原則
## 簡介
打造 AI 代理系統有許多不同的思路。由於在生成式 AI 設計中,模糊性是一種特性而非缺陷,工程師有時可能會不知道從何開始。我們制定了一套以人為中心的使用者體驗設計原則,幫助開發者建立以客戶需求為核心的代理系統,解決業務問題。這些設計原則並非具體的架構指導,而是為定義和構建代理體驗的團隊提供的一個起點。
一般來說,代理應該:
- 擴展並放大人類的能力(如腦力激盪、問題解決、自動化等)
- 填補知識空白(如讓我快速掌握某個知識領域、翻譯等)
- 促進並支持我們以個人偏好的方式與他人合作
- 幫助我們成為更好的自己(例如:生活教練/任務管理者,幫助我們學習情緒調節與正念技巧,建立韌性等)
## 本課程將涵蓋
- 什麼是代理設計原則
- 在實施這些設計原則時應遵循的指導方針
- 運用這些設計原則的範例
## 學習目標
完成本課程後,您將能夠:
1. 解釋什麼是代理設計原則
2. 說明如何應用代理設計原則的指導方針
3. 瞭解如何使用代理設計原則構建代理
## 代理設計原則

### 代理(空間)
這是代理運行的環境。這些原則指導我們如何設計代理以便在物理和數位世界中互動。
- **連結,而非取代** – 幫助人們連結其他人、事件和可行的知識,促進協作與聯繫。
- 代理協助連結事件、知識和人。
- 代理拉近人與人之間的距離,而非取代或貶低人類。
- **易於存取但偶爾隱形** – 代理主要在背景中運行,僅在相關且適當時才提醒我們。
- 代理對授權使用者在任何裝置或平台上都容易發現和存取。
- 代理支持多模態的輸入與輸出(如聲音、語音、文字等)。
- 代理可以根據使用者需求無縫切換前景與背景模式,或主動與被動狀態。
- 代理可能以隱形形式運行,但其背景運作過程及與其他代理的協作對使用者是透明且可控的。
### 代理(時間)
這是代理隨時間運行的方式。這些原則指導我們如何設計代理在過去、現在和未來的互動。
- **過去**:反映歷史,包括狀態和上下文。
- 代理基於更豐富的歷史數據分析提供更相關的結果,而不僅限於事件、人或狀態。
- 代理從過去的事件中建立連結,並主動反思記憶以應對當前情境。
- **現在**:提示,而非僅僅通知。
- 代理採取全面的方式與人互動。當事件發生時,代理不僅是靜態通知或形式化,而是簡化流程或動態生成提示,引導使用者在適當時刻專注。
- 代理根據上下文環境、社會與文化變化,以及使用者意圖提供資訊。
- 代理的互動可以是漸進的,隨著時間推移逐漸增強其複雜度,以賦能使用者。
- **未來**:適應與演進。
- 代理適應不同裝置、平台和模式。
- 代理適應使用者行為和無障礙需求,並可自由定制。
- 代理通過持續的使用者互動來塑造並演進。
### 代理(核心)
這是代理設計核心的關鍵元素。
- **擁抱不確定性但建立信任**。
- 代理的不確定性是可以預期的。不確定性是代理設計中的一個關鍵要素。
- 信任與透明是代理設計的基礎層。
- 人類可以控制代理的開啟/關閉,代理狀態始終清晰可見。
## 實施這些原則的指導方針
在使用上述設計原則時,請遵循以下指導方針:
1. **透明性**:告知使用者 AI 的參與方式、其運作原理(包括過去的行為),以及如何提供反饋和修改系統。
2. **控制權**:讓使用者能夠自訂、設定偏好並個性化,並擁有對系統及其屬性的控制權(包括忘記的能力)。
3. **一致性**:目標是在裝置與端點之間提供一致的多模態體驗。儘量使用熟悉的 UI/UX 元素(例如,語音互動的麥克風圖示),並盡可能減少使用者的認知負擔(例如,提供簡潔的回應、視覺輔助以及“瞭解更多”內容)。
## 如何運用這些原則和指導方針設計旅行代理
假設您正在設計一個旅行代理,以下是如何運用設計原則和指導方針的思路:
1. **透明性** – 告訴使用者旅行代理是一個 AI 驅動的代理。提供一些基本的使用說明(例如,“Hello”訊息,範例提示)。在產品頁面上清楚記載。顯示使用者過去詢問的提示列表。明確說明如何提供反饋(例如,讚/踩按鈕、發送反饋按鈕等)。清楚說明代理是否有使用或主題限制。
2. **控制權** – 明確告訴使用者如何在代理創建後進行修改,例如系統提示。讓使用者選擇代理的詳細程度、寫作風格,以及代理不應談論的內容限制。允許使用者檢視和刪除任何相關的檔案或數據、提示和過去的對話。
3. **一致性** – 確保分享提示、添加檔案或照片,以及標記某人或某物的圖示是標準且易識別的。使用回形針圖示表示檔案上傳/分享功能,使用圖片圖示表示圖形上傳功能。
## 其他資源
- [Practices for Governing Agentic AI Systems | OpenAI](https://openai.com)
- [The HAX Toolkit Project - Microsoft Research](https://microsoft.com)
- [Responsible AI Toolbox](https://responsibleaitoolbox.ai)
**免責聲明**:
本文件使用基於機器的人工智能翻譯服務進行翻譯。儘管我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原始語言的文件作為權威來源。對於關鍵信息,建議尋求專業的人工作翻譯。我們對因使用此翻譯而產生的任何誤解或誤讀概不負責。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/03-agentic-design-patterns/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/03-agentic-design-patterns/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 2614
} |
# 工具使用設計模式
## 介紹
在這節課中,我們將回答以下問題:
- 什麼是工具使用設計模式?
- 它可以應用於哪些使用案例?
- 實現這種設計模式需要哪些要素/組件?
- 使用工具使用設計模式來構建可信任的 AI 代理時需要注意哪些特別考量?
## 學習目標
完成本課程後,您將能夠:
- 定義工具使用設計模式及其目的。
- 辨識適用於工具使用設計模式的使用案例。
- 理解實現該設計模式所需的關鍵要素。
- 了解確保使用此設計模式的 AI 代理可信任的考量。
## 什麼是工具使用設計模式?
**工具使用設計模式**專注於賦予大型語言模型(LLMs)與外部工具互動的能力,以達成特定目標。工具是可由代理執行的程式碼,可以是簡單的函數(例如計算器),也可以是第三方服務的 API 呼叫(例如股票價格查詢或天氣預報)。在 AI 代理的上下文中,工具被設計為由代理根據**模型生成的函數呼叫**來執行。
## 它可以應用於哪些使用案例?
AI 代理可以利用工具完成複雜任務、檢索資訊或做出決策。工具使用設計模式通常用於需要與外部系統動態互動的場景,例如資料庫、網路服務或程式碼解釋器。這種能力適用於多種使用案例,包括但不限於:
- **動態資訊檢索:** 代理可以查詢外部 API 或資料庫以獲取最新數據(例如,查詢 SQLite 資料庫進行數據分析、獲取股票價格或天氣資訊)。
- **程式碼執行與解釋:** 代理可以執行程式碼或腳本來解決數學問題、生成報告或進行模擬。
- **工作流程自動化:** 通過整合任務排程器、電子郵件服務或數據管道等工具,自動化重複性或多步驟的工作流程。
- **客戶支持:** 代理可以與 CRM 系統、工單平台或知識庫互動,解決用戶問題。
- **內容生成與編輯:** 代理可以利用工具(如文法檢查器、文本摘要工具或內容安全評估器)協助完成內容創建任務。
## 實現工具使用設計模式需要哪些要素/組件?
### 函數/工具呼叫
函數呼叫是讓大型語言模型(LLMs)與工具互動的主要方式。您經常會看到「函數」和「工具」這兩個詞互換使用,因為「函數」(可重用的程式碼塊)就是代理用來執行任務的「工具」。為了讓函數的程式碼被調用,LLM 必須將用戶的請求與函數的描述進行比較。為此,需要向 LLM 傳送包含所有可用函數描述的架構(schema)。LLM 然後選擇最適合任務的函數,並返回其名稱和參數。選定的函數被調用,其響應會返回給 LLM,LLM 使用這些資訊來回應用戶的請求。
開發人員若要為代理實現函數呼叫,您需要:
1. 支援函數呼叫的 LLM 模型
2. 包含函數描述的架構
3. 每個描述函數的程式碼
讓我們用一個獲取城市當前時間的例子來說明:
- **初始化支援函數呼叫的 LLM:**
並非所有模型都支援函數呼叫,因此檢查您使用的 LLM 是否支援此功能非常重要。[Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/how-to/function-calling) 支援函數呼叫。我們可以從初始化 Azure OpenAI 客戶端開始。
```python
# Initialize the Azure OpenAI client
client = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2024-05-01-preview"
)
```
- **創建函數架構:**
接下來,我們將定義一個包含函數名稱、函數用途描述以及函數參數名稱和描述的 JSON 架構。我們將此架構與用戶的請求一同傳遞給上述創建的客戶端,以查找舊金山的時間。需要注意的是,返回的是**工具呼叫**,而**不是**問題的最終答案。如前所述,LLM 返回的是它為任務選擇的函數名稱及其參數。
```python
# Function description for the model to read
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Get the current time in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
},
"required": ["location"],
},
}
}
]
```
```python
# Initial user message
messages = [{"role": "user", "content": "What's the current time in San Francisco"}]
# First API call: Ask the model to use the function
response = client.chat.completions.create(
model=deployment_name,
messages=messages,
tools=tools,
tool_choice="auto",
)
# Process the model's response
response_message = response.choices[0].message
messages.append(response_message)
print("Model's response:")
print(response_message)
```
```bash
Model's response:
ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_pOsKdUlqvdyttYB67MOj434b', function=Function(arguments='{"location":"San Francisco"}', name='get_current_time'), type='function')])
```
- **執行任務所需的函數程式碼:**
現在,LLM 已選擇需要執行的函數,接下來需要實現並執行執行任務的程式碼。我們可以使用 Python 實現獲取當前時間的程式碼,還需要編寫程式碼來從 `response_message` 中提取名稱和參數以獲取最終結果。
```python
def get_current_time(location):
"""Get the current time for a given location"""
print(f"get_current_time called with location: {location}")
location_lower = location.lower()
for key, timezone in TIMEZONE_DATA.items():
if key in location_lower:
print(f"Timezone found for {key}")
current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p")
return json.dumps({
"location": location,
"current_time": current_time
})
print(f"No timezone data found for {location_lower}")
return json.dumps({"location": location, "current_time": "unknown"})
```
```python
# Handle function calls
if response_message.tool_calls:
for tool_call in response_message.tool_calls:
if tool_call.function.name == "get_current_time":
function_args = json.loads(tool_call.function.arguments)
time_response = get_current_time(
location=function_args.get("location")
)
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": "get_current_time",
"content": time_response,
})
else:
print("No tool calls were made by the model.")
# Second API call: Get the final response from the model
final_response = client.chat.completions.create(
model=deployment_name,
messages=messages,
)
return final_response.choices[0].message.content
```
```bash
get_current_time called with location: San Francisco
Timezone found for san francisco
The current time in San Francisco is 09:24 AM.
```
函數呼叫是大多數(如果不是全部的話)代理工具使用設計的核心,然而從零開始實現它有時可能會具有挑戰性。如我們在 [第 2 課](../../../02-explore-agentic-frameworks) 中學到的,代理框架為我們提供了實現工具使用的預構建組件。
### 使用代理框架的工具使用範例
- ### **[Semantic Kernel](https://learn.microsoft.com/azure/ai-services/agents/overview)**
Semantic Kernel 是一個為 .NET、Python 和 Java 開發者設計的開源 AI 框架,用於與大型語言模型(LLMs)協作。它通過一個稱為[序列化](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions)的過程,自動向模型描述函數及其參數,簡化了函數呼叫的過程。它還處理模型與程式碼之間的交互。使用像 Semantic Kernel 這樣的代理框架的另一個優勢是,您可以訪問預構建的工具,例如 [File Search](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step4_assistant_tool_file_search.py) 和 [Code Interpreter](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py)。
下圖說明了使用 Semantic Kernel 進行函數呼叫的過程:

在 Semantic Kernel 中,函數/工具被稱為 [Plugins](https://learn.microsoft.com/semantic-kernel/concepts/plugins/?pivots=programming-language-python)。我們可以將函數 `get_current_time` function we saw earlier into a plugin by turning it into a class with the function in it. We can also import the `kernel_function` 裝飾器,這需要提供函數的描述。當您使用 GetCurrentTimePlugin 創建一個 kernel 時,kernel 將自動序列化該函數及其參數,並在此過程中創建發送給 LLM 的架構。
```python
from semantic_kernel.functions import kernel_function
class GetCurrentTimePlugin:
async def __init__(self, location):
self.location = location
@kernel_function(
description="Get the current time for a given location"
)
def get_current_time(location: str = ""):
...
```
```python
from semantic_kernel import Kernel
# Create the kernel
kernel = Kernel()
# Create the plugin
get_current_time_plugin = GetCurrentTimePlugin(location)
# Add the plugin to the kernel
kernel.add_plugin(get_current_time_plugin)
```
- ### **[Azure AI Agent Service](https://learn.microsoft.com/azure/ai-services/agents/overview)**
Azure AI Agent Service 是一個新型代理框架,旨在幫助開發者安全地構建、部署和擴展高質量且可擴展的 AI 代理,而無需管理底層的計算和存儲資源。它對於企業應用特別有用,因為它是一個具有企業級安全性的完全託管服務。
與直接使用 LLM API 開發相比,Azure AI Agent Service 提供了一些優勢,包括:
- 自動工具呼叫——無需解析工具呼叫、調用工具並處理響應;所有這些現在都在伺服器端完成。
- 安全管理數據——您可以依靠線程存儲所需的所有資訊,而無需管理自己的對話狀態。
- 現成的工具——您可以使用這些工具與數據源交互,例如 Bing、Azure AI Search 和 Azure Functions。
Azure AI Agent Service 中的工具可以分為兩類:
1. 知識工具:
- [使用 Bing 搜索進行基礎設置](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/bing-grounding?tabs=python&pivots=overview)
- [文件搜索](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/file-search?tabs=python&pivots=overview)
- [Azure AI Search](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-ai-search?tabs=azurecli%2Cpython&pivots=overview-azure-ai-search)
2. 行動工具:
- [函數呼叫](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/function-calling?tabs=python&pivots=overview)
- [程式碼解釋器](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/code-interpreter?tabs=python&pivots=overview)
- [OpenAI 定義的工具](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/openapi-spec?tabs=python&pivots=overview)
- [Azure Functions](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-functions?pivots=overview)
Agent Service 允許我們將這些工具作為一個 `toolset`. It also utilizes `threads` which keep track of the history of messages from a particular conversation.
Imagine you are a sales agent at a company called Contoso. You want to develop a conversational agent that can answer questions about your sales data.
The image below illustrates how you could use Azure AI Agent Service to analyze your sales data:

To use any of these tools with the service we can create a client and define a tool or toolset. To implement this practically we can use the Python code below. The LLM will be able to look at the toolset and decide whether to use the user created function, `fetch_sales_data_using_sqlite_query` 或者根據用戶請求使用預構建的程式碼解釋器。
```python
import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from fecth_sales_data_functions import fetch_sales_data_using_sqlite_query # fetch_sales_data_using_sqlite_query function which can be found in a fecth_sales_data_functions.py file.
from azure.ai.projects.models import ToolSet, FunctionTool, CodeInterpreterTool
project_client = AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(),
conn_str=os.environ["PROJECT_CONNECTION_STRING"],
)
# Initialize function calling agent with the fetch_sales_data_using_sqlite_query function and adding it to the toolset
fetch_data_function = FunctionTool(fetch_sales_data_using_sqlite_query)
toolset = ToolSet()
toolset.add(fetch_data_function)
# Initialize Code Interpreter tool and adding it to the toolset.
code_interpreter = code_interpreter = CodeInterpreterTool()
toolset = ToolSet()
toolset.add(code_interpreter)
agent = project_client.agents.create_agent(
model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent",
toolset=toolset
)
```
## 使用工具使用設計模式構建可信任 AI 代理的特別考量是什麼?
LLM 動態生成的 SQL 一個常見的問題是安全性,尤其是 SQL 注入或惡意行為的風險,例如刪除或篡改資料庫。儘管這些擔憂是合理的,但可以通過適當配置資料庫訪問權限有效減輕。對於大多數資料庫,這涉及將資料庫配置為只讀模式。對於像 PostgreSQL 或 Azure SQL 這樣的資料庫服務,應為應用程式分配只讀(SELECT)角色。
在安全環境中運行應用進一步增強了保護。在企業場景中,數據通常從操作系統中提取並轉換為只讀資料庫或數據倉庫,並配有用戶友好的架構。這種方法確保了數據的安全性、性能優化和可訪問性,並且應用程式具有受限的只讀訪問權限。
## 其他資源
- [Azure AI Agents Service Workshop](https://microsoft.github.io/build-your-first-agent-with-azure-ai-agent-service-workshop/)
- [Contoso Creative Writer Multi-Agent Workshop](https://github.com/Azure-Samples/contoso-creative-writer/tree/main/docs/workshop)
- [Semantic Kernel Function Calling Tutorial](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions)
- [Semantic Kernel Code Interpreter](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py)
- [Autogen Tools](https://microsoft.github.io/autogen/dev/user-guide/core-user-guide/components/tools.html)
```
**免責聲明**:
本文件是使用基於機器的人工智能翻譯服務進行翻譯的。儘管我們努力確保翻譯的準確性,但請注意,自動翻譯可能會包含錯誤或不準確之處。應以原始語言的文件作為權威來源。對於關鍵信息,建議使用專業的人工作翻譯。我們對因使用此翻譯而引起的任何誤解或誤讀不承擔責任。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/04-tool-use/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/04-tool-use/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 12690
} |
# Agentic RAG
本課程提供對「代理型檢索增強生成」(Agentic Retrieval-Augmented Generation, Agentic RAG)的全面概述。這是一種新興的 AI 範式,讓大型語言模型(LLM)在拉取外部資訊的同時,能夠自主規劃下一步行動。與傳統靜態的檢索後閱讀模式不同,Agentic RAG 包含對 LLM 的多次迭代調用,並穿插工具或函數調用以及結構化輸出。系統會評估結果、改進查詢、在必要時調用額外工具,並持續此循環直到找到滿意的解決方案。
## 課程介紹
本課程將涵蓋以下內容:
- **理解 Agentic RAG:** 了解這種 AI 新範式,讓大型語言模型(LLM)在拉取外部數據的同時,能夠自主規劃下一步行動。
- **掌握迭代式製作者-檢查者模式:** 理解 LLM 的迭代調用循環,穿插工具或函數調用以及結構化輸出,旨在提升正確性並處理格式不正確的查詢。
- **探索實際應用場景:** 找出 Agentic RAG 的亮點應用場景,例如以正確性為優先的環境、複雜的數據庫互動以及延伸工作流程。
## 學習目標
完成本課程後,您將能夠:
- **理解 Agentic RAG:** 學習這種新興 AI 範式,讓大型語言模型(LLM)在拉取外部數據的同時,能夠自主規劃下一步行動。
- **迭代式製作者-檢查者模式:** 掌握 LLM 的迭代調用循環,穿插工具或函數調用以及結構化輸出,旨在提升正確性並處理格式不正確的查詢。
- **掌控推理過程:** 理解系統如何自主掌控推理過程,決定解決問題的方法,而不依賴預先定義的路徑。
- **工作流程:** 瞭解代理型模型如何自主決定檢索市場趨勢報告、識別競爭對手數據、關聯內部銷售指標、綜合分析結果並評估策略。
- **迭代循環、工具整合與記憶:** 學習系統如何依賴循環互動模式,跨步驟維持狀態與記憶,避免重複循環並做出明智的決策。
- **處理失敗模式與自我修正:** 探索系統的強大自我修正機制,包括迭代和重新查詢、使用診斷工具以及依靠人類監督。
- **代理的界限:** 理解 Agentic RAG 的限制,聚焦於特定領域的自主性、基礎設施依賴以及對安全框架的遵守。
- **實際應用場景與價值:** 找出 Agentic RAG 的亮點應用場景,例如以正確性為優先的環境、複雜的數據庫互動以及延伸工作流程。
- **治理、透明性與信任:** 學習治理與透明性的重要性,包括可解釋的推理、偏差控制以及人類監督。
## 什麼是 Agentic RAG?
代理型檢索增強生成(Agentic Retrieval-Augmented Generation, Agentic RAG)是一種新興的 AI 範式,讓大型語言模型(LLM)在拉取外部資訊的同時,能夠自主規劃下一步行動。與靜態的檢索後閱讀模式不同,Agentic RAG 包含對 LLM 的多次迭代調用,並穿插工具或函數調用以及結構化輸出。系統會評估結果、改進查詢、在必要時調用額外工具,並持續此循環直到找到滿意的解決方案。
這種迭代的「製作者-檢查者」操作模式能提升正確性,處理結構化數據庫(例如 NL2SQL)中格式不正確的查詢,並確保高品質的結果。系統會主動掌控推理過程,重寫失敗的查詢、選擇不同的檢索方法並整合多種工具,例如 Azure AI Search 的向量檢索、SQL 數據庫或自定義 API,然後再完成答案。代理型系統的獨特之處在於它能自主掌控推理過程,而不是依賴預定義的路徑。
## 定義代理型檢索增強生成(Agentic RAG)
代理型檢索增強生成(Agentic RAG)是一種 AI 開發的新興範式,讓 LLM 不僅能從外部數據來源中拉取資訊,還能自主規劃下一步行動。與靜態的檢索後閱讀模式或精心編排的提示序列不同,Agentic RAG 包含一個迭代循環,穿插工具或函數調用以及結構化輸出。在每個階段,系統會評估已獲得的結果,決定是否改進查詢、調用額外工具,並持續此循環直到達成滿意的解決方案。
這種迭代的「製作者-檢查者」操作模式旨在提升正確性,處理結構化數據庫中格式不正確的查詢(例如 NL2SQL),並確保平衡且高品質的結果。與僅依賴精心設計的提示鏈不同,系統會主動掌控推理過程。它能重寫失敗的查詢、選擇不同的檢索方法,並整合多種工具,例如 Azure AI Search 的向量檢索、SQL 數據庫或自定義 API,然後再完成答案。這樣可以減少對過於複雜的編排框架的需求,僅需一個相對簡單的「LLM 調用 → 工具使用 → LLM 調用 → …」循環即可產生高級且有根據的輸出。

## 掌控推理過程
讓系統成為「代理型」的關鍵特性是其自主掌控推理過程的能力。傳統的 RAG 實現通常依賴人類預先定義的路徑:例如指定檢索什麼內容以及何時檢索的思路鏈。
但真正的代理型系統能內部決定如何解決問題。它不只是執行腳本,而是基於找到的資訊質量,自主決定步驟的順序。
例如,當被要求制定產品發佈策略時,它不會僅依賴一個列出整個研究和決策工作流程的提示,而是自主決定:
1. 使用 Bing Web Grounding 檢索當前市場趨勢報告。
2. 利用 Azure AI Search 識別相關的競爭對手數據。
3. 使用 Azure SQL Database 關聯歷史內部銷售指標。
4. 通過 Azure OpenAI Service 將調研結果綜合成一個連貫的策略。
5. 評估策略中的漏洞或不一致之處,必要時啟動新一輪的檢索。
所有這些步驟——改進查詢、選擇數據來源、反覆迭代直到「滿意」為止——都是由模型決定的,而非人類預先編寫的腳本。
## 迭代循環、工具整合與記憶

代理型系統依賴於一種循環互動模式:
- **初始調用:** 用戶的目標(即用戶提示)被提交給 LLM。
- **工具調用:** 如果模型發現缺少資訊或指令不明確,它會選擇一個工具或檢索方法,例如向量數據庫查詢(例如 Azure AI Search 的混合搜索)或結構化 SQL 調用,來獲取更多上下文。
- **評估與改進:** 在審查返回的數據後,模型決定這些資訊是否足夠。如果不足,它會改進查詢、嘗試不同的工具或調整方法。
- **重複直到滿意:** 此循環持續進行,直到模型認為它擁有足夠的清晰度和證據來提供一個最終的、經過充分推理的回應。
- **記憶與狀態:** 系統會跨步驟維持狀態和記憶,因此可以回憶起之前的嘗試及其結果,避免重複循環並在過程中做出更明智的決策。
隨著時間的推移,這種模式會形成一種逐步深入理解的感覺,讓模型能夠在無需人類不斷干預或重新編寫提示的情況下,完成複雜的多步任務。
## 處理失敗模式與自我修正
Agentic RAG 的自主性還包括強大的自我修正機制。當系統遇到死胡同,例如檢索到無關文件或遇到格式不正確的查詢時,它可以:
- **迭代與重新查詢:** 模型不會返回低價值的回應,而是嘗試新的搜索策略、重寫數據庫查詢或查找替代數據集。
- **使用診斷工具:** 系統可能調用額外的功能來幫助它調試推理步驟或確認檢索數據的正確性。像 Azure AI Tracing 這樣的工具對於實現健全的可觀察性和監控至關重要。
- **依靠人類監督:** 在高風險或多次失敗的場景中,模型可能會標記不確定性並請求人類指導。一旦人類提供了糾正性反饋,模型可以在後續操作中吸收這一教訓。
這種迭代且動態的方法讓模型能夠持續改進,確保它不僅僅是一個「一次性」的系統,而是一個能夠在特定會話中從錯誤中學習的系統。

## 代理的界限
儘管在任務中具備自主性,Agentic RAG 並不等同於通用人工智慧(AGI)。其「代理型」能力被限制在開發者提供的工具、數據來源和政策範圍內。它無法自行創建工具或超越既定的領域邊界,而是擅長動態編排現有資源。
與更高級的 AI 形式相比,其主要差異包括:
1. **特定領域的自主性:** Agentic RAG 系統專注於在已知領域內實現用戶定義的目標,採用查詢重寫或工具選擇等策略來提升結果。
2. **依賴基礎設施:** 系統的能力取決於開發者整合的工具和數據。它無法在沒有人工干預的情況下超越這些邊界。
3. **遵守安全框架:** 道德指導方針、合規規則和業務政策仍然至關重要。代理的自由度始終受到安全措施和監管機制的限制(希望如此?)。
## 實際應用場景與價值
Agentic RAG 在需要迭代改進和高精度的場景中表現尤為突出:
1. **以正確性為優先的環境:** 在合規檢查、法規分析或法律研究中,代理型模型可以反覆驗證事實、諮詢多個來源並重寫查詢,直到產生經過充分審核的答案。
2. **複雜的數據庫互動:** 當處理結構化數據時,查詢可能經常失敗或需要調整,系統可以利用 Azure SQL 或 Microsoft Fabric OneLake 自主改進查詢,確保最終檢索與用戶意圖一致。
3. **延伸工作流程:** 當新的資訊浮現時,長時間運行的會話可能會隨之演變。Agentic RAG 能夠持續整合新數據,並根據對問題空間的進一步了解調整策略。
## 治理、透明性與信任
隨著這些系統在推理上變得更加自主,治理與透明性至關重要:
- **可解釋的推理:** 模型可以提供一個查詢記錄,包括它進行的查詢、諮詢的來源以及它採取的推理步驟。像 Azure AI Content Safety 和 Azure AI Tracing / GenAIOps 這樣的工具有助於保持透明性並減少風險。
- **偏差控制與平衡檢索:** 開發者可以調整檢索策略以確保考慮到平衡且具代表性的數據來源,並定期審核輸出以檢測偏差或偏向模式,這對於使用 Azure Machine Learning 的高級數據科學組織尤其重要。
- **人類監督與合規:** 對於敏感任務,人類審核仍然是必要的。Agentic RAG 不會取代人類在高風險決策中的判斷,而是通過提供經過充分審核的選項來輔助人類。
擁有能夠清楚記錄操作的工具至關重要。否則,調試多步驟過程可能會非常困難。以下是 Literal AI(Chainlit 背後的公司)提供的一個代理運行範例:


## 結論
Agentic RAG 代表了 AI 系統處理複雜數據密集型任務的一種自然演進。通過採用循環互動模式、自主選擇工具並改進查詢直到達到高品質結果,該系統超越了靜態的提示執行,成為一個更具適應性和上下文感知的決策者。儘管仍然受到人類定義的基礎設施和道德準則的約束,這些代理型能力為企業和最終用戶帶來了更豐富、更動態、最終更有用的 AI 互動。
## 其他資源
- 使用 Azure OpenAI Service 實現檢索增強生成(RAG):學習如何使用您自己的數據與 Azure OpenAI Service。[此 Microsoft Learn 模組提供了實現 RAG 的全面指南](https://learn.microsoft.com/training/modules/use-own-data-azure-openai)
- 使用 Azure AI Foundry 評估生成式 AI 應用:本文涵蓋了在公開數據集上評估和比較模型的方法,包括 [代理型 AI 應用與 RAG 架構](https://learn.microsoft.com/azure/ai-studio/concepts/evaluation-approach-gen-ai)
- [什麼是 Agentic RAG | Weaviate](https://weaviate.io/blog/what-is-agentic-rag)
- [Agentic RAG:代理型檢索增強生成的完整指南 – generation RAG 的新聞](https://ragaboutit.com/agentic-rag-a-complete-guide-to-agent-based-retrieval-augmented-generation/)
- [Agentic RAG:通過查詢重構和自查提升 RAG!Hugging Face 開源 AI 實用手冊](https://huggingface.co/learn/cookbook/agent_rag)
- [為 RAG 添加代理層](https://youtu.be/aQ4yQXeB1Ss?si=2HUqBzHoeB5tR04U)
- [知識助理的未來:Jerry Liu](https://www.youtube.com/watch?v=zeAyuLc_f3Q&t=244s)
- [如何構建 Agentic RAG 系統](https://www.youtube.com/watch?v=AOSjiXP1jmQ)
- [使用 Azure AI Foundry Agent Service 擴展您的 AI 代理](https://ignite.microsoft.com/sessions/BRK102?source=sessions)
### 學術論文
- [2303.17651 Self-Refine: Iterative Refinement with Self-Feedback](https://arxiv.org/abs/2303.17651)
- [2303.11366 Reflexion: Language Agents with Verbal Reinforcement Learning](https://arxiv.org/abs/2303.11366)
- [2305.11738 CRITIC: Large Language Models Can Self-Correct with Tool-Interactive Critiquing](https://arxiv.org/abs/2305.11738)
**免責聲明**:
本文件使用基於機器的人工智能翻譯服務進行翻譯。儘管我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原始語言的文件為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對因使用本翻譯而產生的任何誤解或錯誤解釋不承擔責任。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/05-agentic-rag/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/05-agentic-rag/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 6745
} |
# 建立可信賴的 AI 代理
## 介紹
本課程將涵蓋以下內容:
- 如何構建和部署安全且有效的 AI 代理
- 開發 AI 代理時的重要安全考量
- 在開發 AI 代理時如何維護數據和用戶隱私
## 學習目標
完成本課程後,您將能夠:
- 識別並減輕在創建 AI 代理時可能面臨的風險。
- 實施安全措施,確保數據和訪問權限得到妥善管理。
- 創建能維護數據隱私並提供高品質用戶體驗的 AI 代理。
## 安全性
首先,我們來看看如何構建安全的代理應用程序。安全性意味著 AI 代理能按照設計執行其功能。作為代理應用程序的開發者,我們有一些方法和工具可以最大限度地提高安全性:
### 構建 Meta Prompt 系統
如果您曾使用大型語言模型(LLMs)開發過 AI 應用程序,您會知道設計一個穩健的系統提示或系統訊息的重要性。這些提示負責設定元規則、指令和指南,確保 LLM 能夠正確地與用戶和數據互動。
對於 AI 代理來說,系統提示更為重要,因為 AI 代理需要高度具體的指令來完成我們設計的任務。
為了創建可擴展的系統提示,我們可以使用 Meta Prompt 系統來構建應用中的一個或多個代理:

#### 步驟 1:創建 Meta 或模板提示
Meta Prompt 將由 LLM 用來生成我們所創建代理的系統提示。我們將其設計為模板,以便在需要時能高效地創建多個代理。
以下是一個我們提供給 LLM 的 Meta Prompt 範例:
```plaintext
You are an expert at creating AI agent assitants.
You will be provided a company name, role, responsibilites and other
information that you will use to provide a system prompt for.
To create the system prompt, be descriptive as possible and provide a structure that a system using an LLM can better understand the role and responsibilites of the AI assistant.
```
#### 步驟 2:創建基礎提示
下一步是創建一個基礎提示來描述 AI 代理。您應包括代理的角色、代理將完成的任務以及代理的其他職責。
以下是一個範例:
```plaintext
You are a travel agent for Contoso Travel with that is great at booking flights for customers. To help customers you can perform the following tasks: lookup available flights, book flights, ask for preferences in seating and times for flights, cancel any previously booked flights and alert customers on any delays or cancellations of flights.
```
#### 步驟 3:將基礎提示提供給 LLM
現在,我們可以通過將 Meta Prompt 作為系統提示並添加我們的基礎提示來優化這個提示。
這將生成一個更適合指導我們 AI 代理的提示:
```markdown
**Company Name:** Contoso Travel
**Role:** Travel Agent Assistant
**Objective:**
You are an AI-powered travel agent assistant for Contoso Travel, specializing in booking flights and providing exceptional customer service. Your main goal is to assist customers in finding, booking, and managing their flights, all while ensuring that their preferences and needs are met efficiently.
**Key Responsibilities:**
1. **Flight Lookup:**
- Assist customers in searching for available flights based on their specified destination, dates, and any other relevant preferences.
- Provide a list of options, including flight times, airlines, layovers, and pricing.
2. **Flight Booking:**
- Facilitate the booking of flights for customers, ensuring that all details are correctly entered into the system.
- Confirm bookings and provide customers with their itinerary, including confirmation numbers and any other pertinent information.
3. **Customer Preference Inquiry:**
- Actively ask customers for their preferences regarding seating (e.g., aisle, window, extra legroom) and preferred times for flights (e.g., morning, afternoon, evening).
- Record these preferences for future reference and tailor suggestions accordingly.
4. **Flight Cancellation:**
- Assist customers in canceling previously booked flights if needed, following company policies and procedures.
- Notify customers of any necessary refunds or additional steps that may be required for cancellations.
5. **Flight Monitoring:**
- Monitor the status of booked flights and alert customers in real-time about any delays, cancellations, or changes to their flight schedule.
- Provide updates through preferred communication channels (e.g., email, SMS) as needed.
**Tone and Style:**
- Maintain a friendly, professional, and approachable demeanor in all interactions with customers.
- Ensure that all communication is clear, informative, and tailored to the customer's specific needs and inquiries.
**User Interaction Instructions:**
- Respond to customer queries promptly and accurately.
- Use a conversational style while ensuring professionalism.
- Prioritize customer satisfaction by being attentive, empathetic, and proactive in all assistance provided.
**Additional Notes:**
- Stay updated on any changes to airline policies, travel restrictions, and other relevant information that could impact flight bookings and customer experience.
- Use clear and concise language to explain options and processes, avoiding jargon where possible for better customer understanding.
This AI assistant is designed to streamline the flight booking process for customers of Contoso Travel, ensuring that all their travel needs are met efficiently and effectively.
```
#### 步驟 4:迭代與改進
Meta Prompt 系統的價值在於能夠更輕鬆地擴展多個代理的提示創建過程,並隨著時間的推移改進您的提示。很少有提示能在第一次就完全滿足您的使用需求。通過對基礎提示進行小幅調整並通過系統運行,您可以比較和評估結果以進行改進。
## 理解威脅
為了構建可信賴的 AI 代理,理解並減輕 AI 代理可能面臨的風險和威脅是非常重要的。接下來,我們將探討部分 AI 代理可能遭遇的威脅以及如何更好地規劃和應對。

### 任務與指令
**描述:** 攻擊者試圖通過提示或操縱輸入來更改 AI 代理的指令或目標。
**緩解措施:** 執行驗證檢查和輸入過濾,以檢測在被 AI 代理處理之前可能存在的危險提示。由於這類攻擊通常需要與代理頻繁交互,限制對話輪次也是防止此類攻擊的另一種方法。
### 訪問關鍵系統
**描述:** 如果 AI 代理可以訪問存儲敏感數據的系統和服務,攻擊者可能會破壞代理與這些服務之間的通信。這些可能是直接攻擊或通過代理間接獲取這些系統信息的嘗試。
**緩解措施:** AI 代理應僅在必要時訪問系統,以防止此類攻擊。代理與系統之間的通信也應保持安全。實施身份驗證和訪問控制是保護此類信息的另一種方法。
### 資源與服務超載
**描述:** AI 代理可以訪問不同的工具和服務來完成任務。攻擊者可能利用這一點通過 AI 代理向這些服務發送大量請求,導致系統故障或高額成本。
**緩解措施:** 實施策略限制 AI 代理向服務發送請求的數量。限制對話輪次和 AI 代理的請求數量也是防止此類攻擊的另一種方法。
### 知識庫污染
**描述:** 這類攻擊不直接針對 AI 代理,而是針對代理將使用的知識庫和其他服務。這可能涉及破壞代理用於完成任務的數據或信息,導致用戶收到偏頗或非預期的回應。
**緩解措施:** 定期驗證 AI 代理在工作流中使用的數據。確保這些數據的訪問權限是安全的,並且只有可信任的人員才能更改,以避免此類攻擊。
### 錯誤連鎖效應
**描述:** AI 代理會訪問各種工具和服務來完成任務。由攻擊者引發的錯誤可能導致代理連接的其他系統失效,使得攻擊範圍擴大且更難排查。
**緩解措施:** 避免此類情況的一種方法是讓 AI 代理在受限環境中運行,例如在 Docker 容器中執行任務,以防止直接系統攻擊。為某些系統出現錯誤時創建備援機制和重試邏輯,也是防止更大範圍系統故障的另一種方法。
## 人類介入
另一種構建可信賴 AI 代理系統的有效方式是引入人類介入(Human-in-the-loop)。這種方式創建了一個流程,允許用戶在代理運行期間提供反饋。用戶本質上充當多代理系統中的一個代理,通過批准或終止正在運行的流程來參與。

以下是一段使用 AutoGen 的代碼範例,展示如何實現這一概念:
```python
# Create the agents.
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
assistant = AssistantAgent("assistant", model_client=model_client)
user_proxy = UserProxyAgent("user_proxy", input_func=input) # Use input() to get user input from console.
# Create the termination condition which will end the conversation when the user says "APPROVE".
termination = TextMentionTermination("APPROVE")
# Create the team.
team = RoundRobinGroupChat([assistant, user_proxy], termination_condition=termination)
# Run the conversation and stream to the console.
stream = team.run_stream(task="Write a 4-line poem about the ocean.")
# Use asyncio.run(...) when running in a script.
await Console(stream)
```
**免責聲明**:
本文檔是使用機器翻譯人工智慧服務進行翻譯的。儘管我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原始語言的文件為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而產生的任何誤解或誤讀不承擔責任。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/06-building-trustworthy-agents/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/06-building-trustworthy-agents/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 7013
} |
# 規劃設計
## 簡介
本課程將涵蓋以下內容:
* 定義明確的整體目標,並將複雜任務分解為可管理的小任務。
* 利用結構化輸出來實現更可靠且可機器讀取的回應。
* 採用事件驅動的方法來處理動態任務及應對意外輸入。
## 學習目標
完成本課程後,你將能夠:
* 確認並設定 AI 代理的整體目標,確保它明確知道需要完成的工作。
* 將複雜任務分解為可管理的子任務,並將它們組織成邏輯順序。
* 為代理配備適當的工具(例如搜尋工具或數據分析工具),決定何時及如何使用這些工具,並處理可能出現的意外情況。
* 評估子任務的結果、衡量性能,並通過反覆迭代改進最終輸出。
## 定義整體目標並分解任務

大多數現實世界的任務都過於複雜,無法一步完成。AI 代理需要一個簡潔的目標來指導其規劃和行動。例如,考慮以下目標:
"生成一個三天的旅行行程。"
雖然這個目標表述簡單,但仍需進一步細化。目標越清晰,代理(以及任何人類協作者)就越能專注於實現正確的結果,例如創建一個包含航班選項、酒店推薦和活動建議的完整行程。
### 任務分解
大型或複雜的任務在被分解為更小的、目標導向的子任務後會更易管理。
以旅行行程為例,你可以將目標分解為:
* 航班預訂
* 酒店預訂
* 租車
* 個性化定制
每個子任務可以由專門的代理或流程處理。一個代理可能專注於搜尋最佳航班優惠,另一個代理則專注於酒店預訂,依此類推。一個協調或“下游”代理可以將這些結果整合成一個連貫的行程提供給最終用戶。
這種模組化方法還允許逐步改進。例如,你可以增加專門的代理來提供餐飲推薦或當地活動建議,並隨著時間推進不斷完善行程。
### 結構化輸出
大型語言模型(LLMs)可以生成結構化輸出(例如 JSON),這更方便下游代理或服務進行解析和處理。這在多代理上下文中特別有用,因為我們可以在規劃輸出完成後執行這些任務。請參考這篇 [blogpost](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/cookbook/structured-output-agent.html) 以快速了解。
以下是一段示範簡單規劃代理如何將目標分解為子任務並生成結構化計劃的 Python 程式碼片段:
### 使用多代理協作的規劃代理
在此範例中,一個語義路由代理接收到用戶請求(例如,“我需要一個旅行的酒店計劃。”)。
規劃器接下來會執行以下步驟:
* 接收酒店計劃:規劃器接收用戶的訊息,並根據系統提示(包括可用代理的詳細資訊)生成結構化的旅行計劃。
* 列出代理及其工具:代理註冊表保存了代理的清單(例如航班、酒店、租車和活動代理)以及它們提供的功能或工具。
* 將計劃路由至相應的代理:根據子任務數量,規劃器會將訊息直接發送給專門代理(適用於單一任務情境)或通過群組聊天管理器協調多代理合作。
* 總結結果:最後,規劃器為清晰起見總結生成的計劃。
以下是說明這些步驟的 Python 程式碼範例:
```python
from pydantic import BaseModel
from enum import Enum
from typing import List, Optional, Union
class AgentEnum(str, Enum):
FlightBooking = "flight_booking"
HotelBooking = "hotel_booking"
CarRental = "car_rental"
ActivitiesBooking = "activities_booking"
DestinationInfo = "destination_info"
DefaultAgent = "default_agent"
GroupChatManager = "group_chat_manager"
# Travel SubTask Model
class TravelSubTask(BaseModel):
task_details: str
assigned_agent: AgentEnum # we want to assign the task to the agent
class TravelPlan(BaseModel):
main_task: str
subtasks: List[TravelSubTask]
is_greeting: bool
import json
import os
from typing import Optional
from autogen_core.models import UserMessage, SystemMessage, AssistantMessage
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient
# Create the client with type-checked environment variables
client = AzureOpenAIChatCompletionClient(
azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
)
from pprint import pprint
# Define the user message
messages = [
SystemMessage(content="""You are an planner agent.
Your job is to decide which agents to run based on the user's request.
Below are the available agents specialised in different tasks:
- FlightBooking: For booking flights and providing flight information
- HotelBooking: For booking hotels and providing hotel information
- CarRental: For booking cars and providing car rental information
- ActivitiesBooking: For booking activities and providing activity information
- DestinationInfo: For providing information about destinations
- DefaultAgent: For handling general requests""", source="system"),
UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melbourne", source="user"),
]
response = await client.create(messages=messages, extra_create_args={"response_format": TravelPlan})
# Ensure the response content is a valid JSON string before loading it
response_content: Optional[str] = response.content if isinstance(response.content, str) else None
if response_content is None:
raise ValueError("Response content is not a valid JSON string")
# Print the response content after loading it as JSON
pprint(json.loads(response_content))
```
以下是上述程式碼的輸出,你可以使用這個結構化輸出路由到 `assigned_agent`,並向最終用戶總結旅行計劃。
```json
{
"is_greeting": "False",
"main_task": "Plan a family trip from Singapore to Melbourne.",
"subtasks": [
{
"assigned_agent": "flight_booking",
"task_details": "Book round-trip flights from Singapore to Melbourne."
},
{
"assigned_agent": "hotel_booking",
"task_details": "Find family-friendly hotels in Melbourne."
},
{
"assigned_agent": "car_rental",
"task_details": "Arrange a car rental suitable for a family of four in Melbourne."
},
{
"assigned_agent": "activities_booking",
"task_details": "List family-friendly activities in Melbourne."
},
{
"assigned_agent": "destination_info",
"task_details": "Provide information about Melbourne as a travel destination."
}
]
}
```
包含上述程式碼範例的範例筆記本可在 [這裡](../../../07-planning-design/code_samples/07-autogen.ipynb) 獲取。
### 迭代規劃
某些任務需要反覆調整或重新規劃,其中一個子任務的結果可能會影響下一步。例如,如果代理在預訂航班時發現了意外的數據格式,它可能需要調整策略,然後再進行酒店預訂。
此外,用戶反饋(例如人類決定更喜歡早班航班)也可能觸發部分重新規劃。這種動態、迭代的方法確保最終解決方案能夠符合現實約束和不斷變化的用戶偏好。
例如程式碼:
```python
from autogen_core.models import UserMessage, SystemMessage, AssistantMessage
#.. same as previous code and pass on the user history, current plan
messages = [
SystemMessage(content="""You are a planner agent to optimize the
Your job is to decide which agents to run based on the user's request.
Below are the available agents specialised in different tasks:
- FlightBooking: For booking flights and providing flight information
- HotelBooking: For booking hotels and providing hotel information
- CarRental: For booking cars and providing car rental information
- ActivitiesBooking: For booking activities and providing activity information
- DestinationInfo: For providing information about destinations
- DefaultAgent: For handling general requests""", source="system"),
UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melboune", source="user"),
AssistantMessage(content=f"Previous travel plan - {TravelPlan}", source="assistant")
]
# .. re-plan and send the tasks to respective agents
```
如需更全面的規劃,請參考 Magnetic One [Blogpost](https://www.microsoft.com/research/articles/magentic-one-a-generalist-multi-agent-system-for-solving-complex-tasks),以了解如何解決複雜任務。
## 總結
在本文中,我們探討了一個如何創建規劃器的範例,該規劃器可以動態選擇定義的可用代理。規劃器的輸出分解了任務並分配給代理進行執行。假設代理可以訪問執行任務所需的功能/工具。除了代理之外,你還可以包含其他模式,例如反思、摘要器、輪詢聊天,以進一步自定義。
## 其他資源
* 使用 o1 推理模型在規劃複雜任務中已證明相當先進——TODO: 分享範例?
* Autogen Magentic One - 一個通用型多代理系統,用於解決複雜任務,並在多個具有挑戰性的代理基準測試中取得了令人印象深刻的成果。參考資料:[autogen-magentic-one](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-magentic-one)。在此實現中,協作器創建特定任務的計劃,並將這些任務委派給可用的代理。除了規劃之外,協作器還採用跟蹤機制來監控任務進度並在需要時重新規劃。
**免責聲明**:
本文件是使用機器翻譯AI服務進行翻譯的。儘管我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文文件作為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或錯誤解釋不承擔責任。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/07-planning-design/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/07-planning-design/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 7270
} |
# 多代理設計模式
當你開始進行涉及多個代理的專案時,就需要考慮多代理設計模式。然而,什麼時候需要切換到多代理模式,以及這樣做的優勢,可能並不馬上明顯。
## 簡介
在本課程中,我們將解答以下問題:
- 多代理模式適用於哪些場景?
- 與單一代理執行多任務相比,使用多代理有哪些優勢?
- 實現多代理設計模式的基礎要素是什麼?
- 如何了解多個代理之間的互動情況?
## 學習目標
完成本課程後,你應該能夠:
- 識別多代理模式適用的場景。
- 理解使用多代理相較於單一代理的優勢。
- 掌握實現多代理設計模式的基礎要素。
### 大局觀
*多代理是一種設計模式,讓多個代理共同合作以達成共同目標*。
這種模式廣泛應用於各種領域,包括機器人技術、自主系統和分散式計算。
## 多代理模式適用的場景
那麼,哪些場景適合使用多代理模式呢?答案是,在許多情況下,採用多代理模式是有益的,尤其是以下幾種情況:
- **大量工作負載**:將龐大的工作負載分解成較小的任務,並分配給不同的代理,可以實現並行處理,加快完成速度。例如,大型數據處理任務就適合這種模式。
- **複雜任務**:與大量工作負載類似,複雜任務也可以被分解成小的子任務,並分配給專注於特定任務的代理。例如,在自動駕駛車輛中,不同的代理可以負責導航、障礙物檢測和與其他車輛的通信。
- **多樣化專業技能**:不同的代理可以擁有不同的專業技能,這使得它們能比單一代理更有效地處理任務的不同方面。例如,在醫療領域,代理可以負責診斷、治療計畫和病人監測。
## 使用多代理相較於單一代理的優勢
單一代理系統在處理簡單任務時可能運作良好,但對於更複雜的任務,使用多代理能提供多項優勢:
- **專業化**:每個代理可以專注於特定任務。如果單一代理缺乏專業化,可能會在面對複雜任務時感到困惑,甚至執行不適合它的任務。
- **可擴展性**:透過增加更多代理來擴展系統,比單一代理承擔過多負載更容易。
- **容錯性**:如果某個代理失效,其他代理仍能繼續運作,確保系統的可靠性。
舉個例子,假設幫用戶預訂旅行。一個單一代理系統需要處理整個預訂流程,包括找航班、訂酒店和租車。這樣的系統可能會變得複雜且難以維護。而多代理系統則可以讓不同的代理專注於找航班、訂酒店和租車,這樣系統更模組化、易於維護且具擴展性。
這可以類比為夫妻檔經營的小型旅行社與連鎖經營的旅行社之間的差異。夫妻檔可能由一個人處理所有旅行預訂細節,而連鎖經營則會讓不同人員專注於不同的預訂任務。
## 實現多代理設計模式的基礎要素
在實現多代理設計模式之前,你需要了解構成這種模式的基礎要素。
以用戶預訂旅行為例,以下是可能的基礎要素:
- **代理通信**:負責找航班、訂酒店和租車的代理需要彼此通信,分享用戶的偏好和限制。例如,找航班的代理需要與訂酒店的代理通信,確保酒店的入住日期與航班日期一致。這意味著你需要決定*哪些代理共享資訊以及如何共享*。
- **協調機制**:代理需要協調行動以滿足用戶的偏好和限制。例如,用戶可能偏好靠近機場的酒店,但租車可能只能在機場取得。這就需要訂酒店的代理與租車的代理協調,以滿足用戶需求。這意味著你需要決定*代理如何協調行動*。
- **代理架構**:代理需要具備內部結構,以便做出決策並從與用戶的互動中學習。例如,找航班的代理需要能決定推薦哪個航班給用戶。這意味著你需要決定*代理如何做決策並從互動中學習*。例如,找航班的代理可以使用機器學習模型,根據用戶過去的偏好來推薦航班。
- **多代理互動的可見性**:需要能夠了解多個代理之間的互動情況。這意味著需要有工具和技術來追蹤代理的活動和互動,可能包括日誌記錄、監控工具、可視化工具以及效能指標。
- **多代理模式**:可以選擇不同的架構模式來實現多代理系統,例如集中式、分散式或混合式架構。需要根據具體需求選擇合適的模式。
- **人機協作**:在多數情況下,人類仍需參與其中,因此需要指導代理何時尋求人類的介入。例如,用戶可能會要求推薦特定的酒店或航班,或在預訂前需要確認。
## 多代理互動的可見性
了解多個代理之間的互動情況至關重要,這對於調試、優化以及確保整體系統的效能都非常必要。為此,需要有工具和技術來追蹤代理的活動和互動。例如:
- **日誌記錄與監控工具**:記錄每個代理的行動。例如,記錄代理採取的行動、行動時間及結果。這些資訊可以用於調試和優化。
- **可視化工具**:使用圖形化方式直觀展示代理之間的互動。例如,可以用一個圖表展示代理之間的資訊流,幫助識別瓶頸或系統中的低效部分。
- **效能指標**:追蹤多代理系統的效能。例如,完成任務所需的時間、每單位時間內完成的任務數量,以及代理推薦的準確性。這些資料有助於找出改進的方向。
## 多代理模式
以下是幾個可用於構建多代理應用的具體模式:
### 群組聊天模式
此模式適用於需要創建多代理群組聊天應用的情況,例如團隊協作、客戶支持和社交網絡。
在這種模式中,每個代理代表群組聊天中的一位用戶,並通過消息協議交換訊息。代理可以向群組發送消息、接收消息並回應其他代理的消息。
該模式可以使用集中式架構(所有消息通過中央伺服器傳遞)或分散式架構(代理之間直接交換消息)來實現。

### 任務交接模式
此模式適用於需要創建多代理應用,讓代理之間能夠交接任務的情況。
典型用例包括客戶支持、任務管理和工作流程自動化。
在這種模式中,每個代理代表一個任務或工作流程中的一個步驟,代理可以根據預定規則將任務交接給其他代理。

### 協同過濾模式
此模式適用於需要創建多代理應用,讓多個代理合作為用戶提供推薦的情況。
使用多個代理合作的原因在於,每個代理可以具備不同的專業知識,並以不同方式為推薦過程做出貢獻。
例如,用戶希望獲得股市最佳股票的推薦:
- **行業專家**:一個代理可能是特定行業的專家。
- **技術分析**:另一個代理可能專精於技術分析。
- **基本面分析**:還有一個代理可能專精於基本面分析。通過合作,這些代理可以為用戶提供更全面的推薦。

## 案例:退款流程
考慮一個客戶申請退款的場景,這個過程可能涉及許多代理,我們可以將其分為專屬於退款流程的代理和可以用於其他流程的通用代理。
**退款流程專屬代理**:
以下是一些可能涉及的代理:
- **客戶代理**:代表客戶,負責啟動退款流程。
- **賣家代理**:代表賣家,負責處理退款。
- **支付代理**:代表支付流程,負責將款項退還給客戶。
- **解決代理**:代表問題解決流程,負責處理退款過程中出現的問題。
- **合規代理**:代表合規流程,負責確保退款流程符合規定和政策。
**通用代理**:
這些代理可用於業務中的其他部分:
- **運輸代理**:代表運輸流程,負責將產品寄回賣家。此代理既可用於退款流程,也可用於購買流程中的運輸。
- **回饋代理**:代表回饋流程,負責收集客戶意見。回饋可隨時進行,而不僅限於退款流程。
- **升級代理**:代表升級流程,負責將問題升級至更高級別的支持。此類代理可用於任何需要升級問題的流程。
- **通知代理**:代表通知流程,負責在退款流程的各個階段向客戶發送通知。
- **分析代理**:代表分析流程,負責分析與退款相關的數據。
- **審核代理**:代表審核流程,負責檢查退款流程是否正確執行。
- **報告代理**:代表報告流程,負責生成退款流程的報告。
- **知識代理**:代表知識管理,負責維護與退款流程相關的知識庫。此代理也可以涵蓋其他業務領域。
- **安全代理**:代表安全流程,負責確保退款流程的安全性。
- **質量代理**:代表質量控制,負責確保退款流程的質量。
以上列舉了許多代理,既包括專屬於退款流程的代理,也包括可用於其他業務部分的通用代理。希望這能幫助你了解如何選擇在多代理系統中使用哪些代理。
## 作業
設計一個多代理系統來處理客戶支持流程。識別該流程中涉及的代理、它們的角色和職責,以及它們之間的互動方式。同時考慮專屬於客戶支持流程的代理以及可用於其他業務部分的通用代理。
> 在查看以下解答前,先自己思考一下,你可能需要的代理比想像中更多。
> TIP:考慮客戶支持流程的不同階段,並考慮任何系統可能需要的代理。
## 解答
[解答](./solution/solution.md)
## 知識檢查
問題:什麼時候應該考慮使用多代理?
- [] A1: 當你有少量工作負載和簡單任務時。
- [] A2: 當你有大量工作負載時。
- [] A3: 當你有簡單任務時。
[測驗解答](./solution/solution-quiz.md)
## 總結
在本課程中,我們探討了多代理設計模式,包括多代理適用的場景、使用多代理相較於單一代理的優勢、實現多代理設計模式的基礎要素,以及如何了解多個代理之間的互動情況。
## 其他資源
- [Autogen 設計模式](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/design-patterns/intro.html)
- [Agentic 設計模式](https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/)
**免責聲明**:
本文件使用機器翻譯服務進行翻譯。我們雖然努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。原文的母語版本應被視為權威來源。如需關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而產生的任何誤解或錯誤解釋概不負責。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/08-multi-agent/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/08-multi-agent/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 4644
} |
# AI 代理中的後設認知
## 介紹
歡迎來到有關 AI 代理後設認知的課程!本章節專為對 AI 代理如何思考自身思考過程感興趣的初學者設計。完成本課程後,您將了解關鍵概念,並掌握將後設認知應用於 AI 代理設計的實際範例。
## 學習目標
完成本課程後,您將能夠:
1. 理解代理定義中的推理循環影響。
2. 使用規劃和評估技術來幫助自我修正的代理。
3. 創建能夠操作程式碼以完成任務的代理。
## 後設認知介紹
後設認知是指涉及思考自身思考的高階認知過程。對於 AI 代理來說,這意味著能夠基於自我意識和過去經驗評估並調整其行動。
### 什麼是後設認知?
後設認知,或稱「思考的思考」,是一種高階認知過程,涉及對自身認知過程的自我意識和自我調節。在 AI 領域,後設認知使代理能夠評估和調整其策略和行動,從而提高解決問題和決策的能力。通過理解後設認知,您可以設計出更智能、更具適應性和效率的 AI 代理。
### 後設認知在 AI 代理中的重要性
後設認知在 AI 代理設計中具有多方面的重要性:

- **自我反思**:代理可以評估自身表現並找出需要改進的地方。
- **適應性**:代理可以根據過去的經驗和變化的環境調整策略。
- **錯誤修正**:代理可以自主檢測並修正錯誤,從而產生更準確的結果。
- **資源管理**:代理可以通過規劃和評估行動來優化資源的使用,如時間和計算能力。
## AI 代理的組成部分
在深入了解後設認知過程之前,必須了解 AI 代理的基本組成部分。AI 代理通常由以下部分組成:
- **角色**:代理的個性和特徵,定義其如何與用戶互動。
- **工具**:代理可以執行的功能和能力。
- **技能**:代理擁有的知識和專業技能。
這些組件協同工作,創建一個可以執行特定任務的「專業單元」。
**範例**:考慮一個旅行代理服務,該服務不僅計劃您的假期,還能根據實時數據和過去的客戶旅程經驗調整其路徑。
### 範例:旅行代理服務中的後設認知
假設您正在設計一個由 AI 驅動的旅行代理服務。這個代理「旅行代理」幫助用戶規劃假期。為了融入後設認知,旅行代理需要基於自我意識和過去的經驗評估並調整其行動。以下是後設認知可能發揮作用的方式:
#### 當前任務
當前任務是幫助用戶規劃巴黎之旅。
#### 完成任務的步驟
1. **收集用戶偏好**:詢問用戶有關旅行日期、預算、興趣(如博物館、美食、購物)及任何特定需求。
2. **檢索信息**:搜索符合用戶偏好的航班選項、住宿、景點和餐廳。
3. **生成建議**:提供包含航班詳情、酒店預訂和建議活動的個性化行程。
4. **根據反饋調整**:詢問用戶對建議的反饋並進行必要調整。
#### 所需資源
- 訪問航班和酒店預訂數據庫。
- 關於巴黎景點和餐廳的信息。
- 來自先前交互的用戶反饋數據。
#### 經驗與自我反思
旅行代理使用後設認知來評估其表現並從過去的經驗中學習。例如:
1. **分析用戶反饋**:旅行代理審查用戶反饋,以確定哪些建議受到好評,哪些不受歡迎,並相應地調整其未來建議。
2. **適應性**:如果用戶之前提到不喜歡人多的地方,旅行代理將避免在高峰時段推薦熱門旅遊景點。
3. **錯誤修正**:如果旅行代理在過去的預訂中出現錯誤,例如建議已滿房的酒店,它將學會在提供建議之前更嚴格地檢查可用性。
#### 實際開發範例
以下是旅行代理代碼如何融入後設認知的簡化範例:
```python
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):
# Search for flights, hotels, and attractions based on preferences
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)
# Analyze feedback and adjust future recommendations
self.user_preferences = adjust_preferences(self.user_preferences, feedback)
# Example usage
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)
```
#### 後設認知的重要性
- **自我反思**:代理可以分析其表現並找出需要改進的地方。
- **適應性**:代理可以根據反饋和變化的條件調整策略。
- **錯誤修正**:代理可以自主檢測並修正錯誤。
- **資源管理**:代理可以優化資源使用,例如時間和計算能力。
通過融入後設認知,旅行代理可以提供更個性化和準確的旅行建議,提升整體用戶體驗。
---
## 2. 代理中的規劃
規劃是 AI 代理行為的關鍵組成部分。它涉及在考慮當前狀態、資源和可能的障礙的情況下,概述實現目標所需的步驟。
### 規劃的要素
- **當前任務**:清楚地定義任務。
- **完成任務的步驟**:將任務分解為可管理的步驟。
- **所需資源**:確定必要的資源。
- **經驗**:利用過去的經驗來指導規劃。
**範例**:以下是旅行代理有效協助用戶規劃旅行所需採取的步驟:
### 旅行代理的步驟
1. **收集用戶偏好**
- 詢問用戶有關旅行日期、預算、興趣及任何特定需求的詳細信息。
- 範例:「您計劃什麼時候旅行?」、「您的預算範圍是多少?」、「您在假期中喜歡哪些活動?」
2. **檢索信息**
- 根據用戶偏好搜索相關旅行選項。
- **航班**:尋找符合用戶預算和偏好日期的可用航班。
- **住宿**:找到符合用戶對地點、價格和設施偏好的酒店或出租房產。
- **景點和餐廳**:識別符合用戶興趣的熱門景點、活動和餐飲選項。
3. **生成建議**
- 將檢索到的信息編輯成個性化行程。
- 提供詳細信息,例如航班選項、酒店預訂和建議活動,確保建議符合用戶偏好。
4. **向用戶展示行程**
- 與用戶分享建議的行程以供審查。
- 範例:「這是您巴黎之旅的建議行程,包括航班詳情、酒店預訂和推薦的活動及餐廳。請告訴我您的想法!」
5. **收集反饋**
- 詢問用戶對建議行程的反饋。
- 範例:「您喜歡這些航班選項嗎?」、「這家酒店是否符合您的需求?」、「有沒有您想添加或刪除的活動?」
6. **根據反饋調整**
- 根據用戶反饋修改行程。
- 對航班、住宿和活動建議進行必要更改,以更好地符合用戶偏好。
7. **最終確認**
- 向用戶展示更新後的行程以供最終確認。
- 範例:「我根據您的反饋進行了調整。這是更新後的行程。您看起來如何?」
8. **預訂並確認預約**
- 在用戶批准行程後,進行航班、住宿和任何預定活動的預訂。
- 向用戶發送確認詳細信息。
9. **提供持續支持**
- 在旅行前和旅行期間隨時協助用戶進行任何更改或額外請求。
- 範例:「如果您在旅行期間需要進一步協助,請隨時與我聯繫!」
### 範例互動
```python
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)
# Example usage within a booing request
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)
```
## 3. 修正型 RAG 系統
首先,讓我們了解 RAG 工具和預先加載上下文之間的區別:

### 檢索增強生成 (RAG)
RAG 將檢索系統與生成模型結合在一起。當進行查詢時,檢索系統從外部來源獲取相關文檔或數據,並將檢索到的信息用於增強生成模型的輸入。這有助於模型生成更準確且上下文相關的響應。
在 RAG 系統中,代理從知識庫中檢索相關信息,並使用它來生成適當的響應或行動。
### 修正型 RAG 方法
修正型 RAG 方法側重於使用 RAG 技術來修正錯誤並提高 AI 代理的準確性。這包括:
1. **提示技術**:使用特定提示來指導代理檢索相關信息。
2. **工具**:實施算法和機制,使代理能夠評估檢索信息的相關性並生成準確的響應。
3. **評估**:持續評估代理的表現並進行調整以提高其準確性和效率。
#### 範例:搜索代理中的修正型 RAG
考慮一個從網絡中檢索信息以回答用戶查詢的搜索代理。修正型 RAG 方法可能包括:
1. **提示技術**:根據用戶輸入制定搜索查詢。
2. **工具**:使用自然語言處理和機器學習算法對搜索結果進行排序和篩選。
3. **評估**:分析用戶反饋以識別並修正檢索信息中的不準確之處。
### 修正型 RAG 在旅行代理中的應用
修正型 RAG(檢索增強生成)增強了 AI 檢索和生成信息的能力,同時修正任何不準確之處。讓我們看看旅行代理如何使用修正型 RAG 方法來提供更準確和相關的旅行建議。這包括:
- **提示技術**:使用特定提示來指導代理檢索相關信息。
- **工具**:實施算法和機制,使代理能夠評估檢索信息的相關性並生成準確的響應。
- **評估**:持續評估代理的表現並進行調整以提高其準確性和效率。
#### 在旅行代理中實施修正型 RAG 的步驟
1. **初始用戶交互**
- 旅行代理收集用戶的初始偏好,例如目的地、旅行日期、預算和興趣。
- 範例:```python
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
```
2. **信息檢索**
- 旅行代理根據用戶偏好檢索有關航班、住宿、景點和餐廳的信息。
- 範例:```python
flights = search_flights(preferences)
hotels = search_hotels(preferences)
attractions = search_attractions(preferences)
```
3. **生成初始建議**
- 旅行代理使用檢索到的信息生成個性化行程。
- 範例:```python
itinerary = create_itinerary(flights, hotels, attractions)
print("Suggested Itinerary:", itinerary)
```
4. **收集用戶反饋**
- 旅行代理詢問用戶對初始建議的反饋。
- 範例:```python
feedback = {
"liked": ["Louvre Museum"],
"disliked": ["Eiffel Tower (too crowded)"]
}
```
5. **修正型 RAG 過程**
- **提示技術**:
```
```markdown
旅行代理根據用戶反饋制定新的搜索查詢。
- 範例:```python
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
```
- **工具**:旅行代理使用算法根據用戶反饋對新搜索結果進行排名和篩選,強調相關性。
- 範例:```python
new_attractions = search_attractions(preferences)
new_itinerary = create_itinerary(flights, hotels, new_attractions)
print("Updated Itinerary:", new_itinerary)
```
- **評估**:旅行代理通過分析用戶反饋並進行必要的調整,不斷評估其推薦的相關性和準確性。
- 範例:```python
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)
```
#### 實際範例
以下是一個將改進型 RAG 方法應用於旅行代理的簡化 Python 代碼範例:
```python
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
# Example usage
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)
```
### 預加載上下文
預加載上下文是指在處理查詢之前將相關的上下文或背景信息加載到模型中。這意味著模型從一開始就可以訪問這些信息,從而在不需要在過程中檢索額外數據的情況下生成更具信息量的響應。以下是一個旅行代理應用中如何進行預加載上下文的簡化 Python 代碼範例:
```python
class TravelAgent:
def __init__(self):
# Pre-load popular destinations and their information
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):
# Fetch destination information from pre-loaded context
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}."
# Example usage
travel_agent = TravelAgent()
print(travel_agent.get_destination_info("Paris"))
print(travel_agent.get_destination_info("Tokyo"))
```
#### 解釋
1. **初始化 (`__init__` method)**: The `TravelAgent` class pre-loads a dictionary containing information about popular destinations such as Paris, Tokyo, New York, and Sydney. This dictionary includes details like the country, currency, language, and major attractions for each destination.
2. **Retrieving Information (`get_destination_info` method)**: When a user queries about a specific destination, the `get_destination_info` 方法)**:該方法從預加載的上下文字典中獲取相關信息。通過預加載上下文,旅行代理應用可以快速響應用戶查詢,而不需要實時從外部來源檢索信息。這使應用更加高效和快速響應。
### 在迭代前以目標啟動計劃
以目標啟動計劃是指在開始時明確設定一個清晰的目標或期望結果。通過預先定義這個目標,模型可以在整個迭代過程中將其作為指導原則。這有助於確保每次迭代都更接近實現期望結果,使過程更高效且更專注。以下是一個如何在迭代之前以目標啟動旅行計劃的範例:
### 情景
一名旅行代理希望為客戶計劃一個定制的假期。目標是根據客戶的偏好和預算創建一個最大化客戶滿意度的旅行行程。
### 步驟
1. 定義客戶的偏好和預算。
2. 根據這些偏好啟動初始計劃。
3. 迭代以改進計劃,優化客戶滿意度。
#### Python 代碼
```python
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']
# Example usage
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)
```
#### 代碼解釋
1. **初始化 (`__init__` method)**: The `TravelAgent` class is initialized with a list of potential destinations, each having attributes like name, cost, and activity type.
2. **Bootstrapping the Plan (`bootstrap_plan` method)**: This method creates an initial travel plan based on the client's preferences and budget. It iterates through the list of destinations and adds them to the plan if they match the client's preferences and fit within the budget.
3. **Matching Preferences (`match_preferences` method)**: This method checks if a destination matches the client's preferences.
4. **Iterating the Plan (`iterate_plan` method)**: This method refines the initial plan by trying to replace each destination in the plan with a better match, considering the client's preferences and budget constraints.
5. **Calculating Cost (`calculate_cost` 方法)**:該方法計算當前計劃的總成本,包括潛在的新目的地。
#### 範例使用
- **初始計劃**:旅行代理根據客戶對觀光的偏好和 2000 美元的預算創建初始計劃。
- **改進計劃**:旅行代理通過迭代改進計劃,優化客戶的偏好和預算。
通過以清晰的目標啟動計劃(例如,最大化客戶滿意度)並迭代改進計劃,旅行代理可以為客戶創建定制且優化的旅行行程。這種方法確保旅行計劃從一開始就符合客戶的偏好和預算,並隨著每次迭代而改進。
### 利用 LLM 進行重新排序和評分
大型語言模型(LLM)可以通過評估檢索到的文檔或生成的響應的相關性和質量來進行重新排序和評分。其運作方式如下:
**檢索**:初始檢索步驟根據查詢獲取一組候選文檔或響應。
**重新排序**:LLM 評估這些候選項,並根據其相關性和質量進行重新排序。此步驟確保最相關和高質量的信息首先呈現。
**評分**:LLM 為每個候選項分配分數,反映其相關性和質量。這有助於選擇最佳響應或文檔提供給用戶。
通過利用 LLM 進行重新排序和評分,系統可以提供更準確和上下文相關的信息,改善整體用戶體驗。以下是一個旅行代理如何使用大型語言模型(LLM)根據用戶偏好對旅行目的地進行重新排序和評分的範例:
#### 情景 - 基於偏好的旅行
一名旅行代理希望根據客戶的偏好推薦最佳旅行目的地。LLM 將幫助重新排序和評分目的地,確保呈現最相關的選項。
#### 步驟:
1. 收集用戶偏好。
2. 檢索潛在旅行目的地列表。
3. 使用 LLM 根據用戶偏好重新排序和評分目的地。
以下是如何更新之前的範例以使用 Azure OpenAI Services:
#### 要求
1. 您需要擁有 Azure 訂閱。
2. 創建 Azure OpenAI 資源並獲取您的 API 密鑰。
#### Python 代碼範例
```python
import requests
import json
class TravelAgent:
def __init__(self, destinations):
self.destinations = destinations
def get_recommendations(self, preferences, api_key, endpoint):
# Generate a prompt for the Azure OpenAI
prompt = self.generate_prompt(preferences)
# Define headers and payload for the request
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
payload = {
"prompt": prompt,
"max_tokens": 150,
"temperature": 0.7
}
# Call the Azure OpenAI API to get the re-ranked and scored destinations
response = requests.post(endpoint, headers=headers, json=payload)
response_data = response.json()
# Extract and return the recommendations
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
# Example usage
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)
```
#### 代碼解釋 - 偏好預訂器
1. **初始化**:`TravelAgent` class is initialized with a list of potential travel destinations, each having attributes like name and description.
2. **Getting Recommendations (`get_recommendations` method)**: This method generates a prompt for the Azure OpenAI service based on the user's preferences and makes an HTTP POST request to the Azure OpenAI API to get re-ranked and scored destinations.
3. **Generating Prompt (`generate_prompt` method)**: This method constructs a prompt for the Azure OpenAI, including the user's preferences and the list of destinations. The prompt guides the model to re-rank and score the destinations based on the provided preferences.
4. **API Call**: The `requests` library is used to make an HTTP POST request to the Azure OpenAI API endpoint. The response contains the re-ranked and scored destinations.
5. **Example Usage**: The travel agent collects user preferences (e.g., interest in sightseeing and diverse culture) and uses the Azure OpenAI service to get re-ranked and scored recommendations for travel destinations.
Make sure to replace `your_azure_openai_api_key` with your actual Azure OpenAI API key and `https://your-endpoint.com/...` 使用 Azure OpenAI 部署的實際端點 URL 替換。
通過利用 LLM 進行重新排序和評分,旅行代理可以為客戶提供更個性化和相關的旅行推薦,增強其整體體驗。
### RAG:提示技術與工具
檢索增強生成(RAG)既可以作為提示技術,也可以作為 AI 代理開發中的工具。理解這兩者之間的區別可以幫助您在項目中更有效地利用 RAG。
#### RAG 作為提示技術
**它是什麼?**
- 作為提示技術,RAG 涉及制定特定查詢或提示,以指導從大型語料庫或數據庫中檢索相關信息。這些信息隨後用於生成響應或操作。
**如何運作:**
1. **制定提示**:根據手頭的任務或用戶的輸入創建結構良好的提示或查詢。
2. **檢索信息**:使用提示從預先存在的知識庫或數據集中搜索相關數據。
3. **生成響應**:將檢索到的信息與生成式 AI 模型結合,生成全面且連貫的響應。
**旅行代理範例**:
- 用戶輸入:"我想參觀巴黎的博物館。"
- 提示:"查找巴黎的頂級博物館。"
- 檢索信息:有關盧浮宮、奧賽博物館等的詳細信息。
- 生成響應:"以下是巴黎的一些頂級博物館:盧浮宮、奧賽博物館和龐畢度中心。"
#### RAG 作為工具
**它是什麼?**
- 作為工具,RAG 是一個集成系統,自動化檢索和生成過程,使開發人員能夠更輕鬆地實現複雜的 AI 功能,而無需為每個查詢手動編寫提示。
**如何運作:**
1. **集成**:將 RAG 嵌入到 AI 代理的架構中,使其能夠自動處理檢索和生成任務。
2. **自動化**:該工具管理從接收用戶輸入到生成最終響應的整個過程,而無需為每個步驟顯式提示。
3. **高效性**:通過簡化檢索和生成過程,提高代理的性能,實現更快更準確的響應。
**旅行代理範例**:
- 用戶輸入:"我想參觀巴黎的博物館。"
- RAG 工具:自動檢索有關博物館的信息並生成響應。
- 生成響應:"以下是巴黎的一些頂級博物館:盧浮宮、奧賽博物館和龐畢度中心。"
### 比較
| 方面 | 提示技術 | 工具 |
|----------------------|---------------------------------------------------|-------------------------------------------|
| **手動與自動** | 為每個查詢手動制定提示。 | 自動化檢索和生成過程。 |
| **控制** | 提供更多對檢索過程的控制。 | 簡化並自動化檢索和生成。 |
| **靈活性** | 允許根據特定需求自定義提示。 | 更適合大規模實施。 |
| **複雜性** | 需要編寫和調整提示。 | 更易於集成到 AI 代理架構中。 |
### 實際範例
**提示技術範例:**
```python
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)
```
**工具範例:**
```python
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)
```
```
```markdown
巴黎最好的博物館?")。
- **導航意圖**:使用者希望導航到特定的網站或頁面(例如,「羅浮宮官方網站」)。
- **交易意圖**:使用者目的是進行交易,例如預訂航班或購買商品(例如,「預訂飛往巴黎的航班」)。
2. **上下文感知**:
- 分析使用者查詢的上下文有助於準確識別其意圖,包括考慮先前的互動、使用者偏好以及當前查詢的具體細節。
3. **自然語言處理 (NLP)**:
- 採用 NLP 技術理解並解釋使用者提供的自然語言查詢,包括實體識別、情感分析和查詢解析等任務。
4. **個性化**:
- 根據使用者的歷史記錄、偏好和反饋個性化搜尋結果,提升檢索資訊的相關性。
#### 實際範例:在旅行代理中基於意圖搜尋
以下以旅行代理為例,說明如何實現基於意圖的搜尋。
1. **收集使用者偏好**
```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
```
2. **理解使用者意圖**
```python
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"
```
3. **上下文感知**
```python
def analyze_context(query, user_history):
# Combine current query with user history to understand context
context = {
"current_query": query,
"user_history": user_history
}
return context
```
4. **搜尋並個性化結果**
```python
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):
# Example search logic for informational intent
results = search_web(f"best {preferences['interests']} in {preferences['destination']}")
return results
def search_navigation(query):
# Example search logic for navigational intent
results = search_web(query)
return results
def search_transaction(query, preferences):
# Example search logic for transactional intent
results = search_web(f"book {query} to {preferences['destination']}")
return results
def personalize_results(results, user_history):
# Example personalization logic
personalized = [result for result in results if result not in user_history]
return personalized[:10] # Return top 10 personalized results
```
5. **範例用法**
```python
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)
```
---
## 4. 作為工具生成程式碼
程式碼生成代理使用 AI 模型編寫並執行程式碼,解決複雜問題並自動化任務。
### 程式碼生成代理
程式碼生成代理使用生成式 AI 模型來編寫並執行程式碼。這些代理可以通過生成並運行多種程式語言的程式碼來解決複雜問題、自動化任務並提供有價值的洞察。
#### 實際應用
1. **自動化程式碼生成**:生成特定任務的程式碼片段,例如數據分析、網頁抓取或機器學習。
2. **SQL 作為 RAG**:使用 SQL 查詢檢索和操作數據庫中的數據。
3. **問題解決**:創建並執行程式碼解決特定問題,例如優化算法或分析數據。
#### 範例:用於數據分析的程式碼生成代理
假設您正在設計一個程式碼生成代理,以下是其工作方式:
1. **任務**:分析數據集以識別趨勢和模式。
2. **步驟**:
- 將數據集加載到數據分析工具中。
- 生成 SQL 查詢以篩選和聚合數據。
- 執行查詢並檢索結果。
- 使用結果生成可視化和洞察。
3. **所需資源**:訪問數據集、數據分析工具和 SQL 功能。
4. **經驗**:使用過去的分析結果提高未來分析的準確性和相關性。
### 範例:用於旅行代理的程式碼生成代理
在此範例中,我們將設計一個程式碼生成代理「旅行代理」,通過生成和執行程式碼來協助使用者規劃旅行。此代理可處理檢索旅行選項、篩選結果和使用生成式 AI 編譯行程等任務。
#### 程式碼生成代理概述
1. **收集使用者偏好**:收集使用者輸入的目的地、旅行日期、預算和興趣等。
2. **生成程式碼以檢索數據**:生成程式碼片段檢索航班、酒店和景點的數據。
3. **執行生成的程式碼**:運行生成的程式碼以獲取實時資訊。
4. **生成行程**:將檢索到的數據編譯成個性化的旅行計劃。
5. **基於反饋調整**:接收使用者反饋,必要時重新生成程式碼以優化結果。
#### 分步實施
1. **收集使用者偏好**
```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
```
2. **生成程式碼以檢索數據**
```python
def generate_code_to_fetch_data(preferences):
# Example: Generate code to search for flights based on user preferences
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):
# Example: Generate code to search for hotels
code = f"""
def search_hotels():
import requests
response = requests.get('https://api.example.com/hotels', params={preferences})
return response.json()
"""
return code
```
3. **執行生成的程式碼**
```python
def execute_code(code):
# Execute the generated code using 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)
```
4. **生成行程**
```python
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)
```
5. **基於反饋調整**
```python
def adjust_based_on_feedback(feedback, preferences):
# Adjust preferences based on user feedback
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)
# Regenerate and execute code with updated preferences
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)
```
### 利用環境感知和推理
基於表格的結構模式可以通過利用環境感知和推理來增強查詢生成過程。以下是一個範例:
1. **理解結構模式**:系統將理解表格的結構模式並使用此資訊作為查詢生成的基礎。
2. **基於反饋調整**:系統根據反饋調整使用者偏好並推理需要更新的結構模式欄位。
3. **生成並執行查詢**:系統生成並執行查詢,以根據新偏好檢索更新的航班和酒店數據。
以下是一個包含這些概念的更新 Python 程式碼範例:
```python
def adjust_based_on_feedback(feedback, preferences, schema):
# Adjust preferences based on user feedback
if "liked" in feedback:
preferences["favorites"] = feedback["liked"]
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
# Reasoning based on schema to adjust other related preferences
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):
# Custom logic to adjust preferences based on schema and feedback
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):
# Generate code to fetch flight data based on updated preferences
return f"fetch_flights(preferences={preferences})"
def generate_code_to_fetch_hotels(preferences):
# Generate code to fetch hotel data based on updated preferences
return f"fetch_hotels(preferences={preferences})"
def execute_code(code):
# Simulate execution of code and return mock data
return {"data": f"Executed: {code}"}
def generate_itinerary(flights, hotels, attractions):
# Generate itinerary based on flights, hotels, and attractions
return {"flights": flights, "hotels": hotels, "attractions": attractions}
# Example schema
schema = {
"favorites": {"positive_adjustment": "increase", "negative_adjustment": "decrease", "default": "neutral"},
"avoid": {"positive_adjustment": "decrease", "negative_adjustment": "increase", "default": "neutral"}
}
# Example usage
preferences = {"favorites": "sightseeing", "avoid": "crowded places"}
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
updated_preferences = adjust_based_on_feedback(feedback, preferences, schema)
# Regenerate and execute code with updated preferences
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)
```
#### 說明 - 基於反饋的預訂
1. **結構模式感知**:`schema` dictionary defines how preferences should be adjusted based on feedback. It includes fields like `favorites` and `avoid`, with corresponding adjustments.
2. **Adjusting Preferences (`adjust_based_on_feedback` method)**: This method adjusts preferences based on user feedback and the schema.
3. **Environment-Based Adjustments (`adjust_based_on_environment` 方法)**:此方法基於結構模式和反饋定制調整。
4. **生成並執行查詢**:系統生成程式碼以根據調整後的偏好檢索更新的航班和酒店數據,並模擬執行這些查詢。
5. **生成行程**:系統基於新的航班、酒店和景點數據創建更新的行程。
通過使系統具備環境感知能力並基於結構模式推理,它可以生成更準確和相關的查詢,從而提供更好的旅行建議和更個性化的使用者體驗。
### 使用 SQL 作為檢索增強生成 (RAG) 技術
SQL(結構化查詢語言)是一種強大的數據庫交互工具。作為檢索增強生成 (RAG) 方法的一部分,SQL 可以從數據庫中檢索相關數據,以便在 AI 代理中生成回應或執行操作。以下探討如何在旅行代理的上下文中使用 SQL 作為 RAG 技術。
#### 關鍵概念
1. **數據庫交互**:
- 使用 SQL 查詢數據庫,檢索相關資訊並操作數據。
- 範例:從旅行數據庫中檢索航班詳情、酒店資訊和景點資料。
2. **與 RAG 集成**:
- 根據使用者輸入和偏好生成 SQL 查詢。
- 然後使用檢索到的數據生成個性化建議或操作。
3. **動態查詢生成**:
- AI 代理根據上下文和使用者需求生成動態 SQL 查詢。
- 範例:定制 SQL 查詢以根據預算、日期和興趣篩選結果。
#### 應用
- **自動化程式碼生成**:生成特定任務的程式碼片段。
- **SQL 作為 RAG**:使用 SQL 查詢操作數據。
- **問題解決**:創建並執行程式碼解決問題。
**範例**:數據分析代理:
1. **任務**:分析數據集以發現趨勢。
2. **步驟**:
- 加載數據集。
- 生成 SQL 查詢以篩選數據。
- 執行查詢並檢索結果。
- 生成可視化和洞察。
3. **資源**:數據集訪問、SQL 功能。
4. **經驗**:使用過去的結果改進未來分析。
#### 實際範例:在旅行代理中使用 SQL
1. **收集使用者偏好**
```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
```
2. **生成 SQL 查詢**
```python
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
```
3. **執行 SQL 查詢**
```python
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
```
4. **生成建議**
```python
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)
```
#### 範例 SQL 查詢
1. **航班查詢**
```sql
SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate';
```
2. **酒店查詢**
```sql
SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate';
```
3. **景點查詢**
```sql
SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine';
```
通過將 SQL 作為檢索增強生成 (RAG) 方法的一部分,像旅行代理這樣的 AI 代理可以動態檢索和利用相關數據,提供準確且個性化的建議。
### 結論
元認知是一種強大的工具,可以顯著增強 AI 代理的能力。通過結合元認知過程,您可以設計出更加智能、適應性更強且更高效的代理。使用附加資源進一步探索 AI 代理中元認知的迷人世界。
```
**免責聲明**:
本文件使用基於機器的人工智能翻譯服務進行翻譯。儘管我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原文文件作為權威來源。對於關鍵信息,建議尋求專業人工翻譯。我們對因使用本翻譯而產生的任何誤解或誤讀不承擔責任。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/09-metacognition/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/09-metacognition/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 35716
} |
# AI Agents in Production
## 簡介
本課程將涵蓋以下內容:
- 如何有效地規劃將 AI Agent 部署到生產環境的流程。
- 部署 AI Agent 到生產環境時可能遇到的常見錯誤與問題。
- 如何在保持 AI Agent 性能的同時管理成本。
## 學習目標
完成本課程後,您將能夠掌握以下內容:
- 提升生產環境中 AI Agent 系統的性能、成本效益及整體效能的技巧。
- 如何評估 AI Agent 及其運行系統。
- 部署 AI Agent 至生產環境時如何控制成本。
部署值得信賴的 AI Agent 至關重要。請參閱「Building Trustworthy AI Agents」課程以獲取更多相關資訊。
## 評估 AI Agents
在部署 AI Agent 的過程中(包括部署前、中、後),建立完善的評估系統至關重要。這能確保系統與您及用戶的目標保持一致。
要評估 AI Agent,不僅需要檢視 Agent 的輸出,還需要評估整個 AI Agent 所運行的系統。這包括但不限於:
- 初始模型請求。
- Agent 判斷用戶意圖的能力。
- Agent 判斷正確工具以完成任務的能力。
- 工具對 Agent 請求的回應。
- Agent 解讀工具回應的能力。
- 用戶對 Agent 回應的反饋。
這樣可以更模組化地識別需要改進的地方,並能更有效地監控模型、提示、工具及其他組件的變更影響。
## AI Agents 的常見問題及潛在解決方案
| **問題** | **潛在解決方案** |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AI Agent 任務執行不一致 | - 優化給予 AI Agent 的提示;明確設定目標。<br>- 確認是否可以將任務分解為子任務,並由多個 Agent 處理。 |
| AI Agent 陷入持續迴圈 | - 確保設置明確的終止條件,讓 Agent 知道何時停止流程。<br>- 對於需要推理與規劃的複雜任務,考慮使用專門針對推理任務的大型模型。 |
| AI Agent 工具調用表現不佳 | - 在 Agent 系統外測試並驗證工具的輸出結果。<br>- 優化工具的參數設置、提示及命名方式。 |
| 多 Agent 系統表現不一致 | - 優化每個 Agent 的提示,確保它們具體且互相區分明確。<br>- 構建一個層級系統,使用「路由」或控制 Agent 來決定哪個 Agent 是適合的執行者。 |
## 成本管理
以下是一些管理 AI Agent 部署成本的策略:
- **緩存回應** - 辨識常見請求與任務,並在這些請求進入 Agent 系統前提供回應,是減少相似請求量的好方法。您甚至可以實現一個流程,利用更基本的 AI 模型來判斷某請求與緩存請求的相似程度。
- **使用較小的模型** - 小型語言模型 (SLMs) 在某些 Agent 用例中表現良好,且能顯著降低成本。如前所述,建立評估系統來判斷並比較小型模型與大型模型的效能,是了解小型模型在您的用例中表現的最佳方式。
- **使用路由模型** - 類似的策略是使用多樣化的模型和尺寸。您可以使用 LLM/SLM 或無伺服器函數,根據請求的複雜性將其路由到最適合的模型。這樣不僅能降低成本,還能確保在適當的任務上保持性能。
## 恭喜
這是「AI Agents for Beginners」課程的最後一課。
我們計劃根據回饋與這個快速發展的行業變化,持續新增課程內容,因此請隨時回來查看。
如果您想繼續學習並構建 AI Agent,歡迎加入 [Azure AI Community Discord](https://discord.gg/kzRShWzttr)。
我們在那裡舉辦工作坊、社群圓桌會議及「問我任何事」的活動。
此外,我們還有一個 Learn 資源集合,其中包含幫助您開始在生產環境中構建 AI Agent 的額外材料。
**免責聲明**:
本文件使用機器翻譯服務進行翻譯。我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原語言的原始文件為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或誤讀不承擔責任。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/10-ai-agents-production/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/10-ai-agents-production/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 2716
} |
# 课程设置
## 简介
本课将讲解如何运行本课程的代码示例。
## 需求
- 一个 GitHub 账户
- Python 3.12+
## 克隆或派生此仓库
首先,请克隆或派生(Fork)GitHub 仓库。这将创建您自己的课程材料副本,方便您运行、测试和调整代码!
您可以通过点击此链接 [fork the repo](https://github.com/microsoft/ai-agents-for-beginners/fork) 来完成。
完成后,您将拥有如下所示的课程副本:

## 获取您的 GitHub 个人访问令牌 (PAT)
目前,本课程使用 GitHub Models Marketplace 提供对大语言模型(LLMs)的免费访问,这些模型将用于创建 AI Agent。
要访问此服务,您需要创建一个 GitHub 个人访问令牌。
您可以在 GitHub 账户的 [Personal Access Tokens settings](https://github.com/settings/personal-access-tokens) 页面创建。
在屏幕左侧选择 `Fine-grained tokens` 选项。
然后选择 `Generate new token`。

复制您刚刚创建的新令牌。接下来,您需要将此令牌添加到课程中的 `.env` 文件中。
## 添加到您的环境变量中
要创建 `.env` 文件,请在终端中运行以下命令:
```bash
cp .env.example .env
```
此命令会复制示例文件并在您的目录中创建一个 `.env` 文件。
打开该文件,并将您创建的令牌粘贴到 .env 文件中的 `GITHUB_TOKEN=` 字段。
## 安装所需的依赖包
为了确保您拥有运行代码所需的所有 Python 依赖包,请在终端中运行以下命令。
我们建议创建一个 Python 虚拟环境,以避免潜在的冲突和问题。
```bash
pip install -r requirements.txt
```
此命令将安装所需的 Python 包。
现在,您已经准备好运行本课程的代码了,祝您在 AI Agent 世界的学习中玩得开心!
如果在设置过程中遇到任何问题,请加入我们的 [Azure AI Community Discord](https://discord.gg/kzRShWzttr) 或 [创建一个问题](https://github.com/microsoft/ai-agents-for-beginners/issues?WT.mc_id=academic-105485-koreyst)。
**免责声明**:
本文件使用基于机器的人工智能翻译服务进行翻译。虽然我们努力确保准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言的文件为权威来源。对于关键信息,建议寻求专业人工翻译。因使用本翻译而引起的任何误解或误读,我们概不负责。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/00-course-setup/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/00-course-setup/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 1611
} |
# AI代理和应用场景简介
欢迎参加“AI 代理入门”课程!本课程将为您提供构建 AI 代理的基础知识和实践示例。
加入 [Azure AI Discord 社区](https://discord.gg/kzRShWzttr),与其他学习者和 AI 代理构建者交流,并提出您在课程中遇到的任何问题。
为了开始这门课程,我们将首先更好地理解什么是 AI 代理,以及如何在我们构建的应用程序和工作流中使用它们。
## 课程简介
本节课程内容包括:
- 什么是 AI 代理?有哪些不同类型的代理?
- AI 代理适用于哪些用例?它们如何帮助我们?
- 设计代理解决方案时需要了解的基本构建块有哪些?
## 学习目标
完成本节课程后,您将能够:
- 理解 AI 代理的概念及其与其他 AI 解决方案的区别。
- 高效应用 AI 代理。
- 为用户和客户高效设计代理解决方案。
## 定义 AI 代理及其类型
### 什么是 AI 代理?
AI代理是通过为 **大语言模型(LLMs)** 提供 **工具** 和 **知识** 的访问权限,从而扩展其能力以 **执行操作** 的 **系统**。
我们将这一定义拆解为几个部分:
- **系统** - 需要将代理视为由多个组件组成的系统,而不是单一组件。AI代理的基本组件包括:
- **环境** - 定义 AI 代理运行的空间。例如,如果我们有一个旅游预订 AI 代理,环境可能是 AI 代理用于完成任务的旅游预订系统。
- **传感器** - 环境提供信息和反馈。AI 代理使用传感器来收集和解释有关环境当前状态的信息。在旅游预订代理的例子中,旅游预订系统可以提供酒店可用性或航班价格等信息。
- **执行器** - 一旦 AI 代理接收到环境的当前状态信息,它会根据当前任务决定执行什么操作以改变环境。例如,旅游预订代理可能为用户预订一个可用的房间。

**大语言模型** - 在大语言模型出现之前,代理的概念已经存在。利用 LLMs 构建AI 代理的优势在于它们能够解释人类语言和数据。这种能力使 LLMs 能够解释环境信息并制定改变环境的计划。
**执行操作** - 在 AI 代理系统之外,LLMs 的操作通常仅限于根据用户提示生成内容或信息。在AI代理系统中,LLMs 可以通过解释用户请求并利用环境中可用的工具来完成任务。
**工具访问** - LLM 可以访问哪些工具由两个因素决定:1)它运行的环境;2)AI代理开发者。例如,在旅游代理的例子中,代理的工具可能仅限于预订系统中的操作,或者开发者可以限制代理的工具访问权限,仅限于航班预订。
**知识** - 除了环境提供的信息外,AI 代理还可以从其他系统、服务、工具,甚至其他代理中检索知识。在旅游代理的例子中,这些知识可能包括存储在客户数据库中的用户旅游偏好信息。
### 不同类型的代理
现在我们已经了解了 AI 代理的一般定义,让我们来看一些具体的代理类型,以及它们如何应用于旅游预订 AI 代理。
| **代理类型** | **描述** | **示例** |
| ----------------------------- | ------------------------------------------------------------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| **简单反射代理** | 根据预定义规则执行即时操作。 | 旅游代理解析邮件上下文并将旅行投诉转发给客户服务部门。 |
| **基于模型的反射代理** | 根据世界模型及其变化执行操作。 | 旅游代理根据历史价格数据的访问优先考虑价格变化显著的路线。 |
| **基于目标的代理** | 通过解释目标并决定实现目标的操作来创建计划。 | 旅游代理通过确定从当前位置到目的地所需的旅行安排(如汽车、公共交通、航班)来预订行程。 |
| **基于效用的代理** | 考虑偏好并通过数值权衡如何实现目标。 | 旅游代理在预订旅行时,通过权衡便利性与成本来最大化效用。 |
| **学习型代理** | 通过响应反馈并相应调整操作来随着时间推移不断改进。 | 旅游代理通过使用客户在行程结束后的反馈调查结果来调整未来的预订,从而不断改进。 |
| **分层代理** | 包含多级代理系统,高级代理将任务分解为子任务,由低级代理完成。 | 旅游代理通过将取消行程的任务分解为子任务(如取消特定预订)并让低级代理完成这些任务,再向高级代理汇报完成情况。 |
| **多代理系统(MAS)** | 代理可以独立完成任务,无论是合作还是竞争。 | 合作:多个代理分别预订特定的旅行服务,如酒店、航班和娱乐活动。竞争:多个代理管理并竞争共享的酒店预订日历,为客户预订酒店。 |
## 何时使用 AI 代理
在前面的部分中,我们使用旅游代理的用例解释了如何在不同的旅行预订场景中使用不同类型的代理。在整个课程中,我们将继续使用这一应用。
让我们来看一下 AI 代理最适合使用的用例类型:

- **开放性问题** - 允许 LLM 决定完成任务所需的步骤,因为这些步骤无法始终硬编码到工作流中。
- **多步骤流程** - 需要一定复杂度的任务,AI 代理需要在多个回合中使用工具或信息,而不是单次检索。
- **逐步改进** - 代理可以通过从环境或用户接收反馈来改进,以提供更好的效用。
在“构建可信的 AI 代理”课程中,我们将进一步探讨使用AI代理的考虑因素。
## 代理解决方案的基础知识
### 代理开发
设计 AI 代理系统的第一步是定义工具、操作和行为。在本课程中,我们重点使用 **Azure AI Agent Service** 来定义我们的代理。它提供以下功能:
- 选择开放模型,如 OpenAI、Mistral 和 Llama
- 使用提供商(如 Tripadvisor )提供的授权数据
- 使用标准化的 OpenAPI 3.0 工具
### 代理模式
与 LLM 的通信是通过提示完成的。鉴于 AI 代理的半自主特性,在环境发生变化后,手动重新提示 LLM 并非总是必要或可行。我们使用 **代理模式**,以更可扩展的方式在多个步骤中提示 LLM。
本课程分为当前流行的几种代理模式。
### 代理框架
代理框架允许开发者通过代码实现代理模式。这些框架提供模板、插件和工具,以促进AI 代理的协作。这些优势为 AI 代理系统提供了更好的可观察性和故障排除能力。
在本课程中,我们将探讨以研究为驱动的 AutoGen 框架,以及 Semantic Kernel 提供的面向生产的 Agent 框架。
**免责声明**:
本文件使用基于机器的人工智能翻译服务进行翻译。尽管我们努力确保准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言的文件作为权威来源。对于关键信息,建议寻求专业人工翻译。我们对于因使用此翻译而产生的任何误解或错误解读不承担责任。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/01-intro-to-ai-agents/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/01-intro-to-ai-agents/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 5640
} |
# 探索 AI Agent 框架
AI Agent 框架是专为简化 AI Agent 的创建、部署和管理而设计的软件平台。这些框架为开发者提供了预构建的组件、抽象和工具,从而简化了复杂 AI 系统的开发流程。
通过为 AI Agent 开发中的常见挑战提供标准化的方法,这些框架帮助开发者专注于应用的独特部分。它们提升了构建 AI 系统的可扩展性、可访问性和效率。
## 简介
本课程将涵盖以下内容:
- 什么是 AI Agent 框架?它能让开发者实现什么?
- 团队如何利用这些框架快速原型设计、迭代并提升 Agent 的能力?
- 微软开发的框架和工具([Autogen](https://aka.ms/ai-agents/autogen) / [Semantic Kernel](https://aka.ms/ai-agents-beginners/semantic-kernel) / [Azure AI Agent Service](https://aka.ms/ai-agents-beginners/ai-agent-service))之间有什么区别?
- 我可以直接集成现有的 Azure 生态系统工具,还是需要独立的解决方案?
- 什么是 Azure AI Agent Service?它如何帮助我?
## 学习目标
本课程的目标是帮助你理解:
- AI Agent 框架在 AI 开发中的作用。
- 如何利用 AI Agent 框架构建智能 Agent。
- AI Agent 框架所支持的关键功能。
- Autogen、Semantic Kernel 和 Azure AI Agent Service 之间的差异。
## 什么是 AI Agent 框架?它能让开发者实现什么?
传统的 AI 框架可以帮助你将 AI 集成到应用中,并通过以下方式提升应用性能:
- **个性化**:AI 可以分析用户行为和偏好,提供个性化的推荐、内容和体验。
示例:流媒体服务(如 Netflix)利用 AI 根据观看历史推荐电影和节目,从而提升用户参与度和满意度。
- **自动化和效率**:AI 能够自动化重复性任务、优化工作流程并提高运营效率。
示例:客户服务应用利用 AI 驱动的聊天机器人处理常见查询,从而减少响应时间,并将人类员工解放出来处理更复杂的问题。
- **增强用户体验**:AI 可以通过语音识别、自然语言处理和预测性文本等智能功能提升整体用户体验。
示例:虚拟助手(如 Siri 和 Google Assistant)利用 AI 理解并响应语音命令,使用户更容易与设备互动。
### 听起来很棒,对吧?那么为什么我们还需要 AI Agent 框架?
AI Agent 框架不仅仅是 AI 框架。它们旨在支持创建能够与用户、其他 Agent 和环境交互以实现特定目标的智能 Agent。这些 Agent 可以表现出自主行为、做出决策并适应变化的条件。以下是 AI Agent 框架所支持的一些关键功能:
- **Agent 协作与协调**:支持创建多个 AI Agent,能够协作、沟通并协调以解决复杂任务。
- **任务自动化与管理**:提供自动化多步骤工作流、任务分配和动态任务管理的机制。
- **上下文理解与适应**:使 Agent 具备理解上下文、适应变化的环境并基于实时信息做出决策的能力。
总结来说,Agent 让你可以做得更多,提升自动化水平,创建能够从环境中学习和适应的更智能的系统。
## 如何快速原型设计、迭代并提升 Agent 的能力?
这是一个快速发展的领域,但大多数 AI Agent 框架都具备一些共性,可以帮助你快速原型设计和迭代,主要包括模块化组件、协作工具和实时学习。让我们深入探讨这些内容:
- **使用模块化组件**:AI 框架提供预构建的组件,例如提示、解析器和内存管理。
- **利用协作工具**:为 Agent 设计特定的角色和任务,测试并优化协作工作流。
- **实时学习**:实现反馈循环,使 Agent 从交互中学习并动态调整行为。
### 使用模块化组件
像 LangChain 和 Microsoft Semantic Kernel 这样的框架提供了预构建的组件,例如提示、解析器和内存管理。
**团队如何使用这些组件**:团队可以快速组装这些组件,创建一个功能性原型,而无需从头开始,从而实现快速实验和迭代。
**实际工作原理**:你可以使用预构建的解析器从用户输入中提取信息、使用内存模块存储和检索数据,并使用提示生成器与用户交互,而无需从头构建这些组件。
**示例代码**:以下是一个使用预构建解析器从用户输入中提取信息的示例:
```python
from langchain import Parser
parser = Parser()
user_input = "Book a flight from New York to London on July 15th"
parsed_data = parser.parse(user_input)
print(parsed_data)
# Output: {'origin': 'New York', 'destination': 'London', 'date': 'July 15th'}
```
从这个示例中可以看出,你可以利用预构建的解析器从用户输入中提取关键信息,例如航班预订请求的出发地、目的地和日期。这种模块化方法使你可以专注于高层逻辑。
### 利用协作工具
像 CrewAI 和 Microsoft Autogen 这样的框架可以帮助创建能够协作的多个 Agent。
**团队如何使用这些工具**:团队可以为 Agent 设计特定的角色和任务,从而测试和优化协作工作流,提高整体系统效率。
**实际工作原理**:你可以创建一个 Agent 团队,其中每个 Agent 都有特定的功能,例如数据检索、分析或决策。这些 Agent 可以通过通信和信息共享来实现共同目标,例如回答用户查询或完成任务。
**示例代码(Autogen)**:
```python
# creating agents, then create a round robin schedule where they can work together, in this case in order
# Data Retrieval Agent
# Data Analysis Agent
# Decision Making Agent
agent_retrieve = AssistantAgent(
name="dataretrieval",
model_client=model_client,
tools=[retrieve_tool],
system_message="Use tools to solve tasks."
)
agent_analyze = AssistantAgent(
name="dataanalysis",
model_client=model_client,
tools=[analyze_tool],
system_message="Use tools to solve tasks."
)
# conversation ends when user says "APPROVE"
termination = TextMentionTermination("APPROVE")
user_proxy = UserProxyAgent("user_proxy", input_func=input)
team = RoundRobinGroupChat([agent_retrieve, agent_analyze, user_proxy], termination_condition=termination)
stream = team.run_stream(task="Analyze data", max_turns=10)
# Use asyncio.run(...) when running in a script.
await Console(stream)
```
上述代码展示了如何创建一个任务,该任务涉及多个 Agent 协作分析数据。每个 Agent 执行特定功能,通过协调这些 Agent 来实现预期结果。通过为每个 Agent 分配专门的角色,可以提升任务效率和性能。
### 实时学习
高级框架提供了实时上下文理解和适应的能力。
**团队如何使用这些能力**:团队可以实现反馈循环,使 Agent 从交互中学习并动态调整行为,从而不断改进和优化功能。
**实际工作原理**:Agent 可以分析用户反馈、环境数据和任务结果,更新知识库、调整决策算法并随着时间的推移提升性能。这种迭代学习过程使 Agent 能够适应变化的条件和用户偏好,从而增强整体系统的有效性。
## Autogen、Semantic Kernel 和 Azure AI Agent Service 框架之间的差异是什么?
可以通过多种方式比较这些框架,但我们将从设计、功能和目标使用场景的角度来分析它们的主要区别:
### Autogen
由 Microsoft Research 的 AI Frontiers Lab 开发的开源框架,专注于事件驱动的分布式 *agentic* 应用,支持多个 LLM 和 SLM、工具以及高级多 Agent 设计模式。
Autogen 的核心理念是基于 Agent,这些 Agent 是可以感知环境、做出决策并采取行动以实现特定目标的自主实体。Agent 通过异步消息进行通信,使它们能够独立并行工作,从而增强系统的可扩展性和响应性。
Agent 基于 [Actor 模型](https://en.wikipedia.org/wiki/Actor_model)。根据 Wikipedia 的定义,Actor 是 _并发计算的基本构建块。Actor 在接收到消息时,可以:做出本地决策、创建更多 Actor、发送更多消息以及决定如何响应接收到的下一条消息_。
**使用场景**:自动化代码生成、数据分析任务,以及为规划和研究功能构建自定义 Agent。
Autogen 的一些核心概念包括:
- **Agent**:Agent 是一个软件实体,能够:
- **通过消息通信**,这些消息可以是同步的或异步的。
- **维护自己的状态**,状态可以通过接收到的消息进行修改。
- **执行操作**,这些操作可能会修改 Agent 的状态并产生外部效果,例如更新消息日志、发送新消息、执行代码或进行 API 调用。
以下是一个创建具有聊天功能的 Agent 的简短代码片段:
```python
from autogen_agentchat.agents import AssistantAgent
from autogen_agentchat.messages import TextMessage
from autogen_ext.models.openai import OpenAIChatCompletionClient
class MyAssistant(RoutedAgent):
def __init__(self, name: str) -> None:
super().__init__(name)
model_client = OpenAIChatCompletionClient(model="gpt-4o")
self._delegate = AssistantAgent(name, model_client=model_client)
@message_handler
async def handle_my_message_type(self, message: MyMessageType, ctx: MessageContext) -> None:
print(f"{self.id.type} received message: {message.content}")
response = await self._delegate.on_messages(
[TextMessage(content=message.content, source="user")], ctx.cancellation_token
)
print(f"{self.id.type} responded: {response.chat_message.content}")
```
在上述代码中,`MyAssistant` has been created and inherits from `RoutedAgent`. It has a message handler that prints the content of the message and then sends a response using the `AssistantAgent` delegate. Especially note how we assign to `self._delegate` an instance of `AssistantAgent` 是一个预构建的 Agent,能够处理聊天完成任务。
接下来,让 Autogen 知道这种 Agent 类型并启动程序:
```python
# main.py
runtime = SingleThreadedAgentRuntime()
await MyAgent.register(runtime, "my_agent", lambda: MyAgent())
runtime.start() # Start processing messages in the background.
await runtime.send_message(MyMessageType("Hello, World!"), AgentId("my_agent", "default"))
```
在上述代码中,Agent 被注册到运行时,并向 Agent 发送了一条消息,产生如下输出:
```text
# Output from the console:
my_agent received message: Hello, World!
my_assistant received message: Hello, World!
my_assistant responded: Hello! How can I assist you today?
```
- **多 Agent 支持**:Autogen 支持创建多个 Agent,它们可以协作以更高效地解决复杂任务。通过定义具有专门功能和角色的不同类型的 Agent,例如数据检索、分析、决策和用户交互,可以创建一个多 Agent 系统。以下是一个这样的创建示例:
```python
editor_description = "Editor for planning and reviewing the content."
# Example of declaring an Agent
editor_agent_type = await EditorAgent.register(
runtime,
editor_topic_type, # Using topic type as the agent type.
lambda: EditorAgent(
description=editor_description,
group_chat_topic_type=group_chat_topic_type,
model_client=OpenAIChatCompletionClient(
model="gpt-4o-2024-08-06",
# api_key="YOUR_API_KEY",
),
),
)
# remaining declarations shortened for brevity
# Group chat
group_chat_manager_type = await GroupChatManager.register(
runtime,
"group_chat_manager",
lambda: GroupChatManager(
participant_topic_types=[writer_topic_type, illustrator_topic_type, editor_topic_type, user_topic_type],
model_client=OpenAIChatCompletionClient(
model="gpt-4o-2024-08-06",
# api_key="YOUR_API_KEY",
),
participant_descriptions=[
writer_description,
illustrator_description,
editor_description,
user_description
],
),
)
```
上述代码中,我们有一个 `GroupChatManager`,它被注册到运行时。此管理器负责协调不同类型 Agent(如撰稿人、插画师、编辑和用户)之间的交互。
- **Agent 运行时**:框架提供了一个运行时环境,用于支持 Agent 之间的通信、管理其身份和生命周期,并执行安全和隐私边界。这意味着你可以在一个安全且受控的环境中运行 Agent,确保它们能够安全高效地交互。以下是两种运行时的介绍:
- **独立运行时**:适用于单进程应用,其中所有 Agent 都用同一种编程语言实现并运行在同一进程中。以下是其工作原理的示意图:

应用栈
*Agent 通过运行时通过消息进行通信,运行时管理 Agent 的生命周期。*
- **分布式运行时**:适用于多进程应用,其中 Agent 可以用不同的编程语言实现并运行在不同的机器上。以下是其工作原理的示意图:

### Semantic Kernel + Agent Framework
Semantic Kernel 包含两部分:Semantic Kernel Agent Framework 和 Semantic Kernel 本身。
先谈谈 Semantic Kernel 的核心概念:
- **连接**:与外部 AI 服务和数据源的接口。
```csharp
using Microsoft.SemanticKernel;
// Create kernel
var builder = Kernel.CreateBuilder();
// Add a chat completion service:
builder.Services.AddAzureOpenAIChatCompletion(
"your-resource-name",
"your-endpoint",
"your-resource-key",
"deployment-model");
var kernel = builder.Build();
```
这里是一个简单的示例,展示了如何创建一个 Kernel 并添加一个聊天完成服务。Semantic Kernel 创建了一个与外部 AI 服务(此处为 Azure OpenAI Chat Completion)的连接。
- **插件**:封装了应用程序可以使用的功能。既有现成的插件,也可以创建自定义插件。这里还有一个“语义函数”的概念。之所以称为语义函数,是因为你提供了语义信息,帮助 Semantic Kernel 决定需要调用该函数。以下是一个示例:
```csharp
var userInput = Console.ReadLine();
// Define semantic function inline.
string skPrompt = @"Summarize the provided unstructured text in a sentence that is easy to understand.
Text to summarize: {{$userInput}}";
// Register the function
kernel.CreateSemanticFunction(
promptTemplate: skPrompt,
functionName: "SummarizeText",
pluginName: "SemanticFunctions"
);
```
在此示例中,你首先有一个模板提示 `skPrompt` that leaves room for the user to input text, `$userInput`. Then you register the function `SummarizeText` with the plugin `SemanticFunctions`。注意函数的名称,它帮助 Semantic Kernel 理解该函数的用途以及何时应该调用它。
- **本地函数**:框架还可以直接调用本地函数来执行任务。以下是一个检索文件内容的本地函数示例:
```csharp
public class NativeFunctions {
[SKFunction, Description("Retrieve content from local file")]
public async Task<string> RetrieveLocalFile(string fileName, int maxSize = 5000)
{
string content = await File.ReadAllTextAsync(fileName);
if (content.Length <= maxSize) return content;
return content.Substring(0, maxSize);
}
}
//Import native function
string plugInName = "NativeFunction";
string functionName = "RetrieveLocalFile";
var nativeFunctions = new NativeFunctions();
kernel.ImportFunctions(nativeFunctions, plugInName);
```
- **规划器**:规划器根据用户输入协调执行计划和策略。规划器的作用是表达任务的执行方式,然后作为 Semantic Kernel 的执行指令。它随后调用必要的函数来完成任务。以下是一个计划示例:
```csharp
string planDefinition = "Read content from a local file and summarize the content.";
SequentialPlanner sequentialPlanner = new SequentialPlanner(kernel);
string assetsFolder = @"../../assets";
string fileName = Path.Combine(assetsFolder,"docs","06_SemanticKernel", "aci_documentation.txt");
ContextVariables contextVariables = new ContextVariables();
contextVariables.Add("fileName", fileName);
var customPlan = await sequentialPlanner.CreatePlanAsync(planDefinition);
// Execute the plan
KernelResult kernelResult = await kernel.RunAsync(contextVariables, customPlan);
Console.WriteLine($"Summarization: {kernelResult.GetValue<string>()}");
```
特别注意 `planDefinition` which is a simple instruction for the planner to follow. The appropriate functions are then called based on this plan, in this case our semantic function `SummarizeText` and the native function `RetrieveLocalFile`。
- **内存**:抽象并简化 AI 应用的上下文管理。内存的概念是 LLM 应该了解的信息。你可以将这些信息存储在向量存储中,最终可以是内存数据库、向量数据库或类似数据库。以下是一个非常简化的场景示例,其中将 *事实* 添加到内存中:
```csharp
var facts = new Dictionary<string,string>();
facts.Add(
"Azure Machine Learning; https://learn.microsoft.com/azure/machine-learning/",
@"Azure Machine Learning is a cloud service for accelerating and
managing the machine learning project lifecycle. Machine learning professionals,
data scientists, and engineers can use it in their day-to-day workflows"
);
facts.Add(
"Azure SQL Service; https://learn.microsoft.com/azure/azure-sql/",
@"Azure SQL is a family of managed, secure, and intelligent products
that use the SQL Server database engine in the Azure cloud."
);
string memoryCollectionName = "SummarizedAzureDocs";
foreach (var fact in facts) {
await memoryBuilder.SaveReferenceAsync(
collection: memoryCollectionName,
description: fact.Key.Split(";")[1].Trim(),
text: fact.Value,
externalId: fact.Key.Split(";")[2].Trim(),
externalSourceName: "Azure Documentation"
);
}
```
这些事实随后存储在内存集合 `SummarizedAzureDocs` 中。这是一个非常简化的示例,但你可以看到如何将信息存储到内存中供 LLM 使用。
这就是 Semantic Kernel 框架的基础知识,那么它的 Agent Framework 是什么?
### Azure AI Agent Service
Azure AI Agent Service 是一个较新的补充,于 Microsoft Ignite 2024 上推出。它支持开发和部署更灵活的 AI Agent,例如直接调用开源 LLM(如 Llama 3、Mistral 和 Cohere)。
Azure AI Agent Service 提供更强的企业安全机制和数据存储方法,非常适合企业应用。
它可以与 Autogen 和 Semantic Kernel 等多 Agent 协作框架无缝协作。
该服务目前处于公测阶段,支持用 Python 和 C# 构建 Agent。
#### 核心概念
Azure AI Agent Service 的核心概念包括:
- **Agent**:Azure AI Agent Service 与 Azure AI Foundry 集成。在 AI Foundry 中,AI Agent 充当“智能”微服务,可以用于回答问题(RAG)、执行操作或完全自动化工作流。它通过结合生成式 AI 模型的能力与访问和交互真实数据源的工具实现这些目标。以下是一个 Agent 示例:
```python
agent = project_client.agents.create_agent(
model="gpt-4o-mini",
name="my-agent",
instructions="You are helpful agent",
tools=code_interpreter.definitions,
tool_resources=code_interpreter.resources,
)
```
在此示例中,创建了一个模型为 `gpt-4o-mini`, a name `my-agent`, and instructions `You are helpful agent` 的 Agent。该 Agent 配备了工具和资源,用于执行代码解释任务。
- **线程和消息**:线程是另一个重要概念。它表示 Agent 和用户之间的对话或交互。线程可用于跟踪对话进度、存储上下文信息以及管理交互的状态。以下是一个线程示例:
```python
thread = project_client.agents.create_thread()
message = project_client.agents.create_message(
thread_id=thread.id,
role="user",
content="Could you please create a bar chart for the operating profit using the following data and provide the file to me? Company A: $1.2 million, Company B: $2.5 million, Company C: $3.0 million, Company D: $1.8 million",
)
# Ask the agent to perform work on the thread
run = project_client.agents.create_and_process_run(thread_id=thread.id, agent_id=agent.id)
# Fetch and log all messages to see the agent's response
messages = project_client.agents.list_messages(thread_id=thread.id)
print(f"Messages: {messages}")
```
在上述代码中,创建了一个线程。然后向线程发送了一条消息。通过调用 `create_and_process_run`,要求 Agent 在该线程上执行任务。最后,获取并记录消息以查看 Agent 的响应。这些消息表明用户与 Agent 之间对话的进展。还需要注意的是,消息可以是文本、图像或文件等不同类型,例如 Agent 的工作结果可能是图像或文本响应。作为开发者,你可以利用这些信息进一步处理响应或将其呈现给用户。
- **与其他 AI 框架集成**:Azure AI Agent Service 可以与其他框架(如 Autogen 和 Semantic Kernel)交互,这意味着你可以在这些框架之一中构建应用的一部分,并例如将 Agent Service 用作协调器,或者完全使用 Agent Service 构建应用。
**使用场景**:Azure AI Agent Service 专为需要安全、可扩展且灵活的 AI Agent 部署的企业应用设计。
## 这些框架之间的区别是什么?
虽然这些框架之间似乎有很多重叠,但在设计、功能和目标使用场景方面,它们仍然有一些关键区别:
- **Autogen**:专注于事件驱动的分布式 Agentic 应用,支持多个 LLM 和 SLM、工具以及高级多 Agent 设计模式。
- **Semantic Kernel**:专注于理解和生成类人文本内容,通过捕捉更深层次的语义意义来实现。它旨在自动化复杂的工作流并根据项目目标启动任务。
- **Azure AI Agent Service**:提供更灵活的模型,例如直接调用开源 LLM(如 Llama 3、Mistral 和 Cohere)。它提供更强的企业安全机制和数据存储方法,非常适合企业应用。
仍然不确定该选择哪个?
### 使用场景
让我们通过一些常见的使用场景来帮助你选择:
> **问**:我的团队正在开发一个项目,涉及自动化代码生成和数据分析任务。我们应该选择哪个框架?
>
> **答**:Autogen 是一个不错的选择,因为它专注于事件驱动的分布式 Agentic 应用,并支持高级多 Agent 设计模式。
> **问**:在这个使用场景中,Autogen 比 Semantic Kernel 和 Azure AI Agent Service 更好的原因是什么?
>
> **答**:Autogen 专为事件驱动的分布式 Agentic 应用设计,非常适合自动化代码生成和数据分析任务。它提供了必要的工具和功能,可以高效地构建复杂的多 Agent 系统。
> **问**:听起来 Azure AI Agent Service 也适合这个场景,它也有代码生成工具,对吗?
>
> **答**:是的,Azure AI Agent Service 也支持代码生成和数据分析任务,但它可能更适合需要安全、可扩展且灵活的 AI Agent 部署的企业应用。Autogen 更专注于事件驱动的分布式 Agentic 应用和高级多 Agent 设计模式。
> **问**:所以你的意思是,如果我想要企业级的解决方案,我应该选择 Azure AI Agent Service?
>
> **答**:是的,Azure AI Agent Service 专为需要安全、可扩展且灵活的 AI Agent 部署的企业应用设计。它提供更强的企业安全机制和数据存储方法,非常适合企业使用场景。
### 总结关键差异表格
| 框架 | 重点 | 核心概念 | 使用场景 |
| ---------------- | ---------------------------- | ---------------------------- | ---------------------------- |
| Autogen | 事件驱动的分布式 Agentic 应用 | Agent、角色、功能、数据 | 代码生成、数据分析任务 |
| Semantic Kernel | 理解和生成类人文本内容 | Agent、模块化组件、协作 | 自然语言理解、内容生成 |
| Azure AI Agent Service | 灵活的模型、企业安全、工具调用 | 模块化、协作、流程协调 | 安全、可扩
根据项目目标。适用于自然语言理解、内容生成。
- **Azure AI Agent Service**:灵活的模型、企业级安全机制、数据存储方法。非常适合在企业应用中实现安全、可扩展和灵活的 AI 代理部署。
## 我可以直接集成现有的 Azure 生态系统工具,还是需要独立的解决方案?
答案是肯定的,您可以将现有的 Azure 生态系统工具直接与 Azure AI Agent Service 集成,尤其是因为它已被设计为能够与其他 Azure 服务无缝协作。例如,您可以集成 Bing、Azure AI Search 和 Azure Functions。此外,它还与 Azure AI Foundry 有深度集成。
对于 Autogen 和 Semantic Kernel,您也可以与 Azure 服务集成,但可能需要从代码中调用 Azure 服务。另一种集成方式是使用 Azure SDK,通过您的代理与 Azure 服务交互。此外,如前所述,您可以使用 Azure AI Agent Service 作为在 Autogen 或 Semantic Kernel 中构建的代理的协调器,这将使您轻松访问 Azure 生态系统。
## 参考
- [1] - [Azure Agent Service](https://techcommunity.microsoft.com/blog/azure-ai-services-blog/introducing-azure-ai-agent-service/4298357)
- [2] - [Semantic Kernel and Autogen](https://devblogs.microsoft.com/semantic-kernel/microsofts-agentic-ai-frameworks-autogen-and-semantic-kernel/)
- [3] - [Semantic Kernel Agent Framework](https://learn.microsoft.com/semantic-kernel/frameworks/agent/?pivots=programming-language-csharp)
- [4] - [Azure AI Agent service](https://learn.microsoft.com/azure/ai-services/agents/overview)
- [5] - [Using Azure AI Agent Service with AutoGen / Semantic Kernel to build a multi-agent's solution](https://techcommunity.microsoft.com/blog/educatordeveloperblog/using-azure-ai-agent-service-with-autogen--semantic-kernel-to-build-a-multi-agen/4363121)
**免责声明**:
本文档使用基于机器的人工智能翻译服务进行翻译。尽管我们努力确保准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原文的母语版本为权威来源。对于关键信息,建议寻求专业人工翻译。因使用本翻译而引起的任何误解或误读,我们概不负责。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/02-explore-agentic-frameworks/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/02-explore-agentic-frameworks/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 18520
} |
# AI 代理设计原则
## 简介
关于构建 AI 代理系统,有许多不同的思考方式。由于在生成式 AI 设计中,模糊性是一种特性而非缺陷,因此工程师有时会难以确定从哪里开始。我们制定了一套以人为中心的用户体验设计原则,旨在帮助开发者构建以客户为中心的代理系统,以满足他们的业务需求。这些设计原则并不是一种规定性的架构,而是为定义和构建代理体验的团队提供的起点。
一般来说,代理系统应该:
- 扩展和增强人类能力(如头脑风暴、解决问题、自动化等)
- 弥补知识空白(例如帮助快速了解某一知识领域、翻译等)
- 促进并支持我们个人偏好的协作方式
- 让我们成为更好的自己(例如,作为生活教练/任务管理者,帮助我们学习情绪调节和正念技巧,建立韧性等)
## 本课内容
- 什么是代理设计原则
- 实施这些设计原则时需要遵循的指导方针
- 使用这些设计原则的一些示例
## 学习目标
完成本课后,您将能够:
1. 解释什么是代理设计原则
2. 解释使用代理设计原则的指导方针
3. 理解如何使用代理设计原则构建一个代理
## 代理设计原则

### 代理(空间)
这是代理运行的环境。这些原则指导我们如何设计能够在物理和数字世界中互动的代理。
- **连接而非取代** – 帮助人们与其他人、事件和可操作的知识建立联系,从而促进协作和交流。
- 代理帮助连接事件、知识和人。
- 代理拉近人与人之间的距离,而不是取代或贬低人类。
- **易于访问但偶尔隐形** – 代理主要在后台运行,只有在相关且适当的时候才会提醒我们。
- 代理可在任何设备或平台上轻松被授权用户发现和访问。
- 代理支持多模态输入和输出(如声音、语音、文本等)。
- 代理可以在前台与后台之间无缝切换;根据用户需求的感知,在主动和被动模式之间切换。
- 代理可能以隐形形式运行,但其后台处理路径及与其他代理的协作对用户是透明且可控的。
### 代理(时间)
这是代理如何随着时间运作的方式。这些原则指导我们如何设计跨越过去、现在和未来的代理互动。
- **过去**:回顾包含状态和上下文的历史。
- 代理通过分析丰富的历史数据(不仅仅是事件、人员或状态)提供更相关的结果。
- 代理从过去的事件中创建连接,并积极反思记忆以应对当前情境。
- **现在**:更多地引导,而非简单通知。
- 代理体现了一种全面的互动方式。当事件发生时,代理超越静态通知或其他形式化方式。代理可以简化流程或动态生成提示,在合适的时机引导用户注意。
- 代理根据上下文环境、社会和文化变化以及用户意图提供信息。
- 代理的互动可以是渐进的,随着时间的推移在复杂性上演变和成长,从而赋能用户。
- **未来**:适应和进化。
- 代理适应各种设备、平台和模式。
- 代理适应用户行为、无障碍需求,并可自由定制。
- 代理通过持续的用户交互来塑造和进化。
### 代理(核心)
这些是代理设计核心中的关键要素。
- **接受不确定性但建立信任**。
- 某种程度的代理不确定性是可以预期的。不确定性是代理设计的关键元素。
- 信任和透明是代理设计的基础层。
- 用户可以控制代理的开/关状态,并且代理的状态始终清晰可见。
## 实施这些原则的指导方针
在使用上述设计原则时,请遵循以下指导方针:
1. **透明性**:告知用户 AI 的参与方式及其工作原理(包括过去的操作),以及如何提供反馈和修改系统。
2. **控制权**:允许用户自定义、指定偏好和个性化,并对系统及其属性进行控制(包括遗忘功能)。
3. **一致性**:在设备和终端之间提供一致的多模态体验。尽量使用熟悉的 UI/UX 元素(例如,语音交互使用麦克风图标),并尽可能降低用户的认知负担(例如,提供简明的回复、视觉辅助和“了解更多”内容)。
## 如何使用这些原则和指导方针设计一个旅游代理
假设您正在设计一个旅游代理,以下是您可以如何应用设计原则和指导方针的思路:
1. **透明性** – 让用户知道这个旅游代理是由 AI 驱动的代理。提供一些基本的使用说明(例如,一条“你好”消息,示例提示)。在产品页面上清楚记录这一点。显示用户过去提出的提示列表。明确说明如何提供反馈(如点赞或点踩、发送反馈按钮等)。清楚说明代理是否存在使用或主题限制。
2. **控制权** – 确保用户可以清楚地了解如何修改已创建的代理,例如通过系统提示。允许用户选择代理的详细程度、写作风格,以及代理不应讨论的主题。让用户查看并删除任何相关文件或数据、提示以及过去的对话。
3. **一致性** – 确保用于分享提示、添加文件或照片、标记某人或某物的图标是标准且易于识别的。使用回形针图标表示文件上传/共享,使用图片图标表示上传图形。
## 其他资源
- [Practices for Governing Agentic AI Systems | OpenAI](https://openai.com)
- [The HAX Toolkit Project - Microsoft Research](https://microsoft.com)
- [Responsible AI Toolbox](https://responsibleaitoolbox.ai)
**免责声明**:
本文件使用基于机器的人工智能翻译服务进行翻译。尽管我们尽力确保准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言的文件为权威来源。对于关键信息,建议寻求专业人工翻译。对于因使用本翻译而引起的任何误解或误读,我们概不负责。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/03-agentic-design-patterns/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/03-agentic-design-patterns/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 2629
} |
# 工具使用设计模式
## 简介
在本课程中,我们将探索以下问题:
- 什么是工具使用设计模式?
- 它可以应用于哪些使用场景?
- 实现这一设计模式需要哪些关键元素/构件?
- 使用工具使用设计模式构建可信赖的 AI 代理需要注意哪些特殊事项?
## 学习目标
完成本课程后,您将能够:
- 定义工具使用设计模式及其目的。
- 识别适用于工具使用设计模式的使用场景。
- 理解实现该设计模式所需的关键元素。
- 认识在使用此设计模式的 AI 代理中确保可信赖性需要考虑的因素。
## 什么是工具使用设计模式?
**工具使用设计模式**的核心是赋予大型语言模型(LLM)与外部工具交互的能力,以完成特定目标。工具是代理可以执行的代码,可以是简单的函数(如计算器),也可以是调用第三方服务的 API(如股票价格查询或天气预报)。在 AI 代理的上下文中,工具是设计用来响应**模型生成的函数调用**而执行的。
## 它可以应用于哪些使用场景?
AI 代理可以利用工具完成复杂任务、检索信息或做出决策。工具使用设计模式通常应用于需要动态与外部系统交互的场景,例如数据库、Web 服务或代码解释器。这种能力在以下多种场景中非常有用:
- **动态信息检索**:代理可以查询外部 API 或数据库以获取最新数据(例如,查询 SQLite 数据库进行数据分析、获取股票价格或天气信息)。
- **代码执行和解释**:代理可以执行代码或脚本来解决数学问题、生成报告或进行模拟。
- **工作流自动化**:通过集成任务调度器、电子邮件服务或数据管道等工具,自动化重复性或多步骤的工作流。
- **客户支持**:代理可以与 CRM 系统、工单平台或知识库交互,以解决用户问题。
- **内容生成与编辑**:代理可以利用语法检查器、文本摘要工具或内容安全评估器等工具,协助完成内容创建任务。
## 实现工具使用设计模式需要哪些元素/构件?
### 函数/工具调用
函数调用是使大型语言模型(LLM)能够与工具交互的主要方式。您会发现“函数”和“工具”这两个术语常常互换使用,因为“函数”(可重用代码块)就是代理用于执行任务的“工具”。为了让函数的代码能够被调用,LLM 需要将用户的请求与函数的描述进行匹配。为此,需要向 LLM 提供包含所有可用函数描述的架构。LLM 会选择最适合任务的函数,并返回其名称和参数。选定的函数被调用,其响应会发送回 LLM,LLM 再利用这些信息回复用户的请求。
要为代理实现函数调用,开发者需要:
1. 支持函数调用的 LLM 模型
2. 包含函数描述的架构
3. 每个描述中提到的函数代码
以下通过获取某城市当前时间的示例来说明:
- **初始化支持函数调用的 LLM:**
并非所有模型都支持函数调用,因此需要确认您使用的 LLM 是否支持。[Azure OpenAI](https://learn.microsoft.com/azure/ai-services/openai/how-to/function-calling) 支持函数调用。我们可以从初始化 Azure OpenAI 客户端开始。
```python
# Initialize the Azure OpenAI client
client = AzureOpenAI(
azure_endpoint = os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
api_version="2024-05-01-preview"
)
```
- **创建函数架构:**
接下来,我们将定义一个包含函数名称、功能描述以及参数名称和描述的 JSON 架构。然后将此架构与用户请求(例如查找旧金山的时间)一起传递给上述创建的客户端。需要注意的是,返回的是一个**工具调用**,而不是问题的最终答案。如前所述,LLM 返回其为任务选择的函数名称及其参数。
```python
# Function description for the model to read
tools = [
{
"type": "function",
"function": {
"name": "get_current_time",
"description": "Get the current time in a given location",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "The city name, e.g. San Francisco",
},
},
"required": ["location"],
},
}
}
]
```
```python
# Initial user message
messages = [{"role": "user", "content": "What's the current time in San Francisco"}]
# First API call: Ask the model to use the function
response = client.chat.completions.create(
model=deployment_name,
messages=messages,
tools=tools,
tool_choice="auto",
)
# Process the model's response
response_message = response.choices[0].message
messages.append(response_message)
print("Model's response:")
print(response_message)
```
```bash
Model's response:
ChatCompletionMessage(content=None, role='assistant', function_call=None, tool_calls=[ChatCompletionMessageToolCall(id='call_pOsKdUlqvdyttYB67MOj434b', function=Function(arguments='{"location":"San Francisco"}', name='get_current_time'), type='function')])
```
- **执行任务所需的函数代码:**
现在,LLM 已经选择了需要运行的函数,接下来需要实现并执行完成任务的代码。我们可以用 Python 实现获取当前时间的代码,同时编写代码从 response_message 中提取函数名称和参数,以获得最终结果。
```python
def get_current_time(location):
"""Get the current time for a given location"""
print(f"get_current_time called with location: {location}")
location_lower = location.lower()
for key, timezone in TIMEZONE_DATA.items():
if key in location_lower:
print(f"Timezone found for {key}")
current_time = datetime.now(ZoneInfo(timezone)).strftime("%I:%M %p")
return json.dumps({
"location": location,
"current_time": current_time
})
print(f"No timezone data found for {location_lower}")
return json.dumps({"location": location, "current_time": "unknown"})
```
```python
# Handle function calls
if response_message.tool_calls:
for tool_call in response_message.tool_calls:
if tool_call.function.name == "get_current_time":
function_args = json.loads(tool_call.function.arguments)
time_response = get_current_time(
location=function_args.get("location")
)
messages.append({
"tool_call_id": tool_call.id,
"role": "tool",
"name": "get_current_time",
"content": time_response,
})
else:
print("No tool calls were made by the model.")
# Second API call: Get the final response from the model
final_response = client.chat.completions.create(
model=deployment_name,
messages=messages,
)
return final_response.choices[0].message.content
```
```bash
get_current_time called with location: San Francisco
Timezone found for san francisco
The current time in San Francisco is 09:24 AM.
```
函数调用是大多数代理工具使用设计的核心,但从零开始实现可能会有一定挑战。正如我们在 [第 2 课](../../../02-explore-agentic-frameworks) 中所学到的,代理框架为我们提供了预构建的模块,用于实现工具使用。
### 使用代理框架的工具使用示例
- ### **[Semantic Kernel](https://learn.microsoft.com/azure/ai-services/agents/overview)**
Semantic Kernel 是一个面向 .NET、Python 和 Java 开发者的开源 AI 框架,专注于与大型语言模型(LLM)协作。它通过一个称为[序列化](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions)的过程,自动向模型描述函数及其参数,从而简化了函数调用的使用。此外,它还处理模型与代码之间的交互。使用像 Semantic Kernel 这样的代理框架的另一个好处是,它允许您访问预构建的工具,例如 [文件搜索](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step4_assistant_tool_file_search.py) 和 [代码解释器](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py)。
以下图示展示了使用 Semantic Kernel 进行函数调用的流程:

在 Semantic Kernel 中,函数/工具被称为 [插件](https://learn.microsoft.com/semantic-kernel/concepts/plugins/?pivots=programming-language-python)。我们可以将 `get_current_time` function we saw earlier into a plugin by turning it into a class with the function in it. We can also import the `kernel_function` 装饰器用于函数描述。当您创建包含 GetCurrentTimePlugin 的内核时,内核会自动序列化函数及其参数,从而创建发送给 LLM 的架构。
```python
from semantic_kernel.functions import kernel_function
class GetCurrentTimePlugin:
async def __init__(self, location):
self.location = location
@kernel_function(
description="Get the current time for a given location"
)
def get_current_time(location: str = ""):
...
```
```python
from semantic_kernel import Kernel
# Create the kernel
kernel = Kernel()
# Create the plugin
get_current_time_plugin = GetCurrentTimePlugin(location)
# Add the plugin to the kernel
kernel.add_plugin(get_current_time_plugin)
```
- ### **[Azure AI Agent Service](https://learn.microsoft.com/azure/ai-services/agents/overview)**
Azure AI Agent Service 是一个较新的代理框架,旨在帮助开发者安全地构建、部署和扩展高质量、可扩展的 AI 代理,而无需管理底层的计算和存储资源。它特别适用于企业应用,因为它是一个具有企业级安全性的完全托管服务。
与直接使用 LLM API 开发相比,Azure AI Agent Service 提供了一些优势,包括:
- 自动工具调用——无需解析工具调用、调用工具以及处理响应;所有这些都在服务器端完成。
- 安全管理数据——无需自行管理会话状态,您可以依赖线程存储所需的所有信息。
- 开箱即用的工具——可用于与数据源交互的工具,例如 Bing、Azure AI 搜索和 Azure Functions。
Azure AI Agent Service 中的工具可分为两类:
1. 知识工具:
- [通过 Bing 搜索进行信息获取](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/bing-grounding?tabs=python&pivots=overview)
- [文件搜索](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/file-search?tabs=python&pivots=overview)
- [Azure AI 搜索](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-ai-search?tabs=azurecli%2Cpython&pivots=overview-azure-ai-search)
2. 操作工具:
- [函数调用](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/function-calling?tabs=python&pivots=overview)
- [代码解释器](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/code-interpreter?tabs=python&pivots=overview)
- [OpenAI 定义的工具](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/openapi-spec?tabs=python&pivots=overview)
- [Azure Functions](https://learn.microsoft.com/azure/ai-services/agents/how-to/tools/azure-functions?pivots=overview)
Agent Service 允许我们将这些工具组合为一个 `toolset`. It also utilizes `threads` which keep track of the history of messages from a particular conversation.
Imagine you are a sales agent at a company called Contoso. You want to develop a conversational agent that can answer questions about your sales data.
The image below illustrates how you could use Azure AI Agent Service to analyze your sales data:

To use any of these tools with the service we can create a client and define a tool or toolset. To implement this practically we can use the Python code below. The LLM will be able to look at the toolset and decide whether to use the user created function, `fetch_sales_data_using_sqlite_query`,或者根据用户请求使用预构建的代码解释器。
```python
import os
from azure.ai.projects import AIProjectClient
from azure.identity import DefaultAzureCredential
from fecth_sales_data_functions import fetch_sales_data_using_sqlite_query # fetch_sales_data_using_sqlite_query function which can be found in a fecth_sales_data_functions.py file.
from azure.ai.projects.models import ToolSet, FunctionTool, CodeInterpreterTool
project_client = AIProjectClient.from_connection_string(
credential=DefaultAzureCredential(),
conn_str=os.environ["PROJECT_CONNECTION_STRING"],
)
# Initialize function calling agent with the fetch_sales_data_using_sqlite_query function and adding it to the toolset
fetch_data_function = FunctionTool(fetch_sales_data_using_sqlite_query)
toolset = ToolSet()
toolset.add(fetch_data_function)
# Initialize Code Interpreter tool and adding it to the toolset.
code_interpreter = code_interpreter = CodeInterpreterTool()
toolset = ToolSet()
toolset.add(code_interpreter)
agent = project_client.agents.create_agent(
model="gpt-4o-mini", name="my-agent", instructions="You are helpful agent",
toolset=toolset
)
```
## 使用工具使用设计模式构建可信赖 AI 代理需要注意哪些特殊事项?
使用 LLM 动态生成 SQL 时,常见的担忧是安全性,尤其是 SQL 注入或恶意操作(如删除或篡改数据库)的风险。虽然这些担忧是合理的,但通过正确配置数据库访问权限可以有效缓解这些问题。对于大多数数据库,这包括将数据库配置为只读模式。对于 PostgreSQL 或 Azure SQL 等数据库服务,应用程序应被分配一个只读(SELECT)角色。
在安全环境中运行应用程序可以进一步增强保护。在企业场景中,通常会从操作系统中提取和转换数据到一个只读数据库或数据仓库中,并采用用户友好的架构。这种方法确保数据安全、性能优化且易于访问,同时限制了应用程序的只读访问权限。
## 其他资源
- [Azure AI Agents Service Workshop](https://microsoft.github.io/build-your-first-agent-with-azure-ai-agent-service-workshop/)
- [Contoso Creative Writer Multi-Agent Workshop](https://github.com/Azure-Samples/contoso-creative-writer/tree/main/docs/workshop)
- [Semantic Kernel Function Calling Tutorial](https://learn.microsoft.com/semantic-kernel/concepts/ai-services/chat-completion/function-calling/?pivots=programming-language-python#1-serializing-the-functions)
- [Semantic Kernel Code Interpreter](https://github.com/microsoft/semantic-kernel/blob/main/python/samples/getting_started_with_agents/openai_assistant/step3_assistant_tool_code_interpreter.py)
- [Autogen Tools](https://microsoft.github.io/autogen/dev/user-guide/core-user-guide/components/tools.html)
**免责声明**:
本文件使用基于机器的人工智能翻译服务进行翻译。尽管我们努力确保准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言的原始文件作为权威来源。对于关键信息,建议寻求专业人工翻译服务。因使用本翻译而引起的任何误解或误读,我们概不负责。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/04-tool-use/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/04-tool-use/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 12588
} |
# Agentic RAG
本课程全面介绍了代理型检索增强生成(Agentic RAG),这是一种新兴的人工智能范式,其中大型语言模型(LLMs)在从外部数据源获取信息的同时,能够自主规划下一步的操作。与传统的静态“检索然后阅读”模式不同,Agentic RAG 采用了迭代调用 LLM 的方式,穿插工具或函数调用及结构化输出。系统会评估结果、优化查询、在必要时调用额外工具,并持续循环,直到找到满意的解决方案。
## 简介
本课程将涵盖以下内容:
- **了解 Agentic RAG**:学习一种新兴的人工智能范式,其中大型语言模型(LLMs)能够在从外部数据源获取信息的同时自主规划下一步操作。
- **掌握迭代式“制造者-检查者”风格**:理解这种循环模式,通过迭代调用 LLM,穿插工具或函数调用及结构化输出,旨在提升准确性并处理格式错误的查询。
- **探索实际应用**:识别 Agentic RAG 在特定场景中的优势,例如以准确性为优先的环境、复杂的数据库交互以及扩展的工作流。
## 学习目标
完成本课程后,您将能够了解/掌握以下内容:
- **理解 Agentic RAG**:学习一种新兴的人工智能范式,其中大型语言模型(LLMs)能够在从外部数据源获取信息的同时自主规划下一步操作。
- **迭代式“制造者-检查者”风格**:理解通过迭代调用 LLM,穿插工具或函数调用及结构化输出来提升准确性并处理格式错误查询的概念。
- **掌控推理过程**:理解系统掌控其推理过程的能力,能够自主决定如何解决问题,而不是依赖预定义的路径。
- **工作流**:了解代理型模型如何自主决定检索市场趋势报告、识别竞争对手数据、关联内部销售指标、综合发现并评估策略。
- **迭代循环、工具集成与记忆**:学习系统如何依赖循环交互模式,在步骤间保持状态和记忆,从而避免重复循环并做出更明智的决策。
- **处理失败模式与自我纠正**:探索系统的强大自我纠正机制,包括迭代与重新查询、使用诊断工具以及在必要时依赖人工监督。
- **代理的边界**:了解 Agentic RAG 的局限性,聚焦于领域特定的自主性、对基础设施的依赖以及对安全措施的遵守。
- **实际应用场景及价值**:识别 Agentic RAG 在特定场景中的优势,例如以准确性为优先的环境、复杂的数据库交互以及扩展的工作流。
- **治理、透明性与信任**:学习治理和透明性的重要性,包括可解释的推理、偏见控制以及人工监督。
## 什么是 Agentic RAG?
代理型检索增强生成(Agentic Retrieval-Augmented Generation,简称 Agentic RAG)是一种新兴的人工智能范式,其中大型语言模型(LLMs)能够在从外部数据源获取信息的同时自主规划下一步操作。与传统的静态“检索然后阅读”模式不同,Agentic RAG 采用了迭代调用 LLM 的方式,穿插工具或函数调用及结构化输出。系统会评估结果、优化查询、在必要时调用额外工具,并持续循环,直到找到满意的解决方案。这种迭代式“制造者-检查者”风格旨在提升准确性、处理格式错误的查询,并确保高质量的结果。
系统能够主动掌控其推理过程,重写失败的查询、选择不同的检索方法并整合多种工具——例如 Azure AI Search 的向量搜索、SQL 数据库或自定义 API——在最终生成答案之前完成这些操作。代理型系统的显著特性在于其能够掌控推理过程。传统的 RAG 实现依赖预定义的路径,而代理型系统则基于所获取信息的质量自主决定步骤顺序。
## 定义代理型检索增强生成(Agentic RAG)
代理型检索增强生成(Agentic Retrieval-Augmented Generation,简称 Agentic RAG)是一种新兴的人工智能开发范式,其中 LLM 不仅从外部数据源中获取信息,还能自主规划下一步操作。与传统的静态“检索然后阅读”模式或精心设计的提示序列不同,Agentic RAG 采用了一种迭代调用 LLM 的循环模式,穿插工具或函数调用及结构化输出。在每一步,系统都会评估已获得的结果,决定是否需要优化查询、调用额外工具,并持续这一循环直到找到满意的解决方案。
这种迭代式“制造者-检查者”操作风格旨在提升准确性、处理格式错误的查询(例如 NL2SQL)并确保高质量的结果。与依赖精心设计的提示链不同,系统能够主动掌控其推理过程。它可以重写失败的查询、选择不同的检索方法并整合多种工具——例如 Azure AI Search 的向量搜索、SQL 数据库或自定义 API——在最终生成答案之前完成这些操作。这消除了对过于复杂的编排框架的需求。相反,通过一个相对简单的循环模式“LLM 调用 → 工具使用 → LLM 调用 → …”,即可生成复杂且可靠的输出。

## 掌控推理过程
让系统具备“代理型”能力的关键特性在于其能够掌控推理过程。传统的 RAG 实现通常依赖于人类预先定义的路径:一个思维链条,明确指出需要检索什么以及何时检索。
而真正的代理型系统则能够内部决定如何解决问题。它不只是执行脚本,而是根据所获取信息的质量自主决定步骤顺序。
例如,如果被要求创建一个产品发布策略,它不会仅仅依赖一个明确列出所有研究和决策工作流的提示。相反,代理型模型会自主决定:
1. 使用 Bing Web Grounding 检索当前市场趋势报告。
2. 使用 Azure AI Search 识别相关的竞争对手数据。
3. 使用 Azure SQL Database 关联历史内部销售指标。
4. 通过 Azure OpenAI Service 综合这些发现形成一个连贯的策略。
5. 评估策略是否存在漏洞或不一致之处,如有必要,进行新一轮的检索。
所有这些步骤——优化查询、选择数据源、迭代直到对答案“满意”为止——都是由模型自主决定,而非由人类预先编写脚本。
## 迭代循环、工具集成与记忆

代理型系统依赖于一种循环交互模式:
- **初始调用**:用户目标(即用户提示)被传递给 LLM。
- **工具调用**:如果模型发现信息缺失或指令含糊,它会选择一个工具或检索方法——例如向量数据库查询(如 Azure AI Search 的混合搜索私有数据)或结构化 SQL 调用——以获取更多上下文。
- **评估与优化**:在审查返回的数据后,模型会决定这些信息是否足够。如果不足,它会优化查询、尝试不同工具或调整方法。
- **重复直到满意**:此循环会持续进行,直到模型认为已获得足够的清晰度和证据,可以给出一个最终的、经过充分推理的响应。
- **记忆与状态**:由于系统在步骤之间保持状态和记忆,它可以回忆起之前的尝试及其结果,从而避免重复循环,并在推进过程中做出更明智的决策。
随着时间推移,这种方式创造了一种不断演进的理解,使得模型能够处理复杂的多步骤任务,而无需人类不断干预或重塑提示。
## 处理失败模式与自我纠正
Agentic RAG 的自主性还包括强大的自我纠正机制。当系统遇到瓶颈(例如检索到无关文档或遇到格式错误的查询)时,它可以:
- **迭代与重新查询**:模型不会返回低价值的响应,而是尝试新的搜索策略、重写数据库查询或查找替代数据集。
- **使用诊断工具**:系统可能调用额外的函数来帮助其调试推理步骤或确认检索数据的正确性。像 Azure AI Tracing 这样的工具对于实现强大的可观测性和监控将非常重要。
- **依赖人工监督**:对于高风险或反复失败的场景,模型可能会标记不确定性并请求人工指导。一旦人类提供了纠正反馈,模型可以将这一经验融入后续操作。
这种迭代和动态的方法使得模型能够不断改进,确保它不仅是一次性系统,而是能够在当前会话中从错误中学习的系统。

## 代理的边界
尽管在任务范围内具备一定的自主性,Agentic RAG 并不等同于通用人工智能(AGI)。其“代理型”能力局限于开发者提供的工具、数据源和策略。它无法自主创建新工具或超出已设定的领域边界。相反,它擅长动态协调现有资源。
与更高级 AI 形式的关键区别包括:
1. **领域特定的自主性**:Agentic RAG 系统专注于在已知领域内实现用户定义的目标,采用查询重写或工具选择等策略来优化结果。
2. **依赖基础设施**:系统的能力依赖于开发者集成的工具和数据。没有人类干预,它无法超越这些限制。
3. **遵守安全措施**:道德准则、合规规则和业务政策仍然非常重要。代理的自由始终受到安全措施和监督机制的约束(希望如此?)。
## 实际应用场景及价值
Agentic RAG 在需要迭代优化和精确性的场景中表现出色:
1. **以准确性为优先的环境**:在合规检查、法规分析或法律研究中,代理型模型可以反复验证事实、咨询多个来源并重写查询,直到生成经过充分验证的答案。
2. **复杂的数据库交互**:处理结构化数据时,查询可能经常失败或需要调整,系统可以通过 Azure SQL 或 Microsoft Fabric OneLake 自主优化查询,确保最终检索结果符合用户意图。
3. **扩展工作流**:随着新信息的出现,长时间运行的会话可能会不断演变。Agentic RAG 可以持续整合新数据,并在了解问题空间的过程中调整策略。
## 治理、透明性与信任
随着这些系统在推理上变得更加自主,治理和透明性至关重要:
- **可解释的推理**:模型可以提供其所做查询、所咨询来源及其推理步骤的审计记录。像 Azure AI Content Safety 和 Azure AI Tracing / GenAIOps 这样的工具可以帮助保持透明性并降低风险。
- **偏见控制与平衡检索**:开发者可以调整检索策略以确保考虑到平衡且具有代表性的数据源,并定期审核输出以检测偏见或不平衡模式,适用于使用 Azure Machine Learning 的高级数据科学组织。
- **人工监督与合规性**:对于敏感任务,人工审查仍然是必不可少的。Agentic RAG 并不会在高风险决策中取代人类判断,而是通过提供经过更充分验证的选项来增强人类决策。
拥有能够清晰记录操作的工具至关重要。否则,调试多步骤过程将变得非常困难。以下是来自 Literal AI(Chainlit 背后的公司)的代理运行示例:


## 结论
Agentic RAG 代表了 AI 系统在处理复杂、数据密集型任务方面的一种自然演进。通过采用循环交互模式、自主选择工具并优化查询直到获得高质量结果,系统超越了静态的提示跟随,成为一种更具适应性和上下文感知的决策者。尽管仍然受限于人类定义的基础设施和伦理指南,这些代理型能力使企业和终端用户能够享受到更丰富、更动态、更有价值的 AI 交互。
## 其他资源
- 实现检索增强生成(RAG)与 Azure OpenAI 服务:学习如何使用 Azure OpenAI 服务与您自己的数据。[此 Microsoft Learn 模块提供了有关实现 RAG 的全面指南](https://learn.microsoft.com/training/modules/use-own-data-azure-openai)
- 使用 Azure AI Foundry 评估生成式 AI 应用程序:本文涵盖了基于公开可用数据集评估和比较模型的内容,包括 [代理型 AI 应用程序和 RAG 架构](https://learn.microsoft.com/azure/ai-studio/concepts/evaluation-approach-gen-ai)
- [What is Agentic RAG | Weaviate](https://weaviate.io/blog/what-is-agentic-rag)
- [Agentic RAG: A Complete Guide to Agent-Based Retrieval Augmented Generation – News from generation RAG](https://ragaboutit.com/agentic-rag-a-complete-guide-to-agent-based-retrieval-augmented-generation/)
- [Agentic RAG: turbocharge your RAG with query reformulation and self-query! Hugging Face Open-Source AI Cookbook](https://huggingface.co/learn/cookbook/agent_rag)
- [Adding Agentic Layers to RAG](https://youtu.be/aQ4yQXeB1Ss?si=2HUqBzHoeB5tR04U)
- [The Future of Knowledge Assistants: Jerry Liu](https://www.youtube.com/watch?v=zeAyuLc_f3Q&t=244s)
- [How to Build Agentic RAG Systems](https://www.youtube.com/watch?v=AOSjiXP1jmQ)
- [Using Azure AI Foundry Agent Service to scale your AI agents](https://ignite.microsoft.com/sessions/BRK102?source=sessions)
### 学术论文
- [2303.17651 Self-Refine: Iterative Refinement with Self-Feedback](https://arxiv.org/abs/2303.17651)
- [2303.11366 Reflexion: Language Agents with Verbal Reinforcement Learning](https://arxiv.org/abs/2303.11366)
- [2305.11738 CRITIC: Large Language Models Can Self-Correct with Tool-Interactive Critiquing](https://arxiv.org/abs/2305.11738)
**免责声明**:
本文件使用基于机器的人工智能翻译服务进行翻译。尽管我们努力确保翻译的准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言的文件为权威来源。对于关键信息,建议使用专业人工翻译。我们不对因使用此翻译而引起的任何误解或误读承担责任。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/05-agentic-rag/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/05-agentic-rag/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 6999
} |
# 构建值得信赖的 AI 代理
## 简介
本课程将涵盖以下内容:
- 如何构建和部署安全且高效的 AI 代理。
- 开发 AI 代理时的重要安全注意事项。
- 如何在开发 AI 代理时维护数据和用户隐私。
## 学习目标
完成本课程后,您将能够:
- 识别并减轻在创建 AI 代理时可能面临的风险。
- 实施安全措施,确保数据和访问得到妥善管理。
- 创建既能维护数据隐私又能提供优质用户体验的 AI 代理。
## 安全性
首先,我们来看如何构建安全的代理型应用程序。安全性意味着 AI 代理能够按照设计执行任务。作为代理型应用程序的开发者,我们有一些方法和工具来最大化安全性:
### 构建元提示系统
如果您曾使用大型语言模型(LLMs)构建 AI 应用程序,您应该了解设计一个强大的系统提示或系统消息的重要性。这些提示定义了元规则、指令以及与用户和数据交互的指导方针。
对于 AI 代理来说,系统提示更为重要,因为它们需要非常具体的指令来完成我们为其设计的任务。
为了创建可扩展的系统提示,我们可以使用一个元提示系统来为应用程序中的一个或多个代理构建提示:

#### 第一步:创建元提示或模板提示
元提示将被提供给 LLM,用于生成我们为代理创建的系统提示。我们将其设计为模板,这样如果需要,可以高效地创建多个代理。
以下是我们可能提供给 LLM 的元提示示例:
```plaintext
You are an expert at creating AI agent assitants.
You will be provided a company name, role, responsibilites and other
information that you will use to provide a system prompt for.
To create the system prompt, be descriptive as possible and provide a structure that a system using an LLM can better understand the role and responsibilites of the AI assistant.
```
#### 第二步:创建基础提示
下一步是创建一个基础提示来描述 AI 代理。您应该包括代理的角色、代理需要完成的任务以及代理的其他职责。
示例如下:
```plaintext
You are a travel agent for Contoso Travel with that is great at booking flights for customers. To help customers you can perform the following tasks: lookup available flights, book flights, ask for preferences in seating and times for flights, cancel any previously booked flights and alert customers on any delays or cancellations of flights.
```
#### 第三步:将基础提示提供给 LLM
现在,我们可以通过将元提示作为系统提示,并结合基础提示来优化这个提示。
这将生成一个更适合指导 AI 代理的提示:
```markdown
**Company Name:** Contoso Travel
**Role:** Travel Agent Assistant
**Objective:**
You are an AI-powered travel agent assistant for Contoso Travel, specializing in booking flights and providing exceptional customer service. Your main goal is to assist customers in finding, booking, and managing their flights, all while ensuring that their preferences and needs are met efficiently.
**Key Responsibilities:**
1. **Flight Lookup:**
- Assist customers in searching for available flights based on their specified destination, dates, and any other relevant preferences.
- Provide a list of options, including flight times, airlines, layovers, and pricing.
2. **Flight Booking:**
- Facilitate the booking of flights for customers, ensuring that all details are correctly entered into the system.
- Confirm bookings and provide customers with their itinerary, including confirmation numbers and any other pertinent information.
3. **Customer Preference Inquiry:**
- Actively ask customers for their preferences regarding seating (e.g., aisle, window, extra legroom) and preferred times for flights (e.g., morning, afternoon, evening).
- Record these preferences for future reference and tailor suggestions accordingly.
4. **Flight Cancellation:**
- Assist customers in canceling previously booked flights if needed, following company policies and procedures.
- Notify customers of any necessary refunds or additional steps that may be required for cancellations.
5. **Flight Monitoring:**
- Monitor the status of booked flights and alert customers in real-time about any delays, cancellations, or changes to their flight schedule.
- Provide updates through preferred communication channels (e.g., email, SMS) as needed.
**Tone and Style:**
- Maintain a friendly, professional, and approachable demeanor in all interactions with customers.
- Ensure that all communication is clear, informative, and tailored to the customer's specific needs and inquiries.
**User Interaction Instructions:**
- Respond to customer queries promptly and accurately.
- Use a conversational style while ensuring professionalism.
- Prioritize customer satisfaction by being attentive, empathetic, and proactive in all assistance provided.
**Additional Notes:**
- Stay updated on any changes to airline policies, travel restrictions, and other relevant information that could impact flight bookings and customer experience.
- Use clear and concise language to explain options and processes, avoiding jargon where possible for better customer understanding.
This AI assistant is designed to streamline the flight booking process for customers of Contoso Travel, ensuring that all their travel needs are met efficiently and effectively.
```
#### 第四步:迭代与改进
这个元提示系统的价值在于能够更轻松地为多个代理扩展创建提示,并随着时间推移改进提示。很少有提示能在第一次就完全适用于您的用例。通过更改基础提示并将其运行通过系统,您可以进行小幅调整和改进,从而比较和评估结果。
## 理解威胁
要构建值得信赖的 AI 代理,理解并减轻可能对 AI 代理造成的风险和威胁是至关重要的。我们来看看一些常见的 AI 代理威胁以及如何更好地规划和应对它们。

### 任务与指令
**描述:** 攻击者试图通过提示或操控输入来更改 AI 代理的指令或目标。
**缓解措施:** 执行验证检查和输入过滤,以检测潜在危险的提示,在它们被 AI 代理处理之前拦截。由于这类攻击通常需要频繁与代理交互,限制对话轮数也是防止此类攻击的有效方法。
### 对关键系统的访问
**描述:** 如果 AI 代理可以访问存储敏感数据的系统和服务,攻击者可能会破坏代理与这些服务之间的通信。这可能是直接攻击,也可能是通过代理间接获取这些系统的信息。
**缓解措施:** AI 代理应仅在需要时访问相关系统,以防止此类攻击。代理与系统之间的通信应确保安全。实施身份验证和访问控制也是保护信息的有效手段。
### 资源和服务过载
**描述:** AI 代理可以访问不同的工具和服务来完成任务。攻击者可能利用这一能力,通过代理发送大量请求来攻击这些服务,可能导致系统故障或高昂成本。
**缓解措施:** 实施策略以限制 AI 代理对服务的请求数量。限制对话轮数和请求次数也是防止此类攻击的另一种方法。
### 知识库污染
**描述:** 这种攻击并不直接针对 AI 代理,而是针对代理将使用的知识库和其他服务。这可能包括篡改代理完成任务所需的数据或信息,导致代理向用户提供偏颇或意外的响应。
**缓解措施:** 定期验证 AI 代理在其工作流程中使用的数据。确保对这些数据的访问是安全的,并且只有受信任的人员才能更改,以避免此类攻击。
### 连锁错误
**描述:** AI 代理依赖多种工具和服务来完成任务。攻击者引发的错误可能导致其他系统的故障,使攻击范围扩大且更难排查。
**缓解措施:** 一种避免方法是让 AI 代理在受限环境中运行,例如在 Docker 容器中执行任务,以防止直接系统攻击。创建回退机制和重试逻辑,以应对某些系统返回错误的情况,也是防止更大范围系统故障的有效手段。
## 人类参与
另一种构建值得信赖的 AI 代理系统的有效方法是引入“人类参与”机制。这种机制允许用户在代理运行过程中提供反馈。用户实际上充当了多代理系统中的一个代理,可以批准或终止运行的流程。

以下是一个使用 AutoGen 实现此概念的代码示例:
```python
# Create the agents.
model_client = OpenAIChatCompletionClient(model="gpt-4o-mini")
assistant = AssistantAgent("assistant", model_client=model_client)
user_proxy = UserProxyAgent("user_proxy", input_func=input) # Use input() to get user input from console.
# Create the termination condition which will end the conversation when the user says "APPROVE".
termination = TextMentionTermination("APPROVE")
# Create the team.
team = RoundRobinGroupChat([assistant, user_proxy], termination_condition=termination)
# Run the conversation and stream to the console.
stream = team.run_stream(task="Write a 4-line poem about the ocean.")
# Use asyncio.run(...) when running in a script.
await Console(stream)
```
**免责声明**:
本文件使用基于机器的人工智能翻译服务进行翻译。尽管我们力求准确,但请注意,自动翻译可能包含错误或不准确之处。应以原文的母语版本为权威来源。对于关键信息,建议寻求专业人工翻译服务。对于因使用本翻译而引起的任何误解或误读,我们概不负责。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/06-building-trustworthy-agents/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/06-building-trustworthy-agents/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 6896
} |
# 规划设计
## 简介
本课程将涵盖以下内容:
* 明确总体目标,并将复杂任务拆解为可管理的子任务。
* 利用结构化输出以生成更可靠且机器可读的响应。
* 应用事件驱动的方法来处理动态任务和意外输入。
## 学习目标
完成本课程后,您将能够:
* 为 AI 代理设定一个明确的总体目标,确保它清楚需要实现的内容。
* 将复杂任务分解为可管理的子任务,并以逻辑顺序组织它们。
* 为代理配备合适的工具(例如搜索工具或数据分析工具),决定何时以及如何使用这些工具,并处理可能出现的意外情况。
* 评估子任务的结果,衡量性能,并通过迭代改进最终输出。
## 定义总体目标并分解任务

大多数现实世界的任务都过于复杂,无法一步完成。AI 代理需要一个简洁的目标来指导其规划和行动。例如,考虑以下目标:
"生成一个为期三天的旅行行程。"
尽管这个目标表述得很简单,但它仍然需要进一步细化。目标越清晰,代理(以及任何人类协作者)就越能够专注于实现正确的结果,例如创建一个包含航班选项、酒店推荐和活动建议的全面行程。
### 任务分解
将大型或复杂的任务分解为更小的、以目标为导向的子任务,可以使其更易于管理。
以旅行行程为例,您可以将目标分解为:
* 航班预订
* 酒店预订
* 租车服务
* 个性化定制
每个子任务都可以由专门的代理或流程处理。例如,一个代理可能专注于寻找最佳航班优惠,另一个代理则负责酒店预订,等等。然后,一个协调或“下游”代理可以将这些结果整合成一个连贯的行程,供最终用户使用。
这种模块化方法还允许逐步改进。例如,您可以添加专门的代理来提供美食推荐或本地活动建议,从而随着时间的推移不断优化行程。
### 结构化输出
大型语言模型(LLMs)可以生成结构化输出(例如 JSON),这使得下游代理或服务更容易解析和处理。这在多代理环境中特别有用,我们可以在收到规划输出后执行这些任务。请参考此 [博客文章](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/cookbook/structured-output-agent.html) 以快速了解相关内容。
以下是一个简单规划代理的 Python 代码片段示例,它将目标分解为子任务并生成结构化计划:
### 多代理协作的规划代理
在此示例中,一个语义路由代理接收用户请求(例如,“我需要一个旅行的酒店计划。”)。
规划过程如下:
* 接收酒店计划:规划代理接收用户的消息,并基于系统提示(包括可用代理的详细信息)生成结构化的旅行计划。
* 列出代理及其工具:代理注册表保存了一份代理列表(例如航班、酒店、租车和活动代理)以及它们提供的功能或工具。
* 将计划分配给相应的代理:根据子任务的数量,规划代理会直接将消息发送给专门的代理(针对单任务场景),或者通过群聊管理器协调多代理协作。
* 总结结果:最后,规划代理总结生成的计划以确保清晰明了。
以下是展示这些步骤的 Python 代码示例:
```python
from pydantic import BaseModel
from enum import Enum
from typing import List, Optional, Union
class AgentEnum(str, Enum):
FlightBooking = "flight_booking"
HotelBooking = "hotel_booking"
CarRental = "car_rental"
ActivitiesBooking = "activities_booking"
DestinationInfo = "destination_info"
DefaultAgent = "default_agent"
GroupChatManager = "group_chat_manager"
# Travel SubTask Model
class TravelSubTask(BaseModel):
task_details: str
assigned_agent: AgentEnum # we want to assign the task to the agent
class TravelPlan(BaseModel):
main_task: str
subtasks: List[TravelSubTask]
is_greeting: bool
import json
import os
from typing import Optional
from autogen_core.models import UserMessage, SystemMessage, AssistantMessage
from autogen_ext.models.openai import AzureOpenAIChatCompletionClient
# Create the client with type-checked environment variables
client = AzureOpenAIChatCompletionClient(
azure_deployment=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
model=os.getenv("AZURE_OPENAI_DEPLOYMENT_NAME"),
api_version=os.getenv("AZURE_OPENAI_API_VERSION"),
azure_endpoint=os.getenv("AZURE_OPENAI_ENDPOINT"),
api_key=os.getenv("AZURE_OPENAI_API_KEY"),
)
from pprint import pprint
# Define the user message
messages = [
SystemMessage(content="""You are an planner agent.
Your job is to decide which agents to run based on the user's request.
Below are the available agents specialised in different tasks:
- FlightBooking: For booking flights and providing flight information
- HotelBooking: For booking hotels and providing hotel information
- CarRental: For booking cars and providing car rental information
- ActivitiesBooking: For booking activities and providing activity information
- DestinationInfo: For providing information about destinations
- DefaultAgent: For handling general requests""", source="system"),
UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melbourne", source="user"),
]
response = await client.create(messages=messages, extra_create_args={"response_format": TravelPlan})
# Ensure the response content is a valid JSON string before loading it
response_content: Optional[str] = response.content if isinstance(response.content, str) else None
if response_content is None:
raise ValueError("Response content is not a valid JSON string")
# Print the response content after loading it as JSON
pprint(json.loads(response_content))
```
上述代码的输出如下,您可以使用此结构化输出将任务路由到 `assigned_agent` 并向最终用户总结旅行计划:
```json
{
"is_greeting": "False",
"main_task": "Plan a family trip from Singapore to Melbourne.",
"subtasks": [
{
"assigned_agent": "flight_booking",
"task_details": "Book round-trip flights from Singapore to Melbourne."
},
{
"assigned_agent": "hotel_booking",
"task_details": "Find family-friendly hotels in Melbourne."
},
{
"assigned_agent": "car_rental",
"task_details": "Arrange a car rental suitable for a family of four in Melbourne."
},
{
"assigned_agent": "activities_booking",
"task_details": "List family-friendly activities in Melbourne."
},
{
"assigned_agent": "destination_info",
"task_details": "Provide information about Melbourne as a travel destination."
}
]
}
```
包含上述代码示例的示例笔记本可在 [这里](../../../07-planning-design/code_samples/07-autogen.ipynb) 获取。
### 迭代规划
某些任务需要反复调整或重新规划,其中一个子任务的结果可能会影响下一个子任务。例如,如果代理在预订航班时发现了意外的数据格式,它可能需要在继续酒店预订之前调整其策略。
此外,用户反馈(例如用户决定选择更早的航班)可能会触发部分重新规划。这种动态、迭代的方法可以确保最终解决方案符合现实世界的约束和不断变化的用户偏好。
例如,示例代码:
```python
from autogen_core.models import UserMessage, SystemMessage, AssistantMessage
#.. same as previous code and pass on the user history, current plan
messages = [
SystemMessage(content="""You are a planner agent to optimize the
Your job is to decide which agents to run based on the user's request.
Below are the available agents specialised in different tasks:
- FlightBooking: For booking flights and providing flight information
- HotelBooking: For booking hotels and providing hotel information
- CarRental: For booking cars and providing car rental information
- ActivitiesBooking: For booking activities and providing activity information
- DestinationInfo: For providing information about destinations
- DefaultAgent: For handling general requests""", source="system"),
UserMessage(content="Create a travel plan for a family of 2 kids from Singapore to Melboune", source="user"),
AssistantMessage(content=f"Previous travel plan - {TravelPlan}", source="assistant")
]
# .. re-plan and send the tasks to respective agents
```
有关更全面的规划,请参考 Magnetic One 的 [博客文章](https://www.microsoft.com/research/articles/magentic-one-a-generalist-multi-agent-system-for-solving-complex-tasks),以了解如何解决复杂任务。
## 总结
本文展示了如何创建一个能够动态选择定义代理的规划器。规划器的输出会将任务分解并分配给代理以执行任务。假设这些代理能够访问执行任务所需的功能/工具。除了代理之外,您还可以包括其他模式,例如反思、总结器、轮询聊天等,以进一步自定义。
## 其他资源
* 使用 o1 推理模型在规划复杂任务中表现出了相当高的先进性——TODO: 分享示例?
* Autogen Magnetic One - 一种通用多代理系统,用于解决复杂任务,并在多个具有挑战性的代理基准测试中取得了令人印象深刻的成果。参考:[autogen-magentic-one](https://github.com/microsoft/autogen/tree/main/python/packages/autogen-magentic-one)。在此实现中,协调器会创建特定任务的计划,并将这些任务委派给可用代理。除了规划之外,协调器还采用了一种跟踪机制来监控任务进度,并根据需要重新规划。
**免责声明**:
本文档通过基于机器的人工智能翻译服务进行翻译。虽然我们尽力确保准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原文档的原始语言版本为权威来源。对于关键信息,建议使用专业的人类翻译服务。对于因使用此翻译而引起的任何误解或误读,我们概不负责。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/07-planning-design/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/07-planning-design/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 7284
} |
# 多代理设计模式
当你开始一个涉及多个代理的项目时,就需要考虑多代理设计模式。然而,何时切换到多代理模式以及它的优势可能并不一目了然。
## 引言
在本课中,我们将尝试解答以下问题:
- 哪些场景适合应用多代理模式?
- 多代理相较于单一代理处理多个任务有什么优势?
- 实现多代理设计模式的核心构建模块是什么?
- 我们如何掌握多个代理之间的交互情况?
## 学习目标
完成本课后,你应该能够:
- 识别适合应用多代理模式的场景。
- 理解多代理相较于单一代理的优势。
- 掌握实现多代理设计模式的核心构建模块。
更大的意义是什么?
*多代理是一种设计模式,允许多个代理协同工作以实现共同目标。*
这一模式广泛应用于多个领域,包括机器人技术、自动化系统和分布式计算等。
## 多代理适用的场景
那么,哪些场景适合使用多代理模式呢?答案是有很多场景可以从多个代理的应用中受益,尤其是在以下情况下:
- **大规模工作负载**:大规模的工作负载可以被分解为较小的任务,并分配给不同的代理,从而实现并行处理并加快完成速度。例如,大型数据处理任务就属于这一类。
- **复杂任务**:复杂任务可以像大规模工作负载一样被分解为多个子任务,并分配给专注于特定方面的不同代理。例如,在自动驾驶汽车中,不同的代理分别负责导航、障碍物检测以及与其他车辆的通信。
- **多样化的专业技能**:不同的代理可以具备不同的专业技能,从而比单一代理更有效地处理任务的不同方面。例如,在医疗领域,代理可以分别负责诊断、制定治疗方案以及患者监测。
## 多代理相较于单一代理的优势
单一代理系统在处理简单任务时可能表现良好,但对于更复杂的任务,使用多个代理可以带来以下几个优势:
- **专业化**:每个代理可以专注于特定任务。而单一代理缺乏专业化,可能会在面对复杂任务时感到困惑。例如,它可能执行一个并不擅长的任务。
- **可扩展性**:通过增加更多代理来扩展系统比让单一代理超负荷工作更容易。
- **容错性**:如果一个代理失败,其他代理可以继续运行,从而确保系统的可靠性。
举个例子,假设我们为用户预订一次旅行。单一代理系统需要处理旅行预订过程的所有方面,从搜索航班到预订酒店和租车。如果由单一代理完成,这个代理需要具备处理所有这些任务的工具。这可能导致系统复杂且难以维护和扩展。而多代理系统可以分别让不同的代理专注于搜索航班、预订酒店和租车。这使得系统更加模块化、易于维护且具有可扩展性。
这可以类比为一个家庭式旅行社与连锁旅行社的对比。家庭式旅行社由一个代理处理旅行预订的所有方面,而连锁旅行社则由不同的代理分别处理不同方面的预订。
## 实现多代理设计模式的核心构建模块
在实现多代理设计模式之前,你需要了解构成这一模式的核心构建模块。
让我们通过再次审视用户旅行预订的例子来使这一点更加具体。在这种情况下,核心构建模块包括:
- **代理通信**:负责搜索航班、预订酒店和租车的代理需要相互通信并共享用户的偏好和限制条件。你需要决定这些通信的协议和方法。具体而言,负责搜索航班的代理需要与负责预订酒店的代理沟通,以确保酒店的预订日期与航班日期一致。这意味着代理需要共享用户的旅行日期,因此你需要决定*哪些代理共享信息以及如何共享信息*。
- **协调机制**:代理需要协调它们的行为以确保满足用户的偏好和限制。例如,用户可能偏好靠近机场的酒店,而限制条件可能是租车只能在机场提取。这意味着负责预订酒店的代理需要与负责租车的代理协调,以确保用户的偏好和限制得到满足。因此你需要决定*代理如何协调它们的行为*。
- **代理架构**:代理需要具备内部结构来做出决策并从与用户的交互中学习。例如,负责搜索航班的代理需要具备内部结构来决定向用户推荐哪些航班。这意味着你需要决定*代理如何做出决策并从与用户的交互中学习*。例如,负责搜索航班的代理可以使用机器学习模型,根据用户过去的偏好向其推荐航班。
- **多代理交互的可视性**:你需要能够掌握多个代理之间的交互情况。这意味着你需要工具和技术来跟踪代理的活动和交互。这可以通过日志记录和监控工具、可视化工具以及性能指标来实现。
- **多代理模式**:实现多代理系统可以采用不同的模式,例如集中式、分散式和混合式架构。你需要选择最适合你的用例的模式。
- **人类参与**:在大多数情况下,你需要在系统中保留人类参与,并指示代理在需要时请求人类介入。例如,用户可能会要求预订一个代理未推荐的特定酒店或航班,或者在预订前要求确认。
## 多代理交互的可视性
了解多个代理之间的交互情况非常重要。这种可视性对于调试、优化以及确保整体系统的有效性至关重要。为此,你需要工具和技术来跟踪代理的活动和交互。这可以通过日志记录和监控工具、可视化工具以及性能指标来实现。
例如,在用户旅行预订的场景中,你可以使用一个仪表板来显示每个代理的状态、用户的偏好和限制条件,以及代理之间的交互情况。这个仪表板可以显示用户的旅行日期、航班代理推荐的航班、酒店代理推荐的酒店以及租车代理推荐的租车选项。这将为你提供一个清晰的视图,了解代理之间的交互情况以及是否满足了用户的偏好和限制条件。
让我们更详细地看看这些方面:
- **日志记录和监控工具**:你需要为每个代理的每个动作进行日志记录。日志条目可以存储代理执行的动作、动作的时间以及动作的结果等信息。这些信息可以用于调试、优化等。
- **可视化工具**:可视化工具可以帮助你以更直观的方式查看代理之间的交互。例如,你可以使用图表展示代理之间的信息流。这可以帮助你识别系统中的瓶颈、低效以及其他问题。
- **性能指标**:性能指标可以帮助你跟踪多代理系统的有效性。例如,你可以跟踪完成任务所需的时间、每单位时间完成的任务数量以及代理推荐的准确性。这些信息可以帮助你识别改进空间并优化系统。
## 多代理模式
让我们探讨一些可以用于创建多代理应用的具体模式。以下是一些值得考虑的有趣模式:
### 群聊
这种模式适用于创建一个群聊应用,其中多个代理可以相互通信。典型的使用场景包括团队协作、客户支持和社交网络。
在这种模式中,每个代理代表群聊中的一个用户,消息通过某种消息协议在代理之间交换。代理可以向群聊发送消息、从群聊接收消息以及响应其他代理的消息。
这种模式可以通过集中式架构(所有消息通过中央服务器路由)或分散式架构(消息直接交换)实现。

### 任务交接
这种模式适用于创建一个应用,其中多个代理可以相互交接任务。
典型的使用场景包括客户支持、任务管理和工作流自动化。
在这种模式中,每个代理代表一个任务或工作流中的一个步骤,代理可以根据预定义规则将任务交接给其他代理。

### 协作过滤
这种模式适用于创建一个应用,其中多个代理可以协作为用户提供推荐。
为什么需要多个代理协作?因为每个代理可以拥有不同的专业技能,并以不同的方式为推荐过程做出贡献。
例如,用户想要获得关于股市中最佳股票的推荐:
- **行业专家**:一个代理可以是某个特定行业的专家。
- **技术分析**:另一个代理可以是技术分析的专家。
- **基本面分析**:还有一个代理可以是基本面分析的专家。通过协作,这些代理可以为用户提供更全面的推荐。

## 场景:退款流程
考虑一个客户尝试为某产品申请退款的场景,这一流程可能涉及多个代理。我们可以将这些代理分为专门针对退款流程的代理和可以用于其他流程的通用代理。
**专门针对退款流程的代理**:
以下是一些可能参与退款流程的代理:
- **客户代理**:代表客户,负责启动退款流程。
- **卖家代理**:代表卖家,负责处理退款。
- **支付代理**:代表支付流程,负责退还客户的付款。
- **解决方案代理**:代表问题解决流程,负责解决退款流程中出现的任何问题。
- **合规代理**:代表合规流程,负责确保退款流程符合相关法规和政策。
**通用代理**:
这些代理可以用于业务的其他部分。
- **物流代理**:代表物流流程,负责将产品退回给卖家。该代理既可以用于退款流程,也可以用于例如购买时的物流。
- **反馈代理**:代表反馈流程,负责收集客户的反馈。反馈可以在任何时候进行,而不仅限于退款流程。
- **升级代理**:代表升级流程,负责将问题升级到更高级别的支持。该代理可用于任何需要升级问题的流程。
- **通知代理**:代表通知流程,负责在退款流程的各个阶段向客户发送通知。
- **分析代理**:代表分析流程,负责分析与退款流程相关的数据。
- **审计代理**:代表审计流程,负责审计退款流程以确保其正确执行。
- **报告代理**:代表报告流程,负责生成退款流程的报告。
- **知识代理**:代表知识流程,负责维护与退款流程相关的信息知识库。此代理不仅可以掌握退款相关知识,还可以掌握业务的其他部分。
- **安全代理**:代表安全流程,负责确保退款流程的安全性。
- **质量代理**:代表质量流程,负责确保退款流程的质量。
以上列出了许多代理,包括专门针对退款流程的代理以及可以用于业务其他部分的通用代理。希望这些例子能帮助你了解如何为你的多代理系统决定使用哪些代理。
## 练习
这一课的练习是什么?
设计一个用于客户支持流程的多代理系统。确定流程中涉及的代理、它们的角色和职责,以及它们如何相互交互。既要考虑专门针对客户支持流程的代理,也要考虑可以用于业务其他部分的通用代理。
> 在查看下面的解决方案之前,先自己思考一下,你可能需要比预想中更多的代理。
> TIP:思考客户支持流程的不同阶段,同时考虑任何系统可能需要的代理。
## 解决方案
[解决方案](./solution/solution.md)
## 知识检查
问题:何时应该考虑使用多代理?
- [] A1: 当你有小型工作负载和简单任务时。
- [] A2: 当你有大型工作负载时。
- [] A3: 当你有简单任务时。
[测试解决方案](./solution/solution-quiz.md)
## 总结
在本课中,我们探讨了多代理设计模式,包括多代理适用的场景、多代理相较于单一代理的优势、实现多代理设计模式的核心构建模块,以及如何掌握多个代理之间的交互情况。
## 其他资源
- [Autogen设计模式](https://microsoft.github.io/autogen/stable/user-guide/core-user-guide/design-patterns/intro.html)
- [Agentic设计模式](https://www.analyticsvidhya.com/blog/2024/10/agentic-design-patterns/)
**免责声明**:
本文件使用基于机器的人工智能翻译服务进行翻译。尽管我们尽力确保准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言的文件作为权威来源。对于关键信息,建议使用专业人工翻译。对于因使用本翻译而引起的任何误解或误读,我们概不负责。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/08-multi-agent/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/08-multi-agent/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 5205
} |
# 元认知在人工智能代理中的应用
## 介绍
欢迎学习关于人工智能代理中元认知的课程!本章专为对人工智能代理如何思考其自身思维过程感兴趣的初学者设计。在本课结束时,您将理解关键概念,并掌握将元认知应用于人工智能代理设计的实际示例。
## 学习目标
完成本课程后,您将能够:
1. 理解代理定义中推理循环的影响。
2. 使用计划和评估技术帮助自我纠正的代理。
3. 创建能够操控代码完成任务的代理。
## 元认知简介
元认知是指涉及思考自己思维的高级认知过程。对于人工智能代理来说,这意味着能够基于自我意识和过去的经验来评估和调整其行为。
### 什么是元认知?
元认知,或称“思考思维”,是一种高级认知过程,涉及对自身认知过程的自我意识和自我调节。在人工智能领域,元认知使代理能够评估和调整其策略和行为,从而提升问题解决和决策能力。通过理解元认知,您可以设计出不仅更智能,而且更具适应性和效率的人工智能代理。
### 元认知在人工智能代理中的重要性
元认知在人工智能代理设计中具有重要作用,主要体现在以下几个方面:

- **自我反思**:代理可以评估自身表现并找出改进的地方。
- **适应性**:代理可以根据过去的经验和不断变化的环境调整其策略。
- **错误修正**:代理可以自主检测和纠正错误,从而提高结果的准确性。
- **资源管理**:代理可以通过规划和评估行为来优化资源的使用,例如时间和计算能力。
## 人工智能代理的组成部分
在深入探讨元认知过程之前,首先需要了解人工智能代理的基本组成部分。一个人工智能代理通常包括:
- **角色**:代理的个性和特征,定义其与用户的交互方式。
- **工具**:代理可以执行的能力和功能。
- **技能**:代理所具备的知识和专业能力。
这些组件协同工作,创建一个能够执行特定任务的“专业单元”。
**示例**:考虑一个旅行代理服务,该代理不仅计划您的假期,还能根据实时数据和过去的客户旅程经验调整路径。
### 示例:旅行代理服务中的元认知
假设您正在设计一个由人工智能驱动的旅行代理服务。该代理“旅行代理”协助用户规划假期。为了融入元认知,“旅行代理”需要基于自我意识和过去的经验来评估和调整其行为。
#### 当前任务
当前任务是帮助用户规划去巴黎的旅行。
#### 完成任务的步骤
1. **收集用户偏好**:询问用户的旅行日期、预算、兴趣(例如博物馆、美食、购物)以及任何具体需求。
2. **检索信息**:搜索符合用户偏好的航班、住宿、景点和餐馆。
3. **生成推荐**:提供包含航班详情、酒店预订和建议活动的个性化行程。
4. **根据反馈调整**:询问用户对推荐的反馈,并进行必要的调整。
#### 所需资源
- 访问航班和酒店预订数据库。
- 巴黎景点和餐馆的信息。
- 之前交互中的用户反馈数据。
#### 经验和自我反思
“旅行代理”通过元认知评估其表现并从过去的经验中学习。例如:
1. **分析用户反馈**:旅行代理会审查用户反馈,以确定哪些推荐受到欢迎,哪些不受欢迎,并据此调整未来的建议。
2. **适应性**:如果用户之前提到不喜欢拥挤的地方,旅行代理会在未来避免在高峰时段推荐热门景点。
3. **错误修正**:如果旅行代理在过去的预订中出现错误,例如推荐了已满的酒店,它会学习在推荐之前更严格地检查可用性。
#### 实际开发示例
以下是旅行代理在融入元认知时的代码简化示例:
```python
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):
# Search for flights, hotels, and attractions based on preferences
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)
# Analyze feedback and adjust future recommendations
self.user_preferences = adjust_preferences(self.user_preferences, feedback)
# Example usage
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)
```
#### 元认知为何重要
- **自我反思**:代理可以分析其表现并找出改进的地方。
- **适应性**:代理可以根据反馈和变化的条件调整策略。
- **错误修正**:代理可以自主检测和纠正错误。
- **资源管理**:代理可以优化资源使用,例如时间和计算能力。
通过融入元认知,“旅行代理”可以提供更个性化和准确的旅行推荐,从而提升整体用户体验。
---
## 2. 代理中的规划
规划是人工智能代理行为的关键组成部分。它涉及根据当前状态、资源和可能的障碍来制定实现目标的步骤。
### 规划的要素
- **当前任务**:明确定义任务。
- **完成任务的步骤**:将任务分解为可管理的步骤。
- **所需资源**:确定必要的资源。
- **经验**:利用过去的经验来指导规划。
**示例**:以下是“旅行代理”在有效协助用户规划旅行时需要采取的步骤:
### 旅行代理的步骤
1. **收集用户偏好**
- 询问用户关于旅行日期、预算、兴趣和任何具体需求的详细信息。
- 示例:“您计划什么时候旅行?”“您的预算范围是多少?”“您在假期中喜欢哪些活动?”
2. **检索信息**
- 根据用户偏好搜索相关的旅行选项。
- **航班**:寻找符合用户预算和偏好的航班。
- **住宿**:找到符合用户对位置、价格和设施要求的酒店或租赁房产。
- **景点和餐馆**:识别与用户兴趣一致的热门景点、活动和餐饮选择。
3. **生成推荐**
- 将检索到的信息编制成个性化行程。
- 提供航班选项、酒店预订和建议活动的详细信息,确保推荐符合用户偏好。
4. **向用户展示行程**
- 与用户分享拟议的行程以供审查。
- 示例:“这是为您巴黎之行建议的行程,包括航班详情、酒店预订以及推荐的活动和餐馆。请告诉我您的想法!”
5. **收集反馈**
- 询问用户对拟议行程的反馈。
- 示例:“您喜欢这些航班选项吗?”“酒店是否符合您的需求?”“是否有您想添加或删除的活动?”
6. **根据反馈调整**
- 根据用户反馈修改行程。
- 对航班、住宿和活动推荐进行必要的更改,以更好地符合用户偏好。
7. **最终确认**
- 向用户展示更新后的行程以供最终确认。
- 示例:“我已根据您的反馈进行了调整。这是更新后的行程。您觉得如何?”
8. **预订并确认**
- 在用户批准行程后,进行航班、住宿和任何预定活动的预订。
- 将确认详情发送给用户。
9. **提供持续支持**
- 在用户旅行前和旅行期间,随时协助处理任何更改或额外请求。
- 示例:“如果您在旅行期间需要任何进一步的帮助,请随时与我联系!”
### 示例交互
```python
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)
# Example usage within a booing request
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)
```
## 3. 校正型 RAG 系统
首先,让我们了解 RAG 工具与预加载上下文的区别:

### 检索增强生成(RAG)
RAG 将检索系统与生成模型结合。当提出查询时,检索系统从外部来源获取相关文档或数据,并使用这些检索到的信息增强生成模型的输入。这有助于模型生成更准确和上下文相关的响应。
在 RAG 系统中,代理从知识库中检索相关信息,并利用这些信息生成适当的响应或行动。
### 校正型 RAG 方法
校正型 RAG 方法专注于使用 RAG 技术来纠正错误并提高人工智能代理的准确性。这包括:
1. **提示技术**:使用特定提示指导代理检索相关信息。
2. **工具**:实施使代理能够评估检索信息相关性并生成准确响应的算法和机制。
3. **评估**:持续评估代理的表现,并进行调整以提高其准确性和效率。
#### 示例:搜索代理中的校正型 RAG
考虑一个从网络检索信息以回答用户查询的搜索代理。校正型 RAG 方法可能涉及:
1. **提示技术**:根据用户输入制定搜索查询。
2. **工具**:使用自然语言处理和机器学习算法对搜索结果进行排序和过滤。
3. **评估**:分析用户反馈以识别和纠正检索信息中的不准确之处。
### 校正型 RAG 在旅行代理中的应用
校正型 RAG(检索增强生成)增强了人工智能在检索和生成信息时纠正任何不准确之处的能力。以下是“旅行代理”如何使用校正型 RAG 方法提供更准确和相关的旅行推荐:
这包括:
- **提示技术**:使用特定提示指导代理检索相关信息。
- **工具**:实施使代理能够评估检索信息相关性并生成准确响应的算法和机制。
- **评估**:持续评估代理的表现,并进行调整以提高其准确性和效率。
#### 在旅行代理中实施校正型 RAG 的步骤
1. **初始用户交互**
- “旅行代理”收集用户的初始偏好,例如目的地、旅行日期、预算和兴趣。
- 示例:```python
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
```
2. **信息检索**
- “旅行代理”根据用户偏好检索有关航班、住宿、景点和餐馆的信息。
- 示例:```python
flights = search_flights(preferences)
hotels = search_hotels(preferences)
attractions = search_attractions(preferences)
```
3. **生成初始推荐**
- “旅行代理”利用检索到的信息生成个性化行程。
- 示例:```python
itinerary = create_itinerary(flights, hotels, attractions)
print("Suggested Itinerary:", itinerary)
```
4. **收集用户反馈**
- “旅行代理”询问用户对初始推荐的反馈。
- 示例:```python
feedback = {
"liked": ["Louvre Museum"],
"disliked": ["Eiffel Tower (too crowded)"]
}
```
5. **校正型 RAG 过程**
- **提示技术**:
```
```markdown
旅行代理根据用户反馈制定新的搜索查询。
- 示例:```python
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
```
- **工具**:旅行代理使用算法对新的搜索结果进行排名和筛选,强调基于用户反馈的相关性。
- 示例:```python
new_attractions = search_attractions(preferences)
new_itinerary = create_itinerary(flights, hotels, new_attractions)
print("Updated Itinerary:", new_itinerary)
```
- **评估**:旅行代理通过分析用户反馈并进行必要的调整,持续评估其推荐的相关性和准确性。
- 示例:```python
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)
```
#### 实用示例
以下是一个结合纠正型RAG方法的简化Python代码示例,用于旅行代理:
```python
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
# Example usage
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)
```
### 预加载上下文
预加载上下文是指在处理查询之前,将相关的上下文或背景信息加载到模型中。这意味着模型从一开始就可以访问这些信息,从而帮助其生成更有见地的响应,而无需在过程中检索额外的数据。以下是一个预加载上下文在旅行代理应用中的简化Python示例:
```python
class TravelAgent:
def __init__(self):
# Pre-load popular destinations and their information
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):
# Fetch destination information from pre-loaded context
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}."
# Example usage
travel_agent = TravelAgent()
print(travel_agent.get_destination_info("Paris"))
print(travel_agent.get_destination_info("Tokyo"))
```
#### 解释
1. **初始化 (`__init__` method)**: The `TravelAgent` class pre-loads a dictionary containing information about popular destinations such as Paris, Tokyo, New York, and Sydney. This dictionary includes details like the country, currency, language, and major attractions for each destination.
2. **Retrieving Information (`get_destination_info` method)**: When a user queries about a specific destination, the `get_destination_info` 方法)**:该方法从预加载的上下文字典中获取相关信息。通过预加载上下文,旅行代理应用可以快速响应用户查询,而无需实时从外部来源检索信息。这使得应用更加高效和响应迅速。
### 以目标为导向启动计划并迭代
以目标为导向启动计划是指从一开始就明确目标或预期结果。通过事先定义目标,模型可以在整个迭代过程中以此为指导原则。这有助于确保每次迭代都朝着实现预期结果的方向推进,使过程更加高效和专注。以下是如何为旅行代理启动计划并迭代的示例:
### 场景
旅行代理希望为客户制定一个定制化的假期计划。目标是根据客户的偏好和预算创建一个能最大化客户满意度的旅行行程。
### 步骤
1. 定义客户的偏好和预算。
2. 基于这些偏好启动初始计划。
3. 通过迭代优化计划,最大化客户满意度。
#### Python代码
```python
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']
# Example usage
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)
```
#### 代码解释
1. **初始化 (`__init__` method)**: The `TravelAgent` class is initialized with a list of potential destinations, each having attributes like name, cost, and activity type.
2. **Bootstrapping the Plan (`bootstrap_plan` method)**: This method creates an initial travel plan based on the client's preferences and budget. It iterates through the list of destinations and adds them to the plan if they match the client's preferences and fit within the budget.
3. **Matching Preferences (`match_preferences` method)**: This method checks if a destination matches the client's preferences.
4. **Iterating the Plan (`iterate_plan` method)**: This method refines the initial plan by trying to replace each destination in the plan with a better match, considering the client's preferences and budget constraints.
5. **Calculating Cost (`calculate_cost` 方法)**:该方法计算当前计划的总成本,包括潜在的新目的地。
#### 示例用法
- **初始计划**:旅行代理基于客户的观光偏好和$2000的预算创建初始计划。
- **优化计划**:旅行代理迭代优化计划,以满足客户的偏好和预算。
通过以明确的目标(例如最大化客户满意度)启动计划并迭代优化,旅行代理可以为客户创建一个定制化且优化的旅行行程。这种方法确保旅行计划从一开始就符合客户的偏好和预算,并在每次迭代中不断改进。
### 利用LLM进行重新排序和评分
大型语言模型(LLM)可以通过评估检索到的文档或生成的响应的相关性和质量,用于重新排序和评分。以下是其工作原理:
**检索**:初始检索步骤根据查询获取一组候选文档或响应。
**重新排序**:LLM评估这些候选项,并根据其相关性和质量重新排序。此步骤确保最相关和高质量的信息优先呈现。
**评分**:LLM为每个候选项分配分数,反映其相关性和质量。这有助于选择最适合用户的响应或文档。
通过利用LLM进行重新排序和评分,系统可以提供更准确和上下文相关的信息,从而改善整体用户体验。以下是旅行代理如何使用大型语言模型(LLM)根据用户偏好重新排序和评分旅行目的地的示例:
#### 场景 - 基于偏好的旅行
旅行代理希望根据客户的偏好推荐最佳旅行目的地。LLM将帮助重新排序和评分目的地,以确保呈现最相关的选项。
#### 步骤:
1. 收集用户偏好。
2. 检索潜在的旅行目的地列表。
3. 使用LLM根据用户偏好重新排序和评分目的地。
以下是如何更新之前的示例以使用Azure OpenAI服务:
#### 要求
1. 您需要拥有一个Azure订阅。
2. 创建一个Azure OpenAI资源并获取您的API密钥。
#### 示例Python代码
```python
import requests
import json
class TravelAgent:
def __init__(self, destinations):
self.destinations = destinations
def get_recommendations(self, preferences, api_key, endpoint):
# Generate a prompt for the Azure OpenAI
prompt = self.generate_prompt(preferences)
# Define headers and payload for the request
headers = {
'Content-Type': 'application/json',
'Authorization': f'Bearer {api_key}'
}
payload = {
"prompt": prompt,
"max_tokens": 150,
"temperature": 0.7
}
# Call the Azure OpenAI API to get the re-ranked and scored destinations
response = requests.post(endpoint, headers=headers, json=payload)
response_data = response.json()
# Extract and return the recommendations
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
# Example usage
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)
```
#### 代码解释 - 偏好推荐器
1. **初始化**:将 `TravelAgent` class is initialized with a list of potential travel destinations, each having attributes like name and description.
2. **Getting Recommendations (`get_recommendations` method)**: This method generates a prompt for the Azure OpenAI service based on the user's preferences and makes an HTTP POST request to the Azure OpenAI API to get re-ranked and scored destinations.
3. **Generating Prompt (`generate_prompt` method)**: This method constructs a prompt for the Azure OpenAI, including the user's preferences and the list of destinations. The prompt guides the model to re-rank and score the destinations based on the provided preferences.
4. **API Call**: The `requests` library is used to make an HTTP POST request to the Azure OpenAI API endpoint. The response contains the re-ranked and scored destinations.
5. **Example Usage**: The travel agent collects user preferences (e.g., interest in sightseeing and diverse culture) and uses the Azure OpenAI service to get re-ranked and scored recommendations for travel destinations.
Make sure to replace `your_azure_openai_api_key` with your actual Azure OpenAI API key and `https://your-endpoint.com/...` 替换为Azure OpenAI部署的实际端点URL。
通过利用LLM进行重新排序和评分,旅行代理可以为客户提供更个性化和相关的旅行推荐,从而增强客户的整体体验。
### RAG: 提示技术与工具
检索增强生成(RAG)既可以作为一种提示技术,也可以作为开发AI代理的工具。理解两者之间的区别可以帮助您更有效地在项目中利用RAG。
#### RAG作为提示技术
**是什么?**
- 作为提示技术,RAG涉及制定特定查询或提示,以指导从大型语料库或数据库中检索相关信息。然后将这些信息用于生成响应或采取行动。
**如何工作:**
1. **制定提示**:根据任务或用户输入创建结构良好的提示或查询。
2. **检索信息**:使用提示从预先存在的知识库或数据集中搜索相关数据。
3. **生成响应**:将检索到的信息与生成式AI模型结合,以生成全面且连贯的响应。
**旅行代理示例**:
- 用户输入:"我想参观巴黎的博物馆。"
- 提示:"查找巴黎的顶级博物馆。"
- 检索到的信息:关于卢浮宫、奥赛博物馆等的详细信息。
- 生成的响应:"以下是巴黎的一些顶级博物馆:卢浮宫、奥赛博物馆和蓬皮杜中心。"
#### RAG作为工具
**是什么?**
- 作为工具,RAG是一个集成系统,可以自动化检索和生成过程,使开发人员无需为每个查询手动编写提示即可实现复杂的AI功能。
**如何工作:**
1. **集成**:将RAG嵌入AI代理的架构中,使其能够自动处理检索和生成任务。
2. **自动化**:工具管理整个过程,从接收用户输入到生成最终响应,无需为每一步明确提示。
3. **高效性**:通过简化检索和生成过程,提高代理的性能,使其能够更快、更准确地响应。
**旅行代理示例**:
- 用户输入:"我想参观巴黎的博物馆。"
- RAG工具:自动检索关于博物馆的信息并生成响应。
- 生成的响应:"以下是巴黎的一些顶级博物馆:卢浮宫、奥赛博物馆和蓬皮杜中心。"
### 比较
| 方面 | 提示技术 | 工具 |
|------------------------|-------------------------------------------------------------|-------------------------------------------------------|
| **手动与自动**| 每个查询手动制定提示。 | 检索和生成的自动化过程。 |
| **控制** | 对检索过程提供更多控制。 | 简化并自动化检索和生成。|
| **灵活性** | 允许根据具体需求定制提示。 | 更适合大规模实现。 |
| **复杂性** | 需要设计和调整提示。 | 更容易集成到AI代理的架构中。 |
### 实用示例
**提示技术示例:**
```python
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)
```
**工具示例:**
```python
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)
```
```
```markdown
巴黎最好的博物馆?"). - **导航意图**:用户希望导航到特定的网站或页面(例如,“卢浮宫官网”)。 - **交易意图**:用户希望执行交易,例如预订航班或购买商品(例如,“预订飞往巴黎的航班”)。 2. **上下文意识**: - 分析用户查询的上下文有助于准确识别其意图。这包括考虑先前的互动、用户偏好以及当前查询的具体细节。 3. **自然语言处理(NLP)**: - 使用NLP技术来理解和解释用户提供的自然语言查询。这包括实体识别、情感分析和查询解析等任务。 4. **个性化**: - 根据用户的历史记录、偏好和反馈个性化搜索结果,提高检索信息的相关性。 #### 实际示例:旅行代理中的意图搜索 让我们以旅行代理为例,看看如何实现意图搜索。 1. **收集用户偏好** ```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
``` 2. **理解用户意图** ```python
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"
``` 3. **上下文意识** ```python
def analyze_context(query, user_history):
# Combine current query with user history to understand context
context = {
"current_query": query,
"user_history": user_history
}
return context
``` 4. **搜索并个性化结果** ```python
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):
# Example search logic for informational intent
results = search_web(f"best {preferences['interests']} in {preferences['destination']}")
return results
def search_navigation(query):
# Example search logic for navigational intent
results = search_web(query)
return results
def search_transaction(query, preferences):
# Example search logic for transactional intent
results = search_web(f"book {query} to {preferences['destination']}")
return results
def personalize_results(results, user_history):
# Example personalization logic
personalized = [result for result in results if result not in user_history]
return personalized[:10] # Return top 10 personalized results
``` 5. **示例用法** ```python
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)
``` --- ## 4. 作为工具的代码生成 代码生成代理使用AI模型来编写和执行代码,解决复杂问题并实现任务自动化。 ### 代码生成代理 代码生成代理使用生成式AI模型来编写和执行代码。这些代理可以通过生成和运行各种编程语言的代码来解决复杂问题、实现任务自动化并提供有价值的见解。 #### 实际应用 1. **自动代码生成**:为特定任务生成代码片段,例如数据分析、网络爬取或机器学习。 2. **作为RAG的SQL**:使用SQL查询从数据库中检索和操作数据。 3. **问题解决**:创建并执行代码以解决特定问题,例如优化算法或分析数据。 #### 示例:用于数据分析的代码生成代理 假设您正在设计一个代码生成代理。其工作流程可能如下: 1. **任务**:分析数据集以识别趋势和模式。 2. **步骤**: - 将数据集加载到数据分析工具中。 - 生成SQL查询以过滤和聚合数据。 - 执行查询并检索结果。 - 使用结果生成可视化和见解。 3. **所需资源**:访问数据集、数据分析工具和SQL能力。 4. **经验**:利用过去的分析结果提高未来分析的准确性和相关性。 ### 示例:旅行代理的代码生成代理 在此示例中,我们将设计一个代码生成代理Travel Agent,通过生成和执行代码来协助用户规划旅行。该代理可以处理诸如获取旅行选项、筛选结果以及使用生成式AI编制行程等任务。 #### 代码生成代理概述 1. **收集用户偏好**:收集用户输入的信息,如目的地、旅行日期、预算和兴趣。 2. **生成用于获取数据的代码**:生成代码片段以检索航班、酒店和景点数据。 3. **执行生成的代码**:运行生成的代码以获取实时信息。 4. **生成行程**:将获取的数据编译为个性化的旅行计划。 5. **根据反馈调整**:接收用户反馈并重新生成代码以优化结果。 #### 分步实现 1. **收集用户偏好** ```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
``` 2. **生成用于获取数据的代码** ```python
def generate_code_to_fetch_data(preferences):
# Example: Generate code to search for flights based on user preferences
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):
# Example: Generate code to search for hotels
code = f"""
def search_hotels():
import requests
response = requests.get('https://api.example.com/hotels', params={preferences})
return response.json()
"""
return code
``` 3. **执行生成的代码** ```python
def execute_code(code):
# Execute the generated code using 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)
``` 4. **生成行程** ```python
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)
``` 5. **根据反馈调整** ```python
def adjust_based_on_feedback(feedback, preferences):
# Adjust preferences based on user feedback
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)
# Regenerate and execute code with updated preferences
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)
``` ### 利用环境意识和推理 基于表格的模式确实可以通过利用环境意识和推理来增强查询生成过程。以下是实现方式的示例: 1. **理解模式**:系统将理解表格的模式,并利用此信息来支持查询生成。 2. **根据反馈调整**:系统将根据反馈调整用户偏好,并推断需要更新模式中的哪些字段。 3. **生成和执行查询**:系统将生成并执行查询,以根据新的偏好获取更新的航班和酒店数据。 以下是一个包含这些概念的更新Python代码示例: ```python
def adjust_based_on_feedback(feedback, preferences, schema):
# Adjust preferences based on user feedback
if "liked" in feedback:
preferences["favorites"] = feedback["liked"]
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
# Reasoning based on schema to adjust other related preferences
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):
# Custom logic to adjust preferences based on schema and feedback
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):
# Generate code to fetch flight data based on updated preferences
return f"fetch_flights(preferences={preferences})"
def generate_code_to_fetch_hotels(preferences):
# Generate code to fetch hotel data based on updated preferences
return f"fetch_hotels(preferences={preferences})"
def execute_code(code):
# Simulate execution of code and return mock data
return {"data": f"Executed: {code}"}
def generate_itinerary(flights, hotels, attractions):
# Generate itinerary based on flights, hotels, and attractions
return {"flights": flights, "hotels": hotels, "attractions": attractions}
# Example schema
schema = {
"favorites": {"positive_adjustment": "increase", "negative_adjustment": "decrease", "default": "neutral"},
"avoid": {"positive_adjustment": "decrease", "negative_adjustment": "increase", "default": "neutral"}
}
# Example usage
preferences = {"favorites": "sightseeing", "avoid": "crowded places"}
feedback = {"liked": ["Louvre Museum"], "disliked": ["Eiffel Tower (too crowded)"]}
updated_preferences = adjust_based_on_feedback(feedback, preferences, schema)
# Regenerate and execute code with updated preferences
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)
``` #### 解释 - 基于反馈的预订 1. **模式意识**:`schema` dictionary defines how preferences should be adjusted based on feedback. It includes fields like `favorites` and `avoid`, with corresponding adjustments.
2. **Adjusting Preferences (`adjust_based_on_feedback` method)**: This method adjusts preferences based on user feedback and the schema.
3. **Environment-Based Adjustments (`adjust_based_on_environment`方法)**:此方法根据模式和反馈自定义调整。 4. **生成和执行查询**:系统生成代码以根据调整后的偏好获取更新的航班和酒店数据,并模拟执行这些查询。 5. **生成行程**:系统根据新的航班、酒店和景点数据创建更新后的行程。 通过使系统具有环境意识并基于模式进行推理,它可以生成更准确和相关的查询,从而提供更好的旅行推荐和更个性化的用户体验。 ### 使用SQL作为检索增强生成(RAG)技术 SQL(结构化查询语言)是与数据库交互的强大工具。当用作检索增强生成(RAG)方法的一部分时,SQL可以从数据库中检索相关数据,以为AI代理中的响应或操作提供信息并生成它们。让我们探讨如何在旅行代理的上下文中使用SQL作为RAG技术。 #### 关键概念 1. **数据库交互**: - 使用SQL查询数据库,检索相关信息并操作数据。 - 示例:从旅行数据库中获取航班详情、酒店信息和景点。 2. **与RAG集成**: - 根据用户输入和偏好生成SQL查询。 - 然后使用检索到的数据生成个性化推荐或操作。 3. **动态查询生成**: - AI代理根据上下文和用户需求生成动态SQL查询。 - 示例:定制SQL查询以根据预算、日期和兴趣筛选结果。 #### 应用 - **自动代码生成**:为特定任务生成代码片段。 - **作为RAG的SQL**:使用SQL查询操作数据。 - **问题解决**:创建并执行代码以解决问题。 **示例**:一个数据分析代理: 1. **任务**:分析数据集以发现趋势。 2. **步骤**: - 加载数据集。 - 生成SQL查询以过滤数据。 - 执行查询并检索结果。 - 生成可视化和见解。 3. **资源**:数据集访问权限、SQL能力。 4. **经验**:利用过去的结果提高未来分析的准确性。 #### 实际示例:在旅行代理中使用SQL 1. **收集用户偏好** ```python
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
``` 2. **生成SQL查询** ```python
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
``` 3. **执行SQL查询** ```python
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
``` 4. **生成推荐** ```python
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)
``` #### 示例SQL查询 1. **航班查询** ```sql
SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate';
``` 2. **酒店查询** ```sql
SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate';
``` 3. **景点查询** ```sql
SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine';
``` 通过将SQL作为检索增强生成(RAG)技术的一部分,像Travel Agent这样的AI代理可以动态检索并利用相关数据,提供准确且个性化的推荐。 ### 结论 元认知是一种强大的工具,可以显著增强AI代理的能力。通过引入元认知过程,您可以设计出更智能、更适应性强且更高效的代理。使用附加资源进一步探索AI代理中元认知的迷人世界。
```
**免责声明**:
本文件使用基于机器的人工智能翻译服务进行翻译。尽管我们尽力确保翻译的准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言的文件作为权威来源。对于关键信息,建议使用专业人工翻译。我们对因使用本翻译而产生的任何误解或误读不承担责任。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/09-metacognition/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/09-metacognition/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 34862
} |
# AI代理的生产部署
## 简介
本课程将涵盖以下内容:
- 如何有效规划将AI代理部署到生产环境中。
- 部署AI代理到生产环境时可能遇到的常见错误和问题。
- 如何在保持AI代理性能的同时管理成本。
## 学习目标
完成本课程后,您将了解如何/能够:
- 提高生产环境中AI代理系统的性能、成本效率和效果的技术。
- 如何评估您的AI代理及其具体方法。
- 控制AI代理生产部署成本的策略。
部署值得信赖的AI代理非常重要。请参阅“构建值得信赖的AI代理”课程以了解更多内容。
## 评估AI代理
在部署AI代理之前、期间和之后,建立一个完善的评估系统至关重要。这可以确保您的系统与您和用户的目标保持一致。
评估AI代理时,您需要能够评估的不仅仅是代理的输出,还包括AI代理所运行的整个系统。这包括但不限于:
- 初始模型请求。
- 代理识别用户意图的能力。
- 代理识别执行任务所需正确工具的能力。
- 工具对代理请求的响应。
- 代理解释工具响应的能力。
- 用户对代理响应的反馈。
这种方法可以帮助您以更模块化的方式识别改进领域。然后,您可以更高效地监控模型、提示词、工具以及其他组件更改的效果。
## AI代理的常见问题及潜在解决方案
| **问题** | **潜在解决方案** |
| -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AI代理任务执行不一致 | - 优化提供给AI代理的提示词,明确目标。<br>- 确定是否可以将任务分解为子任务,并通过多个代理分别处理。 |
| AI代理陷入连续循环 | - 确保定义清晰的终止条件,让代理知道何时停止流程。<br>- 对于需要推理和规划的复杂任务,使用专为推理任务设计的大型模型。 |
| AI代理调用工具表现不佳 | - 在代理系统外测试并验证工具的输出。<br>- 优化工具的参数设置、提示词和命名方式。 |
| 多代理系统表现不一致 | - 优化提供给每个代理的提示词,确保它们具体且相互区分。<br>- 构建一个使用“路由”或控制器代理的分层系统,以确定哪个代理是正确的选择。 |
## 成本管理
以下是一些在生产环境中部署AI代理的成本管理策略:
- **缓存响应** - 识别常见请求和任务,并在它们通过您的代理系统之前提供响应,这是减少类似请求量的好方法。您甚至可以通过更基础的AI模型实现一个流程,来判断某个请求与缓存请求的相似度。
- **使用小型模型** - 小型语言模型(SLM)在某些代理使用场景中表现良好,并能显著降低成本。如前所述,建立一个评估系统来确定并比较其与大型模型的性能是了解SLM在您的使用场景中表现的最佳方式。
- **使用路由模型** - 类似的策略是使用不同规模的模型组合。您可以使用LLM/SLM或无服务器函数,根据请求的复杂性将其路由到最合适的模型。这不仅能降低成本,还能确保复杂任务的性能表现。
## 恭喜
这是“AI代理入门”课程的最后一课。
我们计划根据反馈和这个快速发展的行业变化不断增加新课程,因此欢迎您不久后再回来查看。
如果您想继续学习和构建AI代理,欢迎加入 [Azure AI Community Discord](https://discord.gg/kzRShWzttr)。
我们在这里举办工作坊、社区圆桌会议以及“问我任何问题”环节。
此外,我们还有一个学习资料集合,其中包含更多帮助您开始在生产环境中构建AI代理的资源。
**免责声明**:
本文件使用基于机器的人工智能翻译服务进行翻译。尽管我们努力确保翻译的准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原始语言的文件作为权威来源。对于关键信息,建议使用专业的人类翻译服务。对于因使用本翻译而产生的任何误解或误读,我们概不负责。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/10-ai-agents-production/README.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/10-ai-agents-production/README.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 2532
} |
A: A2: Wenn Sie eine große Arbeitsbelastung haben
**Haftungsausschluss**:
Dieses Dokument wurde mit KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, beachten Sie bitte, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die sich aus der Nutzung dieser Übersetzung ergeben. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/de/08-multi-agent/solution/solution-quiz.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/08-multi-agent/solution/solution-quiz.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 622
} |
**Agentspezifisch für den Kundenserviceprozess**:
- **Kunden-Agent**: Dieser Agent repräsentiert den Kunden und ist dafür verantwortlich, den Supportprozess zu initiieren.
- **Support-Agent**: Dieser Agent repräsentiert den Supportprozess und ist dafür verantwortlich, dem Kunden Unterstützung zu leisten.
- **Eskalations-Agent**: Dieser Agent repräsentiert den Eskalationsprozess und ist dafür verantwortlich, Probleme an eine höhere Supportebene weiterzuleiten.
- **Lösungs-Agent**: Dieser Agent repräsentiert den Lösungsprozess und ist dafür verantwortlich, auftretende Probleme während des Supportprozesses zu lösen.
- **Feedback-Agent**: Dieser Agent repräsentiert den Feedbackprozess und ist dafür verantwortlich, Feedback vom Kunden einzuholen.
- **Benachrichtigungs-Agent**: Dieser Agent repräsentiert den Benachrichtigungsprozess und ist dafür verantwortlich, dem Kunden in verschiedenen Phasen des Supportprozesses Benachrichtigungen zu senden.
- **Analyse-Agent**: Dieser Agent repräsentiert den Analyseprozess und ist dafür verantwortlich, Daten im Zusammenhang mit dem Supportprozess zu analysieren.
- **Audit-Agent**: Dieser Agent repräsentiert den Auditprozess und ist dafür verantwortlich, den Supportprozess zu prüfen, um sicherzustellen, dass er korrekt durchgeführt wird.
- **Bericht-Agent**: Dieser Agent repräsentiert den Berichtprozess und ist dafür verantwortlich, Berichte über den Supportprozess zu erstellen.
- **Wissens-Agent**: Dieser Agent repräsentiert den Wissensprozess und ist dafür verantwortlich, eine Wissensdatenbank mit Informationen zum Supportprozess zu pflegen.
- **Sicherheits-Agent**: Dieser Agent repräsentiert den Sicherheitsprozess und ist dafür verantwortlich, die Sicherheit des Supportprozesses zu gewährleisten.
- **Qualitäts-Agent**: Dieser Agent repräsentiert den Qualitätsprozess und ist dafür verantwortlich, die Qualität des Supportprozesses sicherzustellen.
- **Compliance-Agent**: Dieser Agent repräsentiert den Compliance-Prozess und ist dafür verantwortlich, sicherzustellen, dass der Supportprozess den Vorschriften und Richtlinien entspricht.
- **Schulungs-Agent**: Dieser Agent repräsentiert den Schulungsprozess und ist dafür verantwortlich, Support-Agenten darin zu schulen, wie sie Kunden unterstützen können.
Das sind einige Agenten – war das mehr oder weniger, als Sie erwartet haben?
**Haftungsausschluss**:
Dieses Dokument wurde mithilfe von KI-gestützten maschinellen Übersetzungsdiensten übersetzt. Obwohl wir uns um Genauigkeit bemühen, beachten Sie bitte, dass automatisierte Übersetzungen Fehler oder Ungenauigkeiten enthalten können. Das Originaldokument in seiner ursprünglichen Sprache sollte als maßgebliche Quelle betrachtet werden. Für kritische Informationen wird eine professionelle menschliche Übersetzung empfohlen. Wir übernehmen keine Haftung für Missverständnisse oder Fehlinterpretationen, die aus der Nutzung dieser Übersetzung entstehen. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/de/08-multi-agent/solution/solution.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/de/08-multi-agent/solution/solution.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 2960
} |
A: A2: Cuando tienes una gran carga de trabajo
**Descargo de responsabilidad**:
Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por garantizar la precisión, tenga en cuenta que las traducciones automatizadas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse como la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de malentendidos o interpretaciones erróneas que puedan surgir del uso de esta traducción. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/es/08-multi-agent/solution/solution-quiz.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/08-multi-agent/solution/solution-quiz.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 640
} |
**Agentes específicos para el proceso de soporte al cliente**:
- **Agente del cliente**: Este agente representa al cliente y es responsable de iniciar el proceso de soporte.
- **Agente de soporte**: Este agente representa el proceso de soporte y es responsable de brindar asistencia al cliente.
- **Agente de escalamiento**: Este agente representa el proceso de escalamiento y es responsable de escalar problemas a un nivel superior de soporte.
- **Agente de resolución**: Este agente representa el proceso de resolución y es responsable de resolver cualquier problema que surja durante el proceso de soporte.
- **Agente de retroalimentación**: Este agente representa el proceso de retroalimentación y es responsable de recopilar opiniones del cliente.
- **Agente de notificaciones**: Este agente representa el proceso de notificaciones y es responsable de enviar avisos al cliente en varias etapas del proceso de soporte.
- **Agente de analítica**: Este agente representa el proceso de análisis y es responsable de analizar datos relacionados con el proceso de soporte.
- **Agente de auditoría**: Este agente representa el proceso de auditoría y es responsable de auditar el proceso de soporte para garantizar que se lleve a cabo correctamente.
- **Agente de reportes**: Este agente representa el proceso de reportes y es responsable de generar informes sobre el proceso de soporte.
- **Agente de conocimiento**: Este agente representa el proceso de gestión del conocimiento y es responsable de mantener una base de información relacionada con el proceso de soporte.
- **Agente de seguridad**: Este agente representa el proceso de seguridad y es responsable de garantizar la seguridad del proceso de soporte.
- **Agente de calidad**: Este agente representa el proceso de calidad y es responsable de asegurar la calidad del proceso de soporte.
- **Agente de cumplimiento**: Este agente representa el proceso de cumplimiento y es responsable de garantizar que el proceso de soporte cumpla con regulaciones y políticas.
- **Agente de capacitación**: Este agente representa el proceso de capacitación y es responsable de entrenar a los agentes de soporte en cómo asistir a los clientes.
¿Son bastantes agentes, no? ¿Era más o menos de lo que esperabas?
**Descargo de responsabilidad**:
Este documento ha sido traducido utilizando servicios de traducción automática basados en inteligencia artificial. Si bien nos esforzamos por garantizar la precisión, tenga en cuenta que las traducciones automáticas pueden contener errores o imprecisiones. El documento original en su idioma nativo debe considerarse la fuente autorizada. Para información crítica, se recomienda una traducción profesional realizada por humanos. No nos hacemos responsables de ningún malentendido o interpretación errónea que surja del uso de esta traducción. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/es/08-multi-agent/solution/solution.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/es/08-multi-agent/solution/solution.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 2850
} |
A : A2 : Lorsque vous avez une charge de travail importante
**Avertissement** :
Ce document a été traduit à l'aide de services de traduction automatique basés sur l'intelligence artificielle. Bien que nous nous efforcions d'assurer l'exactitude, veuillez noter que les traductions automatisées peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de faire appel à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/fr/08-multi-agent/solution/solution-quiz.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/08-multi-agent/solution/solution-quiz.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 694
} |
**Agents spécifiques au processus de support client** :
- **Agent client** : Cet agent représente le client et est chargé d'initier le processus de support.
- **Agent de support** : Cet agent représente le processus de support et est responsable de fournir de l'assistance au client.
- **Agent d'escalade** : Cet agent représente le processus d'escalade et est chargé de transmettre les problèmes à un niveau de support supérieur.
- **Agent de résolution** : Cet agent représente le processus de résolution et est chargé de résoudre les problèmes qui surviennent pendant le processus de support.
- **Agent de feedback** : Cet agent représente le processus de retour d'information et est responsable de collecter les retours du client.
- **Agent de notification** : Cet agent représente le processus de notification et est chargé d'envoyer des notifications au client à différentes étapes du processus de support.
- **Agent d'analyse** : Cet agent représente le processus d'analyse et est chargé d'analyser les données liées au processus de support.
- **Agent d'audit** : Cet agent représente le processus d'audit et est responsable de vérifier que le processus de support est correctement exécuté.
- **Agent de rapport** : Cet agent représente le processus de création de rapports et est chargé de générer des rapports sur le processus de support.
- **Agent de connaissance** : Cet agent représente le processus de gestion des connaissances et est chargé de maintenir une base de connaissances relative au processus de support.
- **Agent de sécurité** : Cet agent représente le processus de sécurité et est chargé de garantir la sécurité du processus de support.
- **Agent de qualité** : Cet agent représente le processus de gestion de la qualité et est chargé d'assurer la qualité du processus de support.
- **Agent de conformité** : Cet agent représente le processus de conformité et est chargé de garantir que le processus de support respecte les réglementations et les politiques en vigueur.
- **Agent de formation** : Cet agent représente le processus de formation et est chargé de former les agents de support sur la manière d'assister les clients.
Cela fait pas mal d'agents. Est-ce plus ou moins que ce à quoi vous vous attendiez ?
**Avertissement** :
Ce document a été traduit à l'aide de services de traduction basés sur l'intelligence artificielle. Bien que nous nous efforcions d'assurer l'exactitude, veuillez noter que les traductions automatiques peuvent contenir des erreurs ou des inexactitudes. Le document original dans sa langue d'origine doit être considéré comme la source faisant autorité. Pour des informations critiques, il est recommandé de faire appel à une traduction humaine professionnelle. Nous déclinons toute responsabilité en cas de malentendus ou d'interprétations erronées résultant de l'utilisation de cette traduction. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/fr/08-multi-agent/solution/solution.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/fr/08-multi-agent/solution/solution.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 2881
} |
A: A2: 當你有大量工作量時
**免責聲明**:
本文件經由機器翻譯AI服務進行翻譯。儘管我們致力於確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原始語言的文件為權威來源。對於關鍵資訊,建議使用專業人工翻譯。我們對因使用本翻譯而引起的任何誤解或錯誤解釋概不負責。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/hk/08-multi-agent/solution/solution-quiz.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/08-multi-agent/solution/solution-quiz.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 143
} |
**專門為客戶支援流程設計的代理**:
- **客戶代理**: 呢個代理代表客戶,負責開啟支援流程。
- **支援代理**: 呢個代理代表支援流程,負責為客戶提供協助。
- **升級代理**: 呢個代理代表升級流程,負責將問題升級到更高層次嘅支援。
- **解決代理**: 呢個代理代表解決流程,負責解決支援過程中出現嘅任何問題。
- **反饋代理**: 呢個代理代表反饋流程,負責收集客戶嘅反饋意見。
- **通知代理**: 呢個代理代表通知流程,負責喺支援流程嘅唔同階段向客戶發送通知。
- **分析代理**: 呢個代理代表分析流程,負責分析與支援流程相關嘅數據。
- **審核代理**: 呢個代理代表審核流程,負責審核支援流程以確保其正確執行。
- **報告代理**: 呢個代理代表報告流程,負責生成有關支援流程嘅報告。
- **知識代理**: 呢個代理代表知識流程,負責維護與支援流程相關嘅知識庫。
- **安全代理**: 呢個代理代表安全流程,負責確保支援流程嘅安全性。
- **質量代理**: 呢個代理代表質量流程,負責確保支援流程嘅質量。
- **合規代理**: 呢個代理代表合規流程,負責確保支援流程符合規範及政策要求。
- **培訓代理**: 呢個代理代表培訓流程,負責培訓支援代理如何協助客戶。
呢啲代理數量多唔多?係咪超出你預期?
**免責聲明**:
本文件使用機器翻譯服務進行翻譯。我們致力於提供準確的翻譯,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原始語言的文件作為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而引起的任何誤解或誤讀概不負責。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/hk/08-multi-agent/solution/solution.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/hk/08-multi-agent/solution/solution.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 702
} |
A: A2: 大量の作業量がある場合
**免責事項**:
本書類は、機械ベースのAI翻訳サービスを使用して翻訳されています。正確性を期すよう努めておりますが、自動翻訳には誤りや不正確な部分が含まれる可能性があります。原文(元の言語の文書)を公式な情報源としてご参照ください。重要な情報については、専門の人間による翻訳を推奨します。本翻訳の使用に起因する誤解や解釈の誤りについて、当方は一切の責任を負いかねます。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/08-multi-agent/solution/solution-quiz.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/08-multi-agent/solution/solution-quiz.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 211
} |
**カスタマーサポートプロセスに特化したエージェント**:
- **カスタマーエージェント**: このエージェントは顧客を代表し、サポートプロセスを開始する役割を担います。
- **サポートエージェント**: このエージェントはサポートプロセスを代表し、顧客への支援を提供する役割を担います。
- **エスカレーションエージェント**: このエージェントはエスカレーションプロセスを代表し、問題をより高いサポートレベルにエスカレーションする役割を担います。
- **解決エージェント**: このエージェントは解決プロセスを代表し、サポートプロセス中に発生する問題を解決する役割を担います。
- **フィードバックエージェント**: このエージェントはフィードバックプロセスを代表し、顧客からのフィードバックを収集する役割を担います。
- **通知エージェント**: このエージェントは通知プロセスを代表し、サポートプロセスのさまざまな段階で顧客に通知を送る役割を担います。
- **分析エージェント**: このエージェントは分析プロセスを代表し、サポートプロセスに関連するデータを分析する役割を担います。
- **監査エージェント**: このエージェントは監査プロセスを代表し、サポートプロセスが正しく実行されているかを監査する役割を担います。
- **レポートエージェント**: このエージェントはレポートプロセスを代表し、サポートプロセスに関するレポートを作成する役割を担います。
- **ナレッジエージェント**: このエージェントはナレッジプロセスを代表し、サポートプロセスに関連する情報のナレッジベースを維持する役割を担います。
- **セキュリティエージェント**: このエージェントはセキュリティプロセスを代表し、サポートプロセスの安全性を確保する役割を担います。
- **品質エージェント**: このエージェントは品質プロセスを代表し、サポートプロセスの品質を確保する役割を担います。
- **コンプライアンスエージェント**: このエージェントはコンプライアンスプロセスを代表し、サポートプロセスが規制やポリシーに準拠していることを確認する役割を担います。
- **トレーニングエージェント**: このエージェントはトレーニングプロセスを代表し、サポートエージェントが顧客を支援する方法についてトレーニングを行う役割を担います。
これだけのエージェントがいますが、想像していたより多かったですか?それとも少なかったですか?
**免責事項**:
この文書は、AIによる機械翻訳サービスを使用して翻訳されています。正確性を期すよう努めておりますが、自動翻訳には誤りや不正確な箇所が含まれる可能性があります。元の言語で記載された原文が正式な情報源として考慮されるべきです。重要な情報については、専門の人間による翻訳をお勧めします。本翻訳の利用に起因する誤解や誤った解釈について、当方は一切の責任を負いません。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ja/08-multi-agent/solution/solution.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ja/08-multi-agent/solution/solution.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 1285
} |
A: A2: 작업량이 많을 때
**면책 조항**:
이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 노력하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원본 문서의 원어 버전이 신뢰할 수 있는 권위 있는 자료로 간주되어야 합니다. 중요한 정보의 경우, 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해서는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/08-multi-agent/solution/solution-quiz.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/08-multi-agent/solution/solution-quiz.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 241
} |
**고객 지원 프로세스를 위한 에이전트들**:
- **Customer agent (고객 에이전트)**: 이 에이전트는 고객을 나타내며, 지원 프로세스를 시작하는 역할을 담당합니다.
- **Support agent (지원 에이전트)**: 이 에이전트는 지원 프로세스를 나타내며, 고객에게 도움을 제공하는 역할을 담당합니다.
- **Escalation agent (승격 에이전트)**: 이 에이전트는 문제를 상위 지원 단계로 승격시키는 과정을 나타내며, 이를 담당합니다.
- **Resolution agent (해결 에이전트)**: 이 에이전트는 문제 해결 과정을 나타내며, 지원 프로세스 중 발생하는 문제를 해결하는 역할을 담당합니다.
- **Feedback agent (피드백 에이전트)**: 이 에이전트는 피드백 과정을 나타내며, 고객으로부터 피드백을 수집하는 역할을 담당합니다.
- **Notification agent (알림 에이전트)**: 이 에이전트는 알림 과정을 나타내며, 지원 프로세스의 여러 단계에서 고객에게 알림을 보내는 역할을 담당합니다.
- **Analytics agent (분석 에이전트)**: 이 에이전트는 분석 과정을 나타내며, 지원 프로세스와 관련된 데이터를 분석하는 역할을 담당합니다.
- **Audit agent (감사 에이전트)**: 이 에이전트는 감사 과정을 나타내며, 지원 프로세스가 올바르게 수행되고 있는지 감사하는 역할을 담당합니다.
- **Reporting agent (보고 에이전트)**: 이 에이전트는 보고 과정을 나타내며, 지원 프로세스에 대한 보고서를 생성하는 역할을 담당합니다.
- **Knowledge agent (지식 에이전트)**: 이 에이전트는 지식 과정을 나타내며, 지원 프로세스와 관련된 정보를 유지 관리하는 지식 베이스를 관리하는 역할을 담당합니다.
- **Security agent (보안 에이전트)**: 이 에이전트는 보안 과정을 나타내며, 지원 프로세스의 보안을 보장하는 역할을 담당합니다.
- **Quality agent (품질 에이전트)**: 이 에이전트는 품질 과정을 나타내며, 지원 프로세스의 품질을 보장하는 역할을 담당합니다.
- **Compliance agent (준수 에이전트)**: 이 에이전트는 준수 과정을 나타내며, 지원 프로세스가 규정과 정책을 준수하도록 보장하는 역할을 담당합니다.
- **Training agent (교육 에이전트)**: 이 에이전트는 교육 과정을 나타내며, 고객을 지원하는 방법에 대해 지원 에이전트를 교육하는 역할을 담당합니다.
이 정도 에이전트가 있네요. 예상했던 것보다 많았나요, 아니면 적었나요?
**면책 조항**:
이 문서는 기계 기반 AI 번역 서비스를 사용하여 번역되었습니다. 정확성을 위해 최선을 다하고 있지만, 자동 번역에는 오류나 부정확성이 포함될 수 있음을 유의하시기 바랍니다. 원어로 작성된 원본 문서를 권위 있는 자료로 간주해야 합니다. 중요한 정보의 경우, 전문적인 인간 번역을 권장드립니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해서는 책임을 지지 않습니다. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/ko/08-multi-agent/solution/solution.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/ko/08-multi-agent/solution/solution.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 1543
} |
A: A2: Quando você tem uma grande carga de trabalho
**Aviso Legal**:
Este documento foi traduzido utilizando serviços de tradução automática baseados em IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte oficial. Para informações críticas, recomenda-se a tradução humana profissional. Não nos responsabilizamos por mal-entendidos ou interpretações incorretas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/08-multi-agent/solution/solution-quiz.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/08-multi-agent/solution/solution-quiz.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 548
} |
**Agentes específicos para o processo de suporte ao cliente**:
- **Agente do cliente**: Este agente representa o cliente e é responsável por iniciar o processo de suporte.
- **Agente de suporte**: Este agente representa o processo de suporte e é responsável por fornecer assistência ao cliente.
- **Agente de escalonamento**: Este agente representa o processo de escalonamento e é responsável por encaminhar problemas para um nível superior de suporte.
- **Agente de resolução**: Este agente representa o processo de resolução e é responsável por resolver quaisquer problemas que surjam durante o processo de suporte.
- **Agente de feedback**: Este agente representa o processo de feedback e é responsável por coletar feedback do cliente.
- **Agente de notificações**: Este agente representa o processo de notificações e é responsável por enviar notificações ao cliente em várias etapas do processo de suporte.
- **Agente de análise**: Este agente representa o processo de análise e é responsável por analisar dados relacionados ao processo de suporte.
- **Agente de auditoria**: Este agente representa o processo de auditoria e é responsável por auditar o processo de suporte para garantir que está sendo realizado corretamente.
- **Agente de relatórios**: Este agente representa o processo de relatórios e é responsável por gerar relatórios sobre o processo de suporte.
- **Agente de conhecimento**: Este agente representa o processo de conhecimento e é responsável por manter uma base de conhecimento com informações relacionadas ao processo de suporte.
- **Agente de segurança**: Este agente representa o processo de segurança e é responsável por garantir a segurança do processo de suporte.
- **Agente de qualidade**: Este agente representa o processo de qualidade e é responsável por assegurar a qualidade do processo de suporte.
- **Agente de conformidade**: Este agente representa o processo de conformidade e é responsável por garantir que o processo de suporte esteja em conformidade com regulamentos e políticas.
- **Agente de treinamento**: Este agente representa o processo de treinamento e é responsável por treinar os agentes de suporte sobre como ajudar os clientes.
São bastantes agentes, foi mais ou menos do que você esperava?
**Aviso Legal**:
Este documento foi traduzido utilizando serviços de tradução baseados em IA. Embora nos esforcemos para garantir a precisão, esteja ciente de que traduções automatizadas podem conter erros ou imprecisões. O documento original em seu idioma nativo deve ser considerado a fonte oficial. Para informações críticas, recomenda-se a tradução profissional feita por humanos. Não nos responsabilizamos por mal-entendidos ou interpretações incorretas decorrentes do uso desta tradução. | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/pt/08-multi-agent/solution/solution.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/pt/08-multi-agent/solution/solution.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 2744
} |
A: A2: 當你有大量工作量時
**免責聲明**:
本文件使用基於機器的人工智能翻譯服務進行翻譯。儘管我們努力確保準確性,但請注意,自動翻譯可能包含錯誤或不準確之處。應以原始語言的文件作為權威來源。對於關鍵資訊,建議尋求專業人工翻譯。我們對因使用此翻譯而產生的任何誤解或錯誤解讀概不負責。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/08-multi-agent/solution/solution-quiz.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/08-multi-agent/solution/solution-quiz.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 151
} |
**專門用於客戶支援流程的代理**:
- **Customer agent(客戶代理)**:此代理代表客戶,負責啟動支援流程。
- **Support agent(支援代理)**:此代理代表支援流程,負責為客戶提供協助。
- **Escalation agent(升級代理)**:此代理代表升級流程,負責將問題升級至更高層級的支援。
- **Resolution agent(解決代理)**:此代理代表問題解決流程,負責處理支援過程中出現的任何問題。
- **Feedback agent(回饋代理)**:此代理代表回饋流程,負責收集客戶的意見和建議。
- **Notification agent(通知代理)**:此代理代表通知流程,負責在支援流程的不同階段向客戶發送通知。
- **Analytics agent(分析代理)**:此代理代表數據分析流程,負責分析與支援流程相關的數據。
- **Audit agent(審核代理)**:此代理代表審核流程,負責審查支援流程以確保其正確執行。
- **Reporting agent(報告代理)**:此代理代表報告流程,負責生成有關支援流程的報告。
- **Knowledge agent(知識代理)**:此代理代表知識管理流程,負責維護與支援流程相關的知識庫。
- **Security agent(安全代理)**:此代理代表安全流程,負責確保支援流程的安全性。
- **Quality agent(品質代理)**:此代理代表品質管理流程,負責確保支援流程的服務品質。
- **Compliance agent(合規代理)**:此代理代表合規流程,負責確保支援流程符合相關規範與政策。
- **Training agent(培訓代理)**:此代理代表培訓流程,負責培訓支援代理如何更好地協助客戶。
這麼多代理,跟你預期的相比,是多了還是少了呢?
**免責聲明**:
本文件是使用機器翻譯服務進行翻譯的。我們雖然致力於確保翻譯的準確性,但請注意,自動翻譯可能包含錯誤或不精確之處。應以原始語言的文件作為權威來源。對於關鍵信息,建議尋求專業人工翻譯。我們對因使用本翻譯而產生的任何誤解或錯誤解釋概不負責。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/tw/08-multi-agent/solution/solution.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/tw/08-multi-agent/solution/solution.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 951
} |
A: A2: 当你有大量工作时
**免责声明**:
本文档使用基于机器的人工智能翻译服务进行翻译。尽管我们努力确保翻译的准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原文档的原始语言版本作为权威来源。对于关键信息,建议寻求专业人工翻译。我们对于因使用本翻译而引起的任何误解或误读不承担责任。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/08-multi-agent/solution/solution-quiz.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/08-multi-agent/solution/solution-quiz.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 156
} |
**专门用于客户支持流程的代理**:
- **客户代理(Customer agent)**:此代理代表客户,负责启动支持流程。
- **支持代理(Support agent)**:此代理代表支持流程,负责为客户提供协助。
- **升级代理(Escalation agent)**:此代理代表升级流程,负责将问题升级到更高级别的支持。
- **解决代理(Resolution agent)**:此代理代表解决流程,负责解决支持流程中出现的任何问题。
- **反馈代理(Feedback agent)**:此代理代表反馈流程,负责收集客户的反馈意见。
- **通知代理(Notification agent)**:此代理代表通知流程,负责在支持流程的各个阶段向客户发送通知。
- **分析代理(Analytics agent)**:此代理代表分析流程,负责分析与支持流程相关的数据。
- **审计代理(Audit agent)**:此代理代表审计流程,负责审查支持流程以确保其正确执行。
- **报告代理(Reporting agent)**:此代理代表报告流程,负责生成有关支持流程的报告。
- **知识代理(Knowledge agent)**:此代理代表知识流程,负责维护与支持流程相关的信息知识库。
- **安全代理(Security agent)**:此代理代表安全流程,负责确保支持流程的安全性。
- **质量代理(Quality agent)**:此代理代表质量流程,负责确保支持流程的质量。
- **合规代理(Compliance agent)**:此代理代表合规流程,负责确保支持流程符合相关法规和政策。
- **培训代理(Training agent)**:此代理代表培训流程,负责培训支持代理如何为客户提供帮助。
这些代理数量怎么样,是不是比你预期的多或少呢?
**免责声明**:
本文件通过基于机器的AI翻译服务进行翻译。尽管我们努力确保准确性,但请注意,自动翻译可能包含错误或不准确之处。应以原文所在语言的文件为权威来源。对于关键信息,建议使用专业人工翻译。因使用本翻译而引起的任何误解或误读,我们概不负责。 | {
"source": "microsoft/ai-agents-for-beginners",
"title": "translations/zh/08-multi-agent/solution/solution.md",
"url": "https://github.com/microsoft/ai-agents-for-beginners/blob/main/translations/zh/08-multi-agent/solution/solution.md",
"date": "2024-11-28T10:42:52",
"stars": 3317,
"description": "10 Lessons to Get Started Building AI Agents",
"file_size": 940
} |
# ai-by-hand-excel
AI by Hand ✍️ Exercises in Excel

## Basic
* Softmax
* LeakyReLU
* Temperature
## Advanced
* Multi Layer Perceptron (MLP)
* Backpropagation
* Recurrent Neural Network (RNN)
* Long Short Term Memory (LSTM) (+ Seq2Seq)
* Extended Long Short Term Memory (xLSTM)
* Residual Network (ResNet)
* Transformer - Simple
* Transformer - Full Stack
* Self-Attention
* Multihead Attention
* Autoencoder (AE)
* Mamba
* AlphaFold
## Lectures
### 🔥 NEW: DeepSeek
Multi-head Latent Attention + Mixture of Experts
(blank only)
[View](https://o365coloradoedu-my.sharepoint.com/:x:/g/personal/peye9704_colorado_edu/EfAlZg6tnotMtEb3N0TA_98BWFdAiqD24mc-MqETTDoVUQ?e=dh4Ncq)
| [Download](lectures/DeepSeek-blank.xlsx)

## Workbook
1. Dot Product
2. Matrix Multiplication
3. Linear Layer
## Coming Soon
* Generative Adversarial Network (GAN)
* Variational Autoencoder (VAE)
* U-Net
* CLIP
* more ... | {
"source": "ImagineAILab/ai-by-hand-excel",
"title": "README.md",
"url": "https://github.com/ImagineAILab/ai-by-hand-excel/blob/main/README.md",
"date": "2024-09-15T13:21:00",
"stars": 3313,
"description": null,
"file_size": 952
} |
# Contributor Covenant Code of Conduct
## Our Pledge
We as members, contributors, and leaders pledge to make participation in our
community a harassment-free experience for everyone, regardless of age, body
size, visible or invisible disability, ethnicity, sex characteristics, gender
identity and expression, level of experience, education, socio-economic status,
nationality, personal appearance, race, religion, or sexual identity
and orientation.
We pledge to act and interact in ways that contribute to an open, welcoming,
diverse, inclusive, and healthy community.
## Our Standards
Examples of behavior that contributes to a positive environment for our
community include:
* Demonstrating empathy and kindness toward other people
* Being respectful of differing opinions, viewpoints, and experiences
* Giving and gracefully accepting constructive feedback
* Accepting responsibility and apologizing to those affected by our mistakes,
and learning from the experience
* Focusing on what is best not just for us as individuals, but for the
overall community
Examples of unacceptable behavior include:
* The use of sexualized language or imagery, and sexual attention or
advances of any kind
* Trolling, insulting or derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or email
address, without their explicit permission
* Other conduct which could reasonably be considered inappropriate in a
professional setting
## Enforcement Responsibilities
Community leaders are responsible for clarifying and enforcing our standards of
acceptable behavior and will take appropriate and fair corrective action in
response to any behavior that they deem inappropriate, threatening, offensive,
or harmful.
Community leaders have the right and responsibility to remove, edit, or reject
comments, commits, code, wiki edits, issues, and other contributions that are
not aligned to this Code of Conduct, and will communicate reasons for moderation
decisions when appropriate.
## Scope
This Code of Conduct applies within all community spaces, and also applies when
an individual is officially representing the community in public spaces.
Examples of representing our community include using an official e-mail address,
posting via an official social media account, or acting as an appointed
representative at an online or offline event.
## Enforcement
Instances of abusive, harassing, or otherwise unacceptable behavior may be
reported to the community leaders responsible for enforcement at
https://x.com/OmAI_lab.
All complaints will be reviewed and investigated promptly and fairly.
All community leaders are obligated to respect the privacy and security of the
reporter of any incident.
## Enforcement Guidelines
Community leaders will follow these Community Impact Guidelines in determining
the consequences for any action they deem in violation of this Code of Conduct:
### 1. Correction
**Community Impact**: Use of inappropriate language or other behavior deemed
unprofessional or unwelcome in the community.
**Consequence**: A private, written warning from community leaders, providing
clarity around the nature of the violation and an explanation of why the
behavior was inappropriate. A public apology may be requested.
### 2. Warning
**Community Impact**: A violation through a single incident or series
of actions.
**Consequence**: A warning with consequences for continued behavior. No
interaction with the people involved, including unsolicited interaction with
those enforcing the Code of Conduct, for a specified period of time. This
includes avoiding interactions in community spaces as well as external channels
like social media. Violating these terms may lead to a temporary or
permanent ban.
### 3. Temporary Ban
**Community Impact**: A serious violation of community standards, including
sustained inappropriate behavior.
**Consequence**: A temporary ban from any sort of interaction or public
communication with the community for a specified period of time. No public or
private interaction with the people involved, including unsolicited interaction
with those enforcing the Code of Conduct, is allowed during this period.
Violating these terms may lead to a permanent ban.
### 4. Permanent Ban
**Community Impact**: Demonstrating a pattern of violation of community
standards, including sustained inappropriate behavior, harassment of an
individual, or aggression toward or disparagement of classes of individuals.
**Consequence**: A permanent ban from any sort of public interaction within
the community.
## Attribution
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
version 2.0, available at
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
Community Impact Guidelines were inspired by [Mozilla's code of conduct
enforcement ladder](https://github.com/mozilla/diversity).
[homepage]: https://www.contributor-covenant.org
For answers to common questions about this code of conduct, see the FAQ at
https://www.contributor-covenant.org/faq. Translations are available at
https://www.contributor-covenant.org/translations. | {
"source": "om-ai-lab/VLM-R1",
"title": "CODE_OF_CONDUCT.md",
"url": "https://github.com/om-ai-lab/VLM-R1/blob/main/CODE_OF_CONDUCT.md",
"date": "2025-02-06T16:12:30",
"stars": 3312,
"description": "Solve Visual Understanding with Reinforced VLMs",
"file_size": 5223
} |
# VLM-R1: A stable and generalizable R1-style Large Vision-Language Model
<font size=4><div align='center' > [[🤗 Demo](https://huggingface.co/spaces/omlab/VLM-R1-Referral-Expression)] [[🤗 Data](https://huggingface.co/datasets/omlab/VLM-R1)] [[🤗 Checkpoint](https://huggingface.co/omlab/Qwen2.5VL-3B-VLM-R1-REC-500steps)] </div></font>
<div style="margin-left: 5%;">
<img src="./assets/performance.png" width="600"/>
</div>
Since the introduction of [Deepseek-R1](https://github.com/deepseek-ai/DeepSeek-R1), numerous works have emerged focusing on reproducing and improving upon it. In this project, we propose VLM-R1, a stable and generalizable R1-style Large Vision-Language Model.
Specifically, for the task of Referring Expression Comprehension (REC), we trained [Qwen2.5-VL](https://github.com/QwenLM/Qwen2.5-VL) using both R1 and SFT approaches. The results reveal that, on the in-domain test data, the performance of the SFT model is slightly lower than that of the R1 model (as shown at the top of the figure above). However, on the out-of-domain test data, the SFT model’s performance deteriorates significantly as the number of steps increases, while the R1 model shows a steady improvement (as shown at the bottom of the figure above).
## Update
- 2025-02-21: We release the [checkpoint](https://huggingface.co/omlab/Qwen2.5VL-3B-VLM-R1-REC-500steps) of the VLM-R1 REC model.
- 2025-02-20: We release the script for [general data loading](#for-your-own-data).
- 2025-02-19: We incorporate an explanation of the [SFT](#sft) method.
- 2025-02-17: We release the VLM-R1 REC [Demo](https://huggingface.co/spaces/omlab/VLM-R1-Referral-Expression) on Hugging Face Spaces.
- 2025-02-15: We release the VLM-R1 repository and [GRPO](#grpo) training script.
## Setup
```bash
conda create -n vlm-r1 python=3.10
conda activate vlm-r1
bash setup.sh
```
## Training
### Referring Expression Comprehension (REC)
#### GRPO
> 1. Download the [COCO Train2014 image](https://huggingface.co/datasets/omlab/VLM-R1/resolve/main/train2014.zip) and unzip it, and we refer to the image dir as `<your_image_root>`.
> 2. Download the [RefCOCO/+/g and RefGTA Annotation files](https://huggingface.co/datasets/omlab/VLM-R1/resolve/main/rec_jsons_processed.zip) and unzip it (RefGTA is used for out-of-domain evaluation).
> 3. Write the path of the annotation files in the `src/open-r1-multimodal/data_config/rec.yaml` file.
```bash
datasets:
- json_path: /path/to/refcoco_train.json
- json_path: /path/to/refcocop_train.json
- json_path: /path/to/refcocog_train.json
```
> 4. ```bash src/open-r1-multimodal/run_grpo_rec.sh```
> NOTE: If you encounter 'CUDA out of memory' error, you can try to (1) set `gradient_checkpointing` as `true`, (2) reduce the `num_generations`, or (3) use lora (the script will be updated soon).
```bash
cd src/open-r1-multimodal
torchrun --nproc_per_node="8" \
--nnodes="1" \
--node_rank="0" \
--master_addr="127.0.0.1" \
--master_port="12346" \
src/open_r1/grpo_rec.py \
--deepspeed local_scripts/zero3.json \
--output_dir output/$RUN_NAME \
--model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \
--dataset_name data_config/rec.yaml \
--image_root <your_image_root> \
--max_prompt_length 1024 \
--num_generations 8 \
--per_device_train_batch_size 1 \
--gradient_accumulation_steps 2 \
--logging_steps 1 \
--bf16 \
--torch_dtype bfloat16 \
--data_seed 42 \
--report_to wandb \
--gradient_checkpointing false \
--attn_implementation flash_attention_2 \
--num_train_epochs 2 \
--run_name $RUN_NAME \
--save_steps 100 \
--save_only_model true
```

<!--  -->
#### Multi-Node GRPO
For multi-node training, please refers to [multinode_training_demo.sh](src/open-r1-multimodal/multinode_training_demo.sh).
#### SFT
We use [LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory) to train the SFT model.
> 1. Clone the [LLaMA-Factory](https://github.com/hiyouga/LLaMA-Factory) repository and install the dependencies.
```bash
git clone https://github.com/hiyouga/LLaMA-Factory.git
cd LLaMA-Factory
pip install -e ".[torch,metrics]"
```
> 2. Download the dataset_info.json, mllm_rec_json.json, and qwen2_5_vl_full_sft.yaml we provided [here](https://huggingface.co/datasets/omlab/VLM-R1/tree/main/sft_related). Put the json files in the `LLaMA-Factory/data` directory and the yaml file in the `LLaMA-Factory/examples/train_full` directory.
> 3. Run the following command to train the SFT model.
```bash
llamafactory-cli train examples/train_full/qwen2_5_vl_full_sft.yaml
```
### For your own data
We also support data loading the jsonl data of this format in [`src/open-r1-multimodal/src/open_r1/grpo_jsonl.py`](src/open-r1-multimodal/src/open_r1/grpo_jsonl.py). Please note that you may need to use different reward functions for your specialized tasks. Welcome to PR to add your own reward functions or share any other interesting findings!
The jsonl has the format as follows:
```json
{"id": 1, "image": "Clevr_CoGenT_TrainA_R1/data/images/CLEVR_trainA_000001_16885.png", "conversations": [{"from": "human", "value": "<image>What number of purple metallic balls are there?"}, {"from": "gpt", "value": "0"}]}
```
Note: The image path in the jsonl file should be relative to the image folder specified in `--image_folders`. The absolute path of the input image is constructed as `os.path.join(image_folder, data['image'])`. For example:
- If your jsonl has `"image": "folder1/image1.jpg"`
- And you specify `--image_folders "/path/to/images/"`
- The full image path will be `/path/to/images/folder1/image1.jpg`
Multiple data files and image folders can be specified using ":" as a separator:
```bash
--data_file_paths /path/to/data1.jsonl:/path/to/data2.jsonl \
--image_folders /path/to/images1/:/path/to/images2/
```
The script can be run like this:
```bash
torchrun --nproc_per_node="8" \
--nnodes="1" \
--node_rank="0" \
--master_addr="127.0.0.1" \
--master_port="12345" \
src/open_r1/grpo_jsonl.py \
--output_dir output/$RUN_NAME \
--model_name_or_path Qwen/Qwen2.5-VL-3B-Instruct \
--deepspeed local_scripts/zero3.json \
--dataset_name <your_dataset_name> \
--data_file_paths /path/to/your/data.jsonl \ # can be multiple, separated by ":"
--image_folders /path/to/your/image/folder/ \ # can be multiple, separated by ":"
...
```
## Evaluation

> 1. Download the provided [RefGTA images](https://huggingface.co/datasets/omlab/VLM-R1/resolve/main/refgta.zip).
```bash
cd ./src/eval
# Remember to change the model path, image root, and annotation path in the script
python test_rec_r1.py # for GRPO
python test_rec_baseline.py # for SFT
```
## Acknowledgements
We would like to express our sincere gratitude to [DeepSeek](https://github.com/deepseek-ai/DeepSeek-R1), [Open-R1](https://github.com/huggingface/open-r1), [QwenVL](https://github.com/QwenLM/Qwen2.5-VL), [Open-R1-Multimodal](https://github.com/EvolvingLMMs-Lab/open-r1-multimodal), [R1-V](https://github.com/Deep-Agent/R1-V), [RefCOCO](https://github.com/lichengunc/refer), and [RefGTA](https://github.com/mikittt/easy-to-understand-REG/tree/master/pyutils/refer2) for providing open-source resources that contributed to the development of this project.
## Citation
If you find this project useful, welcome to cite us.
```bib
@misc{shen2025vlmr1,
author = {Shen, Haozhan and Zhang, Zilun and Zhang, Qianqian and Xu, Ruochen and Zhao, Tiancheng},
title = {VLM-R1: A stable and generalizable R1-style Large Vision-Language Model},
howpublished = {\url{https://github.com/om-ai-lab/VLM-R1}},
note = {Accessed: 2025-02-15},
year = {2025}
}
``` | {
"source": "om-ai-lab/VLM-R1",
"title": "README.md",
"url": "https://github.com/om-ai-lab/VLM-R1/blob/main/README.md",
"date": "2025-02-06T16:12:30",
"stars": 3312,
"description": "Solve Visual Understanding with Reinforced VLMs",
"file_size": 7817
} |
# AI-Crash-Course
AI Crash Course to help busy builders catch up to the public frontier of AI research in 2 weeks
**Intro:** I’m [Henry Shi](https://www.linkedin.com/in/henrythe9th/) and I started Super.com in 2016 and grew it to $150MM+ in annual revenues and recently exited. As a traditional software founder, I needed to quickly catch up to the frontier of AI research to figure out where the next opportunities and gaps were. I compiled a list of resources that were essential for me and should get you caught up within 2 weeks.
For more context, checkout the [original twitter thread](https://x.com/henrythe9ths/status/1877056425454719336)
**Start Here:**
[Neural Network \-\> LLM Series](https://www.youtube.com/watch?v=aircAruvnKk&list=PLZHQObOWTQDNU6R1_67000Dx_ZCJB-3pi)
**Then get up to speed via Survey papers:**
- Follow the ideas in the survey paper that interest you and dig deeper
[LLM Survey](https://arxiv.org/pdf/2402.06196v2) \- 2024
[Agent Survey](https://arxiv.org/pdf/2308.11432) \- 2023
[Prompt Engineering Survey](https://arxiv.org/pdf/2406.06608) \- 2024
**AI Papers:** (prioritize ones with star \*)
**Foundational Modelling:**
[**Transformers**\*](https://arxiv.org/pdf/1706.03762) (foundation, self-attention) \- 2017
[Scaling Laws](https://arxiv.org/pdf/2001.08361)/[**GPT3**\*](https://arxiv.org/pdf/2005.14165) (conviction to scale up GPT2/3/4) \- 2020
[LoRA](https://arxiv.org/abs/2106.09685) (Fine tuning) \- 2021
[Training Compute-Optimal LLMs](https://arxiv.org/pdf/2203.15556) \- 2022
[**RLHF**\*](https://arxiv.org/pdf/2203.02155) (InstructGPT-\>ChatGPT) \- 2022
[DPO](https://arxiv.org/pdf/2305.18290) (No need for RL/Reward model) \- 2023
[LLM-as-Judge](https://arxiv.org/pdf/2306.05685) (On par with human evaluations) \- 2023
[MoE](https://arxiv.org/pdf/2401.04088) (MIxture of Experts) \- 2024
**Planning/Reasoning:**
[AlphaZero](https://arxiv.org/pdf/1712.01815)/[**MuZero**\*](https://arxiv.org/pdf/1911.08265) (RL without prior knowledge of game or rules) \- 2017/2019
[**CoT**\* (Chain of Thought)](https://arxiv.org/pdf/2201.11903)/[ToT (Tree of Thoughts)](https://arxiv.org/pdf/2305.10601)/[GoT (Graph of Thoughts)](https://arxiv.org/pdf/2308.09687)/[Meta CoT](https://arxiv.org/pdf/2501.04682) \- 2022/2023/2023/2025
[ReACT](https://arxiv.org/pdf/2210.03629) (Generate reasoning traces and task-specific actions in interleaved manner) \- 2022
[Let’s Verify Step by Step](https://arxiv.org/pdf/2305.20050) (Process \> Outcome) \- 2023
[**ARC-Prize**\*](https://arxiv.org/pdf/2412.04604) (Latest methods for solving ARC-AGI problems) \- 2024
[**DeepSeek R1**\*](https://arxiv.org/pdf/2501.12948v1) (Building OSS o1-level reasoning model with pure RL, no SFT, no RM) \- 2025
**Applications:**
[Toolformer](https://arxiv.org/pdf/2302.04761) (LLMs to use tools) \- 2023
[GPT4](https://arxiv.org/pdf/2303.08774) (Overview of GPT4, but fairly high level) \- 2023
[**Llama3**\*](https://arxiv.org/pdf/2407.21783) (In depth details of how Meta built Llama3 and the various configurations and hyperparameters) \- 2024
[Gemini1.5](https://arxiv.org/pdf/2403.05530) (Multimodal across 10MM context window) \- 2024
[Deepseekv3](https://github.com/deepseek-ai/DeepSeek-V3/blob/main/DeepSeek_V3.pdf) (Building a frontier OSS model at a fraction of the cost of everyone else) \- 2024
[SWE-Agent](https://arxiv.org/pdf/2405.15793)/[OpenHands](https://arxiv.org/pdf/2407.16741) (OpenSource software development agents) \- 2024
**Benchmarks:**
[BIG-Bench](https://arxiv.org/pdf/2206.04615) (First broad & diverse collaborative OSS benchmark) \- 2022
[SWE-Bench](https://arxiv.org/pdf/2310.06770) (Real world software development) \- 2023
[Chatbot Arena](https://arxiv.org/pdf/2403.04132) (Live human preference Elo ratings) \- 2024
<hr />
**Videos/Lectures:**
[3Blue1Brown on Foundational Math/Concepts](https://www.youtube.com/@3blue1brown)
[Build a Large Language Model (from Scratch) \#1 Bestseller](https://www.amazon.com/Build-Large-Language-Model-Scratch/dp/1633437167)
[Andrej Kaparthy: Zero to Hero Series](https://www.youtube.com/playlist?list=PLAqhIrjkxbuWI23v9cThsA9GvCAUhRvKZ)
[Yannic Kilcher Paper Explanations](https://www.youtube.com/@YannicKilcher)
[Noam Brown (o1 founder) on Planning in AI](https://www.youtube.com/watch?v=eaAonE58sLU)
[Stanford: Building LLMs](https://www.youtube.com/watch?v=9vM4p9NN0Ts)
[Foundations of LLMs](https://arxiv.org/pdf/2501.09223)
[Why You’re Not Too Old to Pivot Into AI](https://www.latent.space/p/not-old) (motivation)
**Helpful Websites:**
[History of Deep Learning](https://github.com/adam-maj/deep-learning?tab=readme-ov-file) \- summary timeline of deeplearning with major breakthroughs and key concepts
[Full Stack Deep Learning](https://fullstackdeeplearning.com/) \- courses for building AI products
[Prompting Guide](https://www.promptingguide.ai/) \- extensive list of prompting techniques and examples
[a16z AI Cannon](https://a16z.com/ai-canon/) \- similar list of resources, but longer (slightly dated)
[2025 AI Engineer Reading List](https://www.latent.space/p/2025-papers) \- longer reading list, broken out by focus area
[State of Generative Models 2024](https://nrehiew.github.io/blog/2024/) \- good simple summary of current state
**Others (non LLMs):**
[Vision Transformer](https://arxiv.org/pdf/2010.11929) (no need for CNNs) \- 2021
[Latent Diffusion](https://arxiv.org/pdf/2112.10752) (Text-to-Image) \- 2021
**Obvious/easy papers (to get your feet wet if you're new to papers):**
[CoT (Chain of Thought)](https://arxiv.org/pdf/2201.11903) \- 2022
[SELF-REFINE: Iterative Refinement with Self-Feedback](https://arxiv.org/pdf/2303.17651) \- 2023 | {
"source": "henrythe9th/AI-Crash-Course",
"title": "README.md",
"url": "https://github.com/henrythe9th/AI-Crash-Course/blob/main/README.md",
"date": "2025-01-08T05:43:56",
"stars": 3305,
"description": "AI Crash Course to help busy builders catch up to the public frontier of AI research in 2 weeks",
"file_size": 5754
} |
# Changelog
## [0.4.0] - 2024-11-16
### Added
- Add Google Singlespeaker (Journey) and Multispeaker TTS models
- Fixed limitations of Google Multispeaker TTS model: 5000 bytes input limite and 500 bytes per turn limit.
- Updated tests and docs accordingly
## [0.3.6] - 2024-11-13
### Added
- Add longform podcast generation support
- Users can now generate longer podcasts (20-30+ minutes) using the `--longform` flag in CLI or `longform=True` in Python API
- Implements "Content Chunking with Contextual Linking" technique for coherent long-form content
- Configurable via `max_num_chunks` and `min_chunk_size` parameters in conversation config
- `word_count` parameter removed from conversation config as it's no longer used
## [0.3.3] - 2024-11-08
### Breaking Changes
- Loading images from 'path' has been removed for security reasons. Please specify images by passing an 'url'.
### Added
- Add podcast generation from topic "Latest News in U.S. Politics"
- Integrate with 100+ LLM models (OpenAI, Anthropic, Google etc) for transcript generation
- Integrate with Google's Multispeaker TTS model for high-quality audio generation
- Deploy [REST API](https://github.com/souzatharsis/podcastfy/blob/main/usage/api.md) with FastAPI
- Support for raw text as input
- Add PRIVACY_POLICY.md
- Start TESTIMONIALS.md
- Add apps using Podcastfy to README.md
### Fixed
- #165 Fixed audio generation in Windows OS issue: Normalize path separators for cross-platform compatibility
## [0.2.3] - 2024-10-15
### Added
- Add local llm option by @souzatharsis
- Enable running podcastfy with no API KEYs thanks to solving #18 #58 #65 by @souzatharsis and @ChinoUkaegbu
- Add user-provided TSS config such as voices #10 #6 #27 by @souzatharsis
- Add open in collab and setting python version to 3.11 by @Devparihar5 #57
- Add edge tts support by @ChinoUkaegbu
- Update pypdf with pymupdf(10x faster then pypdf) #56 check by @Devparihar5
- Replace r.jina.ai with simple BeautifulSoap #18 by @souzatharsis
### Fixed
- Fixed CLI for user-provided config #69 @souzatharsis
## [0.2.2] - 2024-10-13
### Added
- Added API reference docs and published it to https://podcastfy.readthedocs.io/en/latest/
### Fixed
- ([#52](https://github.com/user/podcastfy/issues/37)) Fixed simple bug introduced in 0.2.1 that broke the ability to generate podcasts from text inputs!
- Fixed one example in the documentation that was not working.
## [0.2.1] - 2024-10-12
### Added
- ([#8](https://github.com/user/podcastfy/issues/8)) Podcastfy is now multi-modal! Users can now generate audio from images by simply providing the paths to the image files.
### Fixed
- ([#40](https://github.com/user/podcastfy/issues/37)) Updated default ElevenLabs voice from `BrittneyHart` to `Jessica`. The latter was a non-default voice I used from my account, which caused error for users who don't have it.
## [0.2.0] - 2024-10-10
### Added
- Parameterized podcast generation with Conversation Configuration ([#11](https://github.com/user/podcastfy/issues/11), [#3](https://github.com/user/podcastfy/issues/3), [#4](https://github.com/user/podcastfy/issues/4))
- Users can now customize podcast style, structure, and content
- See [Conversation Customization](usage/conversation_custom.md) for detailed options
- Updated demo in [podcastfy.ipynb](podcastfy.ipynb)
- LangChain integration for improved LLM interface and observability ([#29](https://github.com/user/podcastfy/issues/29))
- Changelog to track version updates ([#22](https://github.com/user/podcastfy/issues/22))
- Tests for Customized conversation scenarios
### Fixed
- CLI now correctly reads from user-provided local .env file ([#37](https://github.com/user/podcastfy/issues/37)) | {
"source": "souzatharsis/podcastfy",
"title": "CHANGELOG.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/CHANGELOG.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 3732
} |
# Contributor Covenant Code of Conduct
## Our Pledge
In the interest of fostering an open and welcoming environment, we as contributors and maintainers pledge to making participation in our project and our community a harassment-free experience for everyone, regardless of age, body size, disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation.
## Our Standards
Examples of behavior that contributes to creating a positive environment include:
* Using welcoming and inclusive language
* Being respectful of differing viewpoints and experiences
* Gracefully accepting constructive criticism
* Focusing on what is best for the community
* Showing empathy towards other community members
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery and unwelcome sexual attention or advances
* Trolling, insulting/derogatory comments, and personal or political attacks
* Public or private harassment
* Publishing others' private information, such as a physical or electronic address, without explicit permission
* Other conduct which could reasonably be considered inappropriate in a professional setting
## Our Responsibilities
Project maintainers are responsible for clarifying the standards of acceptable behavior and are expected to take appropriate and fair corrective action in response to any instances of unacceptable behavior.
Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct, or to ban temporarily or permanently any contributor for other behaviors that they deem inappropriate, threatening, offensive, or harmful.
## Scope
This Code | {
"source": "souzatharsis/podcastfy",
"title": "CODE_OF_CONDUCT.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/CODE_OF_CONDUCT.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 1901
} |
# Contributor Guidelines
Thank you for your interest in contributing to Podcastfy! We welcome contributions from the community to help improve and expand this project. Please follow these guidelines to ensure a smooth collaboration process.
## Getting Started
1. Fork the repository on GitHub.
2. Clone your fork locally: `git clone https://github.com/your-username/podcastfy.git`
3. Create a new branch for your feature or bug fix: `git checkout -b feature/your-feature-name`
## Code Style
- Follow PEP 8 style guidelines for Python code.
- Use tabs for indentation instead of spaces.
- Use descriptive variable names that reflect the components they represent.
- Include docstrings for all functions, classes, and modules.
## Development
- Poetry is the preferred but not mandatory dependency manager. Install it with `pip install poetry`.
- Contributors can opt to use `uv` instead and generate and push updated requirements.txt from it.
- Sphinx is used as the documentation generator. Install it with `pip install sphinx`.
- `make doc-gen` to generate the documentation.
## Submitting Changes
1. Commit your changes with clear, descriptive commit messages.
2. Push your changes to your fork on GitHub.
3. Submit a pull request to the main repository.
## Pre-Pull Request Checklist
1. Managing dependencies
- Add new dependencies with `poetry add <new-dependency>`
- Remove a dependency with `poetry remove <dependency-name>`.
- Then generate requirements.txt with `poetry export -f requirements.txt --output requirements.txt --without-hashes`
2. Testing
- Consider adding new tests at test/*.py, particularly if implementing user facing change.
- Test locally: `poetry run pytest`
- Tests (tests/*.py) are run automatically by GitHub Actions, double check that they pass.
3. Docs
- Update any documentation if required README.md, usage/*.md, *.ipynb etc.
- Regenerate documentation (/docs) if there are any changes in docstrings or modules' interface (`make doc-gen`)
## Reporting Issues
- Use the GitHub issue tracker to report bugs or suggest enhancements.
- Provide a clear and detailed description of the issue or suggestion.
- Include steps to reproduce the bug, if applicable.
## Code of Conduct
Please note that this project is released with a [Contributor Code of Conduct](CODE_OF_CONDUCT.md). By participating in this project, you agree to abide by its terms.
## Questions?
If you have any questions or need further clarification, please don't hesitate to ask in the GitHub issues section.
Thank you for contributing to Podcastfy! | {
"source": "souzatharsis/podcastfy",
"title": "GUIDELINES.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/GUIDELINES.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 2607
} |
# Privacy Policy
**Effective Date:** 11/03/2024
Podcastfy is an open-source project that does not collect, store, or transmit any personal user data. All processing occurs locally on your machine or through third-party services that you configure.
## Use of Third-Party Services
When you use Podcastfy with third-party services (such as APIs for text-to-speech or language models), any data transmitted to these services is subject to their respective privacy policies. You are responsible for reviewing and agreeing to the terms and policies of these third-party providers.
## Data Processing
- **Local Processing:** All content transformation and processing are performed locally unless explicitly configured to use external services.
- **No Data Collection:** Podcastfy does not collect or send any user data to the developers or any third parties without your consent.
## User Responsibility
Users are responsible for:
- Ensuring compliance with all applicable laws and regulations regarding data privacy.
- Protecting any personal or sensitive data processed through the application.
- Reviewing the privacy policies of any third-party services used in conjunction with Podcastfy.
## Contact Information
If you have any questions or concerns about this Privacy Policy, please open an issue on our [GitHub repository](https://github.com/souzatharsis/podcastfy/issues). | {
"source": "souzatharsis/podcastfy",
"title": "PRIVACY_POLICY.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/PRIVACY_POLICY.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 1383
} |
<div align="center">
<a name="readme-top"></a>
<a href="https://trendshift.io/repositories/12965" target="_blank"><img src="https://trendshift.io/api/badge/repositories/12965" alt="Podcastfy.ai | Trendshift" style="width: 250px; height: 55px;" width="250" height="55"/></a>
# Podcastfy.ai 🎙️🤖
An Open Source API alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI
https://github.com/user-attachments/assets/5d42c106-aabe-44c1-8498-e9c53545ba40
[Paper](https://github.com/souzatharsis/podcastfy/blob/main/paper/paper.pdf) |
[Python Package](https://github.com/souzatharsis/podcastfy/blob/59563ee105a0d1dbb46744e0ff084471670dd725/podcastfy.ipynb) |
[CLI](https://github.com/souzatharsis/podcastfy/blob/59563ee105a0d1dbb46744e0ff084471670dd725/usage/cli.md) |
[Web App](https://openpod.fly.dev/) |
[Feedback](https://github.com/souzatharsis/podcastfy/issues)
[](https://colab.research.google.com/github/souzatharsis/podcastfy/blob/main/podcastfy.ipynb)
[](https://pypi.org/project/podcastfy/)

[](https://github.com/souzatharsis/podcastfy/issues)
[](https://github.com/souzatharsis/podcastfy/actions/workflows/python-app.yml)
[](https://github.com/souzatharsis/podcastfy/actions/workflows/docker-publish.yml)
[](https://podcastfy.readthedocs.io/en/latest/?badge=latest)
[](https://opensource.org/licenses/Apache-2.0)

</div>
Podcastfy is an open-source Python package that transforms multi-modal content (text, images) into engaging, multi-lingual audio conversations using GenAI. Input content includes websites, PDFs, images, YouTube videos, as well as user provided topics.
Unlike closed-source UI-based tools focused primarily on research synthesis (e.g. NotebookLM ❤️), Podcastfy focuses on open source, programmatic and bespoke generation of engaging, conversational content from a multitude of multi-modal sources, enabling customization and scale.
## Testimonials 💬
> "Love that you casually built an open source version of the most popular product Google built in the last decade"
> "Loving this initiative and the best I have seen so far especially for a 'non-techie' user."
> "Your library was very straightforward to work with. You did Amazing work brother 🙏"
> "I think it's awesome that you were inspired/recognize how hard it is to beat NotebookLM's quality, but you did an *incredible* job with this! It sounds incredible, and it's open-source! Thank you for being amazing!"
[](https://api.star-history.com/svg?repos=souzatharsis/podcastfy&type=Date&theme=dark)
## Audio Examples 🔊
This sample collection was generated using this [Python Notebook](usage/examples.ipynb).
### Images
Sample 1: Senecio, 1922 (Paul Klee) and Connection of Civilizations (2017) by Gheorghe Virtosu
***
<img src="data/images/Senecio.jpeg" alt="Senecio, 1922 (Paul Klee)" width="20%" height="auto"> <img src="data/images/connection.jpg" alt="Connection of Civilizations (2017) by Gheorghe Virtosu " width="21.5%" height="auto">
<video src="https://github.com/user-attachments/assets/a4134a0d-138c-4ab4-bc70-0f53b3507e6b"></video>
***
Sample 2: The Great Wave off Kanagawa, 1831 (Hokusai) and Takiyasha the Witch and the Skeleton Spectre, c. 1844 (Kuniyoshi)
***
<img src="data/images/japan_1.jpg" alt="The Great Wave off Kanagawa, 1831 (Hokusai)" width="20%" height="auto"> <img src="data/images/japan2.jpg" alt="Takiyasha the Witch and the Skeleton Spectre, c. 1844 (Kuniyoshi)" width="21.5%" height="auto">
<video src="https://github.com/user-attachments/assets/f6aaaeeb-39d2-4dde-afaf-e2cd212e9fed"></video>
***
Sample 3: Pop culture icon Taylor Swift and Mona Lisa, 1503 (Leonardo da Vinci)
***
<img src="data/images/taylor.png" alt="Taylor Swift" width="28%" height="auto"> <img src="data/images/monalisa.jpeg" alt="Mona Lisa" width="10.5%" height="auto">
<video src="https://github.com/user-attachments/assets/3b6f7075-159b-4540-946f-3f3907dffbca"></video>
### Text
| Audio | Description | Source |
|-------|--|--------|
| <video src="https://github.com/user-attachments/assets/ef41a207-a204-4b60-a11e-06d66a0fbf06"></video> | Personal Website | [Website](https://www.souzatharsis.com) |
| [Audio](https://soundcloud.com/high-lander123/amodei?in=high-lander123/sets/podcastfy-sample-audio-longform&si=b8dfaf4e3ddc4651835e277500384156) (`longform=True`) | Lex Fridman Podcast: 5h interview with Dario Amodei Anthropic's CEO | [Youtube](https://www.youtube.com/watch?v=ugvHCXCOmm4) |
| [Audio](https://soundcloud.com/high-lander123/benjamin?in=high-lander123/sets/podcastfy-sample-audio-longform&si=dca7e2eec1c94252be18b8794499959a&utm_source=clipboard&utm_medium=text&utm_campaign=social_sharing) (`longform=True`)| Benjamin Franklin's Autobiography | [Book](https://www.gutenberg.org/cache/epub/148/pg148.txt) |
### Multi-Lingual Text
| Language | Content Type | Description | Audio | Source |
|----------|--------------|-------------|-------|--------|
| French | Website | Agroclimate research information | [Audio](https://audio.com/thatupiso/audio/podcast-fr-agro) | [Website](https://agroclim.inrae.fr/) |
| Portuguese-BR | News Article | Election polls in São Paulo | [Audio](https://audio.com/thatupiso/audio/podcast-thatupiso-br) | [Website](https://noticias.uol.com.br/eleicoes/2024/10/03/nova-pesquisa-datafolha-quem-subiu-e-quem-caiu-na-disputa-de-sp-03-10.htm) |
## Quickstart 💻
### Prerequisites
- Python 3.11 or higher
- `$ pip install ffmpeg` (for audio processing)
### Setup
1. Install from PyPI
`$ pip install podcastfy`
2. Set up your [API keys](usage/config.md)
### Python
```python
from podcastfy.client import generate_podcast
audio_file = generate_podcast(urls=["<url1>", "<url2>"])
```
### CLI
```
python -m podcastfy.client --url <url1> --url <url2>
```
## Usage 💻
- [Python Package Quickstart](podcastfy.ipynb)
- [How to](usage/how-to.md)
- [Python Package Reference Manual](https://podcastfy.readthedocs.io/en/latest/podcastfy.html)
- [CLI](usage/cli.md)
## Customization 🔧
Podcastfy offers a range of customization options to tailor your AI-generated podcasts:
- Customize podcast [conversation](usage/conversation_custom.md) (e.g. format, style, voices)
- Choose to run [Local LLMs](usage/local_llm.md) (156+ HuggingFace models)
- Set other [Configuration Settings](usage/config.md)
## Features ✨
- Generate conversational content from multiple sources and formats (images, text, websites, YouTube, and PDFs).
- Generate shorts (2-5 minutes) or longform (30+ minutes) podcasts.
- Customize transcript and audio generation (e.g., style, language, structure).
- Generate transcripts using 100+ LLM models (OpenAI, Anthropic, Google etc).
- Leverage local LLMs for transcript generation for increased privacy and control.
- Integrate with advanced text-to-speech models (OpenAI, Google, ElevenLabs, and Microsoft Edge).
- Provide multi-language support for global content creation.
- Integrate seamlessly with CLI and Python packages for automated workflows.
## Built with Podcastfy 🚀
- [OpenNotebook](https://www.open-notebook.ai/)
- [SurfSense](https://www.surfsense.net/)
- [OpenPod](https://openpod.fly.dev/)
- [Podcast-llm](https://github.com/evandempsey/podcast-llm)
- [Podcastfy-HuggingFace App](https://huggingface.co/spaces/thatupiso/Podcastfy.ai_demo)
## Updates 🚀🚀
### v0.4.0+ release
- Released new Multi-Speaker TTS model (is it the one NotebookLM uses?!?)
- Generate short or longform podcasts
- Generate podcasts from input topic using grounded real-time web search
- Integrate with 100+ LLM models (OpenAI, Anthropic, Google etc) for transcript generation
See [CHANGELOG](CHANGELOG.md) for more details.
## License
This software is licensed under [Apache 2.0](LICENSE). See [instructions](usage/license-guide.md) if you would like to use podcastfy in your software.
## Contributing 🤝
We welcome contributions! See [Guidelines](GUIDELINES.md) for more details.
## Example Use Cases 🎧🎶
- **Content Creators** can use `Podcastfy` to convert blog posts, articles, or multimedia content into podcast-style audio, enabling them to reach broader audiences. By transforming content into an audio format, creators can cater to users who prefer listening over reading.
- **Educators** can transform lecture notes, presentations, and visual materials into audio conversations, making educational content more accessible to students with different learning preferences. This is particularly beneficial for students with visual impairments or those who have difficulty processing written information.
- **Researchers** can convert research papers, visual data, and technical content into conversational audio. This makes it easier for a wider audience, including those with disabilities, to consume and understand complex scientific information. Researchers can also create audio summaries of their work to enhance accessibility.
- **Accessibility Advocates** can use `Podcastfy` to promote digital accessibility by providing a tool that converts multimodal content into auditory formats. This helps individuals with visual impairments, dyslexia, or other disabilities that make it challenging to consume written or visual content.
## Contributors
<a href="https://github.com/souzatharsis/podcastfy/graphs/contributors">
<img alt="contributors" src="https://contrib.rocks/image?repo=souzatharsis/podcastfy"/>
</a>
<p align="right" style="font-size: 14px; color: #555; margin-top: 20px;">
<a href="#readme-top" style="text-decoration: none; color: #007bff; font-weight: bold;">
↑ Back to Top ↑
</a>
</p> | {
"source": "souzatharsis/podcastfy",
"title": "README.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/README.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 10400
} |
- "Love that you casually built an open source version of the most popular product Google built in the last decade"
- "Your library was very straightforward to work with. You did Amazing work brother 🙏"
- "I think it's awesome that you were inspired/recognize how hard it is to beat NotebookLM's quality, but you did an *incredible* job with this! It sounds incredible, and it's open-source! Thank you for being amazing!"
- "Discovered your work last night. Stunning accomplishment. Well done."
- "Loving this initiative and the best I have seen so far especially for a "non-techie" user." | {
"source": "souzatharsis/podcastfy",
"title": "TESTIMONIALS.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/TESTIMONIALS.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 589
} |
---
title: 'When Content Speaks Volumes: Podcastfy — An Open Source Python Package Bridging Multimodal Data and Conversational Audio with GenAI'
tags:
- Python
- generative AI
- GenAI
- text-to-speech
- large language models
- content transformation
- accessibility
authors:
- name: Tharsis T. P. Souza
orcid: 0000-0003-3260-9526
affiliation: "1, 2"
affiliations:
- name: Columbia University in the City of New York
index: 1
- name: Instituto Federal de Educacao, Ciencia e Tecnologia do Sul de Minas (IFSULDEMINAS)
index: 2
date: 11/03/2024
bibliography: paper.bib
---
# Abstract
`Podcastfy` is an open-source Python framework that programmatically transforms multisourced, multimodal content into multilingual, natural-sounding audio conversations using generative AI. By converting various types of digital content - including images, websites, YouTube videos, and PDFs - into conversational audio formats, `Podcastfy` enhances accessibility, engagement, and usability for a wide range of users. As an open-source project, `Podcastfy` benefits from continuous community-driven improvements, enhancing its adaptability to evolving user requirements and accessibility standards.
# Statement of Need
The rapid expansion of digital content across various formats has intensified the need for tools capable of converting diverse information into accessible and digestible forms [@johnson2023adaptive; @chen2023digital; @mccune2023accessibility]. Existing solutions often fall short due to their proprietary nature, limited multimodal support, or inadequate accessibility features [@marcus2019design; @peterson2023web; @gupta2023advances].
`Podcastfy` addresses this gap with an open-source solution that supports multimodal input processing and generates natural-sounding, summarized conversational content. Leveraging advances in large language models (LLMs) and text-to-speech (TTS) synthesis, `Podcastfy` aims to benefit a diverse group of users — including content creators, educators, researchers, and accessibility advocates — by providing a customizable solution that transforms digital content into multilingual textual and auditory formats, enhancing accessibility and engagement.
# Features
- Generate conversational content from multiple sources and formats (images, websites, YouTube, and PDFs).
- Customize transcript and audio generation (e.g., style, language, structure, length).
- Create podcasts from pre-existing or edited transcripts.
- Leverage cloud-based and local LLMs for transcript generation (increased privacy and control).
- Integrate with advanced text-to-speech models (OpenAI, ElevenLabs, and Microsoft Edge).
- Provide multi-language support for global content creation and enhanced accessibility.
- Integrate seamlessly with CLI and Python packages for automated workflows.
See [audio samples](https://github.com/souzatharsis/podcastfy?tab=readme-ov-file#audio-examples-).
# Use Cases
`Podcastfy` is designed to serve a wide range of applications, including:
- **Content Creators** can use `Podcastfy` to convert blog posts, articles, or multimedia content into podcast-style audio, enabling them to reach broader audiences. By transforming content into an audio format, creators can cater to users who prefer listening over reading.
- **Educators** can transform lecture notes, presentations, and visual materials into audio conversations, making educational content more accessible to students with different learning preferences. This is particularly beneficial for students with visual impairments or those who have difficulty processing written information.
- **Researchers** can convert research papers, visual data, and technical content into conversational audio. This makes it easier for a wider audience, including those with disabilities, to consume and understand complex scientific information. Researchers can also create audio summaries of their work to enhance accessibility.
- **Accessibility Advocates** can use `Podcastfy` to promote digital accessibility by providing a tool that converts multimodal content into auditory formats. This helps individuals with visual impairments, dyslexia, or other disabilities that make it challenging to consume written or visual content.
# Implementation and Architecture
`Podcastfy` implements a modular architecture designed for flexibility and extensibility through five main components, as shown in Figure 1.
1. **Client Interface**
- Provides both CLI (Command-Line Interface) and API interfaces.
- Coordinates the workflow between processing layers.
- Implements a unified interface for podcast generation through the `generate_podcast()` method.
2. **Configuration Management**
- Offers extensive customization options through a dedicated module.
- Manages system settings and user preferences, such as podcast name, language, style, and structure.
- Controls the behavior of all processing layers.
3. **Content Extraction Layer**
- Extracts content from various sources, including websites, PDFs, and YouTube videos.
- The `ContentExtractor` class coordinates three specialized extractors:
- `PDFExtractor`: Handles PDF document processing.
- `WebsiteExtractor`: Manages website content extraction.
- `YouTubeTranscriber`: Processes YouTube video content.
- Serves as the entry point for all input types, providing standardized text output to the transcript generator.
4. **LLM-based Transcript Generation Layer**
- Uses large language models to generate natural-sounding conversations from extracted content.
- The `ContentGenerator` class manages conversation generation using different LLM backends:
- Integrates with LangChain to implement prompt management and common LLM access through the `BaseChatModel` interface.
- Supports both local (`LlamaFile`) and cloud-based models.
- Uses `ChatGoogleGenerativeAI` for cloud-based LLM services.
- Allows customization of conversation style, roles, and dialogue structure.
- Outputs structured conversations in text format.
5. **Text-to-Speech (TTS) Layer**
- Converts input transcripts into audio using various TTS models.
- The `TextToSpeech` class implements a factory pattern:
- The `TTSFactory` creates appropriate providers based on configuration.
- Supports multiple backends (OpenAI, ElevenLabs, and Microsoft Edge) through the `TTSProvider` interface.
- Produces the final podcast audio output.
{width=80%}
The modular architecture enables independent development and maintenance of each component. This pipeline design ensures a clean separation of concerns while maintaining seamless data transformation between stages. This modular approach also facilitates easy updates and extensions to individual components without affecting the rest of the system.
The framework is offered as a Python package, with a command-line interface as well as a REST API, making it accessible to users with different technical backgrounds and requirements.
# Quick Start
## Prerequisites
- Python 3.11 or higher
- `$ pip install ffmpeg` (for audio processing)
## Setup
1. Install from PyPI
`$ pip install podcastfy`
2. Set up [API keys](usage/config.md)
## Python
```python
from podcastfy.client import generate_podcast
audio_file = generate_podcast(urls=["<url1>", "<url2>"])
```
## CLI
```
python -m podcastfy.client --url <url1> --url <url2>
```
# Customization Examples
`Podcastfy` offers various customization options that make it versatile for different types of content transformation. To accomplish that, we leverage LangChain's [@langchain2024] prompt management capabilities to dynamically construct prompts for the LLM, adjusting conversation characteristics such as style, roles, and dialogue structure. Below are some examples that demonstrate its capabilities.
## Academic Debate
The following Python code demonstrates how to configure `Podcastfy` for an academic debate:
```python
from podcastfy import generate_podcast
debate_config = {
"conversation_style": ["formal", "debate"],
"roles_person1": "main presenter",
"roles_person2": "opposing viewpoint",
"dialogue_structure": ["Introduction", "Argument Presentation", "Counterarguments", "Conclusion"]
}
generate_podcast(
urls=["PATH/TO/academic-article.pdf"],
conversation_config=debate_config
)
```
In this example, the roles are set to "main presenter" and "opposing viewpoint" to simulate an academic debate between two speakers on a chosen topic. This approach is especially useful for educational content that aims to present multiple perspectives on a topic. The output is structured with clear sections such as introduction, argument presentation, counterarguments, and conclusion, allowing listeners to follow complex ideas easily.
## Technical Tutorial
In this example, the configuration is optimized for creating technical tutorial content.
```python
tutorial_config = {
"word_count": 2500,
"conversation_style": ["instructional", "step-by-step"],
"roles_person1": "expert developer",
"roles_person2": "learning developer",
"dialogue_structure": [
"Concept Introduction",
"Technical Background",
"Implementation Steps",
"Common Pitfalls",
"Best Practices"
],
"engagement_techniques": [
"code examples",
"real-world applications",
"troubleshooting tips"
],
"creativity": 0.4
}
generate_podcast(
urls=["https://tech-blog.com/tutorial"],
conversation_config=tutorial_config
)
```
The roles are set to "expert developer" and "learning developer" to create a natural teaching dynamic. The dialogue structure follows a logical progression from concept introduction through implementation and best practices. The engagement_techniques parameter ensures the content remains practical and applicable by incorporating code examples, real-world applications, and troubleshooting guidance. A moderate creativity setting (0.4) maintains technical accuracy while allowing for engaging explanations and examples.
## Storytelling Adventure
The following Python code demonstrates how to generate a storytelling podcast:
```python
from podcastfy import generate_podcast
story_config = {
"conversation_style": ["adventurous", "narrative"],
"creativity": 1.0,
"roles_person1": "narrator",
"roles_person2": "character",
"dialogue_structure": ["Introduction", "Adventure Begins", "Challenges", "Resolution"]
}
generate_podcast(
urls=["SAMPLE/WWW.URL.COM"],
conversation_config=story_config
)
```
In this example, `Podcastfy` creates an engaging story by assigning roles like "narrator" and "character" and adjusting the creativity parameter for richer descriptions. Using this configuration, `Podcastfy` can generate engaging narrative content. By adjusting the creativity parameter, `Podcastfy` can create a story involving multiple characters, unexpected plot twists, and rich descriptions.
## Additional Examples
### Daily News Briefing
```python
news_config = {
"word_count": 1500,
"conversation_style": ["concise", "informative"],
"podcast_name": "Morning Briefing",
"dialogue_structure": [
"Headlines",
"Key Stories",
"Market Update",
"Weather"
],
"roles_person1": "news anchor",
"roles_person2": "field reporter",
"creativity": 0.3
}
generate_podcast(
urls=[
"https://news-source.com/headlines",
"https://market-updates.com/today"
],
conversation_config=news_config
)
```
### Language Learning Content
```python
language_config = {
"output_language": "Spanish",
"word_count": 1000,
"conversation_style": ["educational", "casual"],
"engagement_techniques": [
"vocabulary explanations",
"cultural context",
"pronunciation tips"
],
"roles_person1": "language teacher",
"roles_person2": "curious student",
"creativity": 0.6
}
generate_podcast(
urls=["https://spanish-content.com/article"],
conversation_config=language_config
)
```
## Working with Podcastfy Modules
`Podcastfy`'s components are designed to work independently, allowing flexibility in updating or extending each module. The data flows from the `ContentExtractor` module to `ContentGenerator` and finally to the `TexttoSpeech` converter, ensuring a seamless transformation of multimodal content into audio. In this section, we provide some examples of how to use each module.
## Content Extraction
Podcastfy's `content_extractor.py` module allows users to extract content from a given URL, which can be processed further to generate a podcast. Below is an example of how to use the content extraction component:
```python
from podcastfy.content_extractor import ContentExtractor
# Initialize the content extractor
extractor = ContentExtractor()
# Extract content from a URL
url = "https://example.com/article"
extracted_content = extractor.extract_content(url)
print("Extracted Content:")
print(extracted_content)
```
This example demonstrates how to extract text from a given URL. The extracted content is then passed to the next stages of processing.
## Content Generation
The `content_generator.py` module is responsible for generating conversational content based on textual input. Below is an example of how to use the content generation component:
```python
from podcastfy.content_generator import ContentGenerator
# Initialize the content generator
generator = ContentGenerator(api_key="<GEMINI_API_KEY>")
# Generate conversational content
input_text = "This is a sample input text about artificial intelligence."
generated_conversation = generator.generate_conversation(input_text)
print("Generated Conversation:")
print(generated_conversation)
```
Users can opt to run a cloud-based LLM (Gemini) or run a local (potentially Open Source) LLM model ([see local llm configuration](https://github.com/souzatharsis/podcastfy/blob/main/usage/local_llm.md)).
## Text-to-Speech Conversion
The `text_to_speech.py` module allows the generated transcript to be converted into audio. Below is an example of how to use the text-to-speech component:
```python
from podcastfy.text_to_speech import TextToSpeech
# Initialize the text-to-speech converter
tts = TextToSpeech(model='elevenlabs', api_key="<ELEVENLABS_API_KEY>")
# Convert the generated conversation to speech
input_text = "<Person1>This is a sample conversation generated by Podcastfy.</Person1><Person2>That's great!</Person2>"
output_audio_file = "output_podcast.mp3"
tts.convert_to_speech(input_text, output_audio_file)
print(f"Audio saved to {output_audio_file}")
```
This example demonstrates how to use the `TextToSpeech` class to convert generated text into an audio file. Users can specify different models for TTS, such as `elevenlabs`, `openai`, or `edge` (free to use).
# Limitations
`Podcastfy` has several limitations, including:
- **Content Accuracy and Quality**
- The accuracy of generated conversations depends heavily on the capabilities of the underlying LLMs.
- Complex technical or domain-specific content may not always be accurately interpreted or summarized.
- The framework cannot guarantee the factual correctness of generated content, requiring human verification for critical applications.
- **Language Support Constraints**
- While multilingual support is available, performance may vary significantly across different languages.
- Less common languages may have limited TTS voice options and lower-quality speech synthesis.
- Nuanced cultural contexts and idioms may not translate effectively across languages.
- **Technical Dependencies**
- Reliance on third-party APIs (OpenAI, ElevenLabs, Google) introduces potential service availability risks.
- Local LLM options, while providing independence, require significant computational resources.
- Network connectivity is required for cloud-based services, limiting offline usage.
- **Content Extraction Challenges**
- Complex webpage layouts or dynamic content may not be accurately extracted.
- PDF extraction quality depends on document formatting and structure.
- YouTube video processing depends on the availability of transcripts.
- **Accessibility Considerations**
- Generated audio may not fully meet all accessibility standards.
- Limited support for real-time content processing.
- May require additional processing for users with specific accessibility needs.
These limitations highlight areas for future development and improvement of the framework. Users should carefully consider these constraints when implementing `Podcastfy` for their specific use cases and requirements.
# Limitations
`Podcastfy` faces several key limitations in its current implementation. The accuracy and quality of generated content heavily depends on the underlying LLMs, with complex technical content potentially being misinterpreted. Additionally, while multilingual support is available, performance varies across languages, with less common languages having limited TTS voice options. The framework also relies on third-party APIs which introduces service availability risks, and local LLM options require significant computational resources.
These limitations highlight areas for future development and improvement of the framework. Users should carefully consider these constraints when implementing `Podcastfy` for their specific use cases and requirements.
# Conclusion
`Podcastfy` contributes to multimodal content accessibility by enabling the programmatic transformation of digital content into conversational audio. The framework addresses accessibility needs through automated content summarization and natural-sounding speech synthesis. Its modular design and configurable options allow for flexible content processing and audio generation workflows that can be adapted for different use cases and requirements.
We invite contributions from the community to further enhance the capabilities of `Podcastfy`. Whether it's by adding support for new input modalities, improving the quality of conversation generation, or optimizing the TTS synthesis, we welcome collaboration to make `Podcastfy` more powerful and versatile.
# Acknowledgements
We acknowledge the open-source community and the developers of the various libraries and tools that make `Podcastfy` possible. Special thanks to the developers of LangChain, Llamafile and HuggingFace. We are particularly grateful to all our [contributors](https://github.com/souzatharsis/podcastfy/graphs/contributors) who have helped improve this project.
# References | {
"source": "souzatharsis/podcastfy",
"title": "paper/paper.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/paper/paper.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 18817
} |
* NotebookLM by Google
* Storm by Stanford University
* Open Notebook by @lf
* Open NotebookLM
* podlm.ai
* notebooklm.ai | {
"source": "souzatharsis/podcastfy",
"title": "paper/related-work.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/paper/related-work.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 121
} |
# Podcastfy REST API Documentation
## Overview
The Podcastfy API allows you to programmatically generate AI podcasts from various input sources. This document outlines the API endpoints and their usage.
## Using cURL with Podcastfy API
### Prerequisites
1. Confirm cURL installation:
```bash
curl --version
```
### API Request Flow
Making a prediction requires two sequential requests:
1. POST request to initiate processing - returns an `EVENT_ID`
2. GET request to fetch results - uses the `EVENT_ID` to fetch results
Between step 1 and 2, there is a delay of 1-3 minutes. We are working on reducing this delay and implementing a way to notify the user when the podcast is ready. Thanks for your patience!
### Basic Request Structure
```bash
# Step 1: POST request to initiate processing
# Make sure to include http:// or https:// in the URL
curl -X POST https://thatupiso-podcastfy-ai-demo.hf.space/gradio_api/call/process_inputs \
-H "Content-Type: application/json" \
-d '{
"data": [
"text_input",
"https://yourwebsite.com",
[], # pdf_files
[], # image_files
"gemini_key",
"openai_key",
"elevenlabs_key",
2000, # word_count
"engaging,fast-paced", # conversation_style
"main summarizer", # roles_person1
"questioner", # roles_person2
"Introduction,Content,Conclusion", # dialogue_structure
"PODCASTFY", # podcast_name
"YOUR PODCAST", # podcast_tagline
"openai", # tts_model
0.7, # creativity_level
"" # user_instructions
]
}'
# Step 2: GET request to fetch results
curl -N https://thatupiso-podcastfy-ai-demo.hf.space/gradio_api/call/process_inputs/$EVENT_ID
# Example output result
event: complete
data: [{"path": "/tmp/gradio/bcb143f492b1c9a6dbde512557541e62f090bca083356be0f82c2e12b59af100/podcast_81106b4ca62542f1b209889832a421df.mp3", "url": "https://thatupiso-podcastfy-ai-demo.hf.space/gradio_a/gradio_api/file=/tmp/gradio/bcb143f492b1c9a6dbde512557541e62f090bca083356be0f82c2e12b59af100/podcast_81106b4ca62542f1b209889832a421df.mp3", "size": null, "orig_name": "podcast_81106b4ca62542f1b209889832a421df.mp3", "mime_type": null, "is_stream": false, "meta": {"_type": "gradio.FileData"}}]
```
You can download the file by extending the URL prefix "https://thatupiso-podcastfy-ai-demo.hf.space/gradio_a/gradio_api/file=" with the path to the file in variable `path`. (Note: The variable "url" above has a bug introduced by Gradio, so please ignore it.)
### Parameter Details
| Index | Parameter | Type | Description |
|-------|-----------|------|-------------|
| 0 | text_input | string | Direct text input for podcast generation |
| 1 | urls_input | string | URLs to process (include http:// or https://) |
| 2 | pdf_files | array | List of PDF files to process |
| 3 | image_files | array | List of image files to process |
| 4 | gemini_key | string | Google Gemini API key |
| 5 | openai_key | string | OpenAI API key |
| 6 | elevenlabs_key | string | ElevenLabs API key |
| 7 | word_count | number | Target word count for podcast |
| 8 | conversation_style | string | Conversation style descriptors (e.g. "engaging,fast-paced") |
| 9 | roles_person1 | string | Role of first speaker |
| 10 | roles_person2 | string | Role of second speaker |
| 11 | dialogue_structure | string | Structure of dialogue (e.g. "Introduction,Content,Conclusion") |
| 12 | podcast_name | string | Name of the podcast |
| 13 | podcast_tagline | string | Podcast tagline |
| 14 | tts_model | string | Text-to-speech model ("gemini", "openai", "elevenlabs", or "edge") |
| 15 | creativity_level | number | Level of creativity (0-1) |
| 16 | user_instructions | string | Custom instructions for generation |
## Using Python
### Installation
```bash
pip install gradio_client
```
### Quick Start
```python
from gradio_client import Client, handle_file
client = Client("thatupiso/Podcastfy.ai_demo")
```
### API Endpoints
#### Generate Podcast (`/process_inputs`)
Generates a podcast from provided text, URLs, PDFs, or images.
##### Parameters
| Parameter | Type | Required | Default | Description |
|-----------|------|----------|---------|-------------|
| text_input | str | Yes | - | Raw text input for podcast generation |
| urls_input | str | Yes | - | Comma-separated URLs to process |
| pdf_files | List[filepath] | Yes | None | List of PDF files to process |
| image_files | List[filepath] | Yes | None | List of image files to process |
| gemini_key | str | No | "" | Google Gemini API key |
| openai_key | str | No | "" | OpenAI API key |
| elevenlabs_key | str | No | "" | ElevenLabs API key |
| word_count | float | No | 2000 | Target word count for podcast |
| conversation_style | str | No | "engaging,fast-paced,enthusiastic" | Conversation style descriptors |
| roles_person1 | str | No | "main summarizer" | Role of first speaker |
| roles_person2 | str | No | "questioner/clarifier" | Role of second speaker |
| dialogue_structure | str | No | "Introduction,Main Content Summary,Conclusion" | Structure of dialogue |
| podcast_name | str | No | "PODCASTFY" | Name of the podcast |
| podcast_tagline | str | No | "YOUR PERSONAL GenAI PODCAST" | Podcast tagline |
| tts_model | Literal['openai', 'elevenlabs', 'edge'] | No | "openai" | Text-to-speech model |
| creativity_level | float | No | 0.7 | Level of creativity (0-1) |
| user_instructions | str | No | "" | Custom instructions for generation |
##### Returns
| Type | Description |
|------|-------------|
| filepath | Path to generated audio file |
##### Example Usage
```python
from gradio_client import Client, handle_file
client = Client("thatupiso/Podcastfy.ai_demo")
# Generate podcast from URL
result = client.predict(
text_input="",
urls_input="https://example.com/article",
pdf_files=[],
image_files=[],
gemini_key="your-gemini-key",
openai_key="your-openai-key",
word_count=1500,
conversation_style="casual,informative",
podcast_name="Tech Talk",
tts_model="openai",
creativity_level=0.8
)
print(f"Generated podcast: {result}")
```
### Error Handling
The API will return appropriate error messages for:
- Invalid API keys
- Malformed input
- Failed file processing
- TTS generation errors
### Rate Limits
Please be aware of the rate limits for the underlying services:
- Gemini API
- OpenAI API
- ElevenLabs API
## Notes
- At least one input source (text, URL, PDF, or image) must be provided
- API keys are required for corresponding services
- The generated audio file format is MP3 | {
"source": "souzatharsis/podcastfy",
"title": "usage/api.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/usage/api.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 6561
} |
## CLI
Podcastfy can be used as a command-line interface (CLI) tool. See below some usage examples.
Please make sure you follow configuration instructions first - [See Setup](README.md#setup).
1. Generate a podcast from URLs (using OpenAI TTS by default):
```
python -m podcastfy.client --url https://example.com/article1 --url https://example.com/article2
```
2. Generate a podcast from URLs using ElevenLabs TTS:
```
python -m podcastfy.client --url https://example.com/article1 --url https://example.com/article2 --tts-model elevenlabs
```
3. Generate a podcast from a file containing URLs:
```
python -m podcastfy.client --file path/to/urls.txt
```
4. Generate a podcast from an existing transcript file:
```
python -m podcastfy.client --transcript path/to/transcript.txt
```
5. Generate only a transcript (without audio) from URLs:
```
python -m podcastfy.client --url https://example.com/article1 --transcript-only
```
6. Generate a podcast using a combination of URLs and a file:
```
python -m podcastfy.client --url https://example.com/article1 --file path/to/urls.txt
```
7. Generate a podcast from image files:
```
python -m podcastfy.client --image path/to/image1.jpg --image path/to/image2.png
```
8. Generate a podcast with a custom conversation configuration:
```
python -m podcastfy.client --url https://example.com/article1 --conversation-config path/to/custom_config.yaml
```
9. Generate a podcast from URLs and images:
```
python -m podcastfy.client --url https://example.com/article1 --image path/to/image1.jpg
```
10. Generate a transcript using a local LLM:
```
python -m podcastfy.client --url https://example.com/article1 --transcript-only --local
```
11. Generate a podcast from raw text input:
```
python -m podcastfy.client --text "Your raw text content here that you want to convert into a podcast"
```
12. Generate a longform podcast from URLs:
```
python -m podcastfy.client --url https://example.com/article1 --url https://example.com/article2 --longform
```
For more information on available options, use:
```
python -m podcastfy.client --help
``` | {
"source": "souzatharsis/podcastfy",
"title": "usage/cli.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/usage/cli.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 2221
} |
# Podcastfy Configuration
## API keys
The project uses a combination of a `.env` file for managing API keys and sensitive information, and a `config.yaml` file for non-sensitive configuration settings. Follow these steps to set up your configuration:
1. Create a `.env` file in the root directory of the project.
2. Add your API keys and other sensitive information to the `.env` file. For example:
```
GEMINI_API_KEY=your_gemini_api_key_here
ELEVENLABS_API_KEY=your_elevenlabs_api_key_here
OPENAI_API_KEY=your_openai_api_key_here
```
## API Key Requirements
The API Keys required depend on the model you are using for transcript generation and audio generation.
- Transcript generation (LLMs):
- By default, Podcastfy uses Google's `gemini-1.5-pro-latest` model. Hence, you need to set `GEMINI_API_KEY`.
- See how to configure other LLMs [here](how-to.md#custom-llm-support).
- Audio generation (TTS):
- By default, Podcastfy uses OpenAI TTS. Hence, you need to set `OPENAI_API_KEY`.
- Additional supported models are ElevenLabs ('elevenlabs'), Microsoft Edge ('edge') and Google TTS ('gemini'). All but Edge require an API key.
> [!Note]
> Never share your `.env` file or commit it to version control. It contains sensitive information that should be kept private. The `config.yaml` file can be shared and version-controlled as it doesn't contain sensitive data.
## Example Configurations
Here's a table showing example configurations:
| Configuration | Base LLM | TTS Model | API Keys Required |
| -------------------- | --------- | ---------------------- | --------------------------------- |
| Default | Gemini | OpenAI | GEMINI_API_KEY and OPENAI_API_KEY |
| No API Keys Required | Local LLM | Edge | None |
| Recommended | Gemini | 'geminimulti' (Google) | GEMINI_API_KEY |
In our experience, Google's Multispeaker TTS model ('geminimulti') is the best model in terms of quality followed by ElevenLabs which offers great customization (voice options and multilingual capability). Google's multispeaker TTS model is limited to English only and requires an additional set up step.
## Setting up Google TTS Model
You can use Google's Multispeaker TTS model by setting the `tts_model` parameter to `geminimulti` in `Podcastfy`.
Google's Multispeaker TTS model requires a Google Cloud API key, you can use the same API key you are already using for Gemini or create a new one. After you have secured your API Key there are two additional steps in order to use Google Multispeaker TTS model:
- Step 1: You will need to enable the Cloud Text-to-Speech API on the API key.
- Go to "https://console.cloud.google.com/apis/dashboard"
- Select your project (or create one by clicking on project list and then on "new project")
- Click "+ ENABLE APIS AND SERVICES" at the top of the screen
- Enter "text-to-speech" into the search box
- Click on "Cloud Text-to-Speech API" and then on "ENABLE"
- You should be here: "https://console.cloud.google.com/apis/library/texttospeech.googleapis.com?project=..."
- Step 2: You need to add the Cloud Text-to-Speech API permission to the API KEY you're using on the Google Cloud console.
- Go to https://console.cloud.google.com/apis/credentials
- Click on whatever key you're using for Gemini
- Go down to API Restrictions and add the Cloud Text-to-Speech API
<br>
⚠️**NOTE :**<br>
By default, **Google Multi-Speaker voices** are only available to **allowlisted projects**. If you wish to use these voices, follow the steps below: <br>
- **Prerequisites:** A **paid Google Cloud support subscription** is required to proceed.
- **Request Access:** You'll need to **contact Google Cloud Support** to get Multi-Speaker voices enabled for your project.
- **Common Error:** If Multi-Speaker voices are not enabled, you will encounter the following runtime error:
```bash
RuntimeError: Failed to generate audio: 403 Multi-speaker voices are only available to allowlisted projects
```
- **How to Proceed:**
- Navigate to the **Support** section in your **GCP Console**. <br>
- Open a new case under **"Cases"** and provide the necessary project details. <br>
- Google Cloud Support should be able to assist you in enabling this feature. <br>
<br>

<br>
Phew!!! That was a lot of steps but you only need to do it once and you might be impressed with the quality of the audio. See [Google TTS](https://cloud.google.com/text-to-speech) for more details. Thank you @mobarski and @evandempsey for the help!
## Conversation Configuration
See [conversation_custom.md](conversation_custom.md) for more details.
## Running Local LLMs
See [local_llm.md](local_llm.md) for more details.
## Optional configuration
The `config.yaml` file in the root directory contains non-sensitive configuration settings. You can modify this file to adjust various parameters such as output directories, text-to-speech settings, and content generation options.
The application will automatically load the environment variables from `.env` and the configuration settings from `config.yaml` when it runs.
See [Configuration](config_custom.md) if you would like to further customize settings. | {
"source": "souzatharsis/podcastfy",
"title": "usage/config.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/usage/config.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 5415
} |
# Podcastfy Advanced Configuration Guide
Podcastfy uses a `config.yaml` file to manage various settings and parameters. This guide explains each configuration option available in the file.
## Content Generator
- `gemini_model`: "gemini-1.5-pro-latest"
- The Gemini AI model used for content generation.
- `max_output_tokens`: 8192
- Maximum number of tokens for the output generated by the AI model.
- `temperature`: 1
- Controls randomness in the AI's output. 0 means deterministic responses. Range for gemini-1.5-pro: 0.0 - 2.0 (default: 1.0)
- `langchain_tracing_v2`: false
- Enables LangChain tracing for debugging and monitoring. If true, requires langsmith api key
## Content Extractor
- `youtube_url_patterns`:
- Patterns to identify YouTube URLs.
- Current patterns: "youtube.com", "youtu.be"
## Website Extractor
- `markdown_cleaning`:
- `remove_patterns`:
- Patterns to remove from extracted markdown content.
- Current patterns remove image links, hyperlinks, and URLs.
## YouTube Transcriber
- `remove_phrases`:
- Phrases to remove from YouTube transcriptions.
- Current phrase: "[music]"
## Logging
- `level`: "INFO"
- Default logging level.
- `format`: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
- Format string for log messages.
## Website Extractor
- `markdown_cleaning`:
- `remove_patterns`:
- Additional patterns to remove from extracted markdown content:
- '\[.*?\]': Remove square brackets and their contents
- '\(.*?\)': Remove parentheses and their contents
- '^\s*[-*]\s': Remove list item markers
- '^\s*\d+\.\s': Remove numbered list markers
- '^\s*#+': Remove markdown headers
- `unwanted_tags`:
- HTML tags to be removed during extraction:
- 'script', 'style', 'nav', 'footer', 'header', 'aside', 'noscript'
- `user_agent`: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36'
- User agent string to be used for web requests
- `timeout`: 10
- Request timeout in seconds for web scraping | {
"source": "souzatharsis/podcastfy",
"title": "usage/config_custom.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/usage/config_custom.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 2054
} |
# Podcastfy Conversation Configuration
Podcastfy offers a range of customization options to tailor your AI-generated podcasts. This document outlines how you can adjust parameters such as conversation style, word count, and dialogue structure to suit your specific needs.
## Table of Contents
1. [Parameters](#parameters)
2. [Customization Examples](#customization-examples)
1. [Academic Debate](#academic-debate)
2. [Storytelling Adventure](#storytelling-adventure)
3. [Customization Scenarios](#customization-scenarios)
1. [Using the Python Package](#using-the-python-package)
2. [Using the CLI](#using-the-cli)
4. [Notes of Caution](#notes-of-caution)
## Conversation Parameters
Podcastfy uses the default conversation configuration stored in [podcastfy/conversation_config.yaml](https://github.com/souzatharsis/podcastfy/blob/main/podcastfy/conversation_config.yaml).
| Parameter | Default Value | Type | Description |
|-----------|---------------|------|-------------|
| conversation_style | ["engaging", "fast-paced", "enthusiastic"] | list[str] | Styles to apply to the conversation |
| roles_person1 | "main summarizer" | str | Role of the first speaker |
| roles_person2 | "questioner/clarifier" | str | Role of the second speaker |
| dialogue_structure | ["Introduction", "Main Content Summary", "Conclusion"] | list[str] | Structure of the dialogue |
| podcast_name | "PODCASTIFY" | str | Name of the podcast |
| podcast_tagline | "Your Personal Generative AI Podcast" | str | Tagline for the podcast |
| output_language | "English" | str | Language of the output |
| engagement_techniques | ["rhetorical questions", "anecdotes", "analogies", "humor"] | list[str] | Techniques to engage the audience |
| creativity | 1 | float | Level of creativity/temperature (0-1) |
| user_instructions | "" | str | Custom instructions to guide the conversation focus and topics |
| max_num_chunks | 7 | int | Maximum number of rounds of discussions in longform |
| min_chunk_size | 600 | int | Minimum number of characters to generate a round of discussion in longform |
## Text-to-Speech (TTS) Settings
Podcastfy uses the default TTS configuration stored in [podcastfy/conversation_config.yaml](https://github.com/souzatharsis/podcastfy/blob/main/podcastfy/conversation_config.yaml).
### ElevenLabs TTS
- `default_voices`:
- `question`: "Chris"
- Default voice for questions in the podcast.
- `answer`: "Jessica"
- Default voice for answers in the podcast.
- `model`: "eleven_multilingual_v2"
- The ElevenLabs TTS model to use.
### OpenAI TTS
- `default_voices`:
- `question`: "echo"
- Default voice for questions using OpenAI TTS.
- `answer`: "shimmer"
- Default voice for answers using OpenAI TTS.
- `model`: "tts-1-hd"
- The OpenAI TTS model to use.
### Gemini Multi-Speaker TTS
- `default_voices`:
- `question`: "R"
- Default voice for questions using Gemini Multi-Speaker TTS.
- `answer`: "S"
- Default voice for answers using Gemini Multi-Speaker TTS.
- `model`: "en-US-Studio-MultiSpeaker"
- Model to use for Gemini Multi-Speaker TTS.
- `language`: "en-US"
- Language of the voices.
### Gemini TTS
- `default_voices`:
- `question`: "en-US-Journey-D"
- Default voice for questions using Gemini TTS.
- `answer`: "en-US-Journey-O"
- Default voice for answers using Gemini TTS.
### Edge TTS
- `default_voices`:
- `question`: "en-US-JennyNeural"
- Default voice for questions using Edge TTS.
- `answer`: "en-US-EricNeural"
- Default voice for answers using Edge TTS.
### General TTS Settings
- `default_tts_model`: "openai"
- Default text-to-speech model to use.
- `output_directories`:
- `transcripts`: "./data/transcripts"
- Directory for storing generated transcripts.
- `audio`: "./data/audio"
- Directory for storing generated audio files.
- `audio_format`: "mp3"
- Format of the generated audio files.
- `temp_audio_dir`: "data/audio/tmp/"
- Temporary directory for audio processing.
- `ending_message`: "Bye Bye!"
- Message to be appended at the end of the podcast.
## Customization Examples
These examples demonstrate how conversations can be altered to suit different purposes, from academic rigor to creative storytelling. The comments explain the rationale behind each choice, helping users understand how to tailor the configuration to their specific needs.
### Academic Debate
This configuration transforms the podcast into a formal academic debate, encouraging deep analysis and critical thinking. It's designed for educational content or in-depth discussions on complex topics.
```python
{
"word_count": 3000, # Longer to allow for detailed arguments
"conversation_style": ["formal", "analytical", "critical"], # Appropriate for academic discourse
"roles_person1": "thesis presenter", # Presents the main argument
"roles_person2": "counterargument provider", # Challenges the thesis
"dialogue_structure": [
"Opening Statements",
"Thesis Presentation",
"Counterarguments",
"Rebuttals",
"Closing Remarks"
], # Mimics a structured debate format
"podcast_name": "Scholarly Showdown",
"podcast_tagline": "Where Ideas Clash and Knowledge Emerges",
"engagement_techniques": [
"socratic questioning",
"historical references",
"thought experiments"
], # Techniques to stimulate critical thinking
"creativity": 0 # Low creativity to maintain focus on facts and logic
}
```
### Storytelling Adventure
This configuration turns the podcast into an interactive storytelling experience, engaging the audience in a narrative journey. It's ideal for fiction podcasts or creative content marketing.
```yaml
word_count: 1000 # Shorter to maintain pace and suspense
conversation_style:
- narrative
- suspenseful
- descriptive # Creates an immersive story experience
roles_person1: storyteller
roles_person2: audience participator # Allows for interactive elements
dialogue_structure:
- Scene Setting
- Character Introduction
- Rising Action
- Climax
- Resolution # Follows classic storytelling structure
podcast_name: Tale Spinners
podcast_tagline: Where Every Episode is an Adventure
engagement_techniques:
- cliffhangers
- vivid imagery
- audience prompts # Keeps the audience engaged and coming back
creativity: 0.9 # High creativity for unique and captivating stories
```
## Customization Scenarios
### Using the Python Package
When using the Podcastfy Python package, you can customize the conversation by passing a dictionary to the `conversation_config` parameter:
```python
from podcastfy.client import generate_podcast
custom_config = {
"word_count": 200,
"conversation_style": ["casual", "humorous"],
"podcast_name": "Tech Chuckles",
"creativity": 0.7
}
generate_podcast(
urls=["https://example.com/tech-news"],
conversation_config=custom_config
)
```
### Using the CLI
When using the Podcastfy CLI, you can specify a path to a YAML file containing your custom configuration:
```bash
podcastfy --url https://example.com/tech-news --conversation-config path/to/custom_config.yaml
```
The `custom_config.yaml` file should contain your configuration in YAML format:
```yaml
word_count: 200
conversation_style:
- casual
- humorous
podcast_name: Tech Chuckles
creativity: 0.7
```
## Notes of Caution
- The `word_count` is a target, and the AI may generate more or less than the specified word count. Low word counts are more likely to generate high-level discussions, while high word counts are more likely to generate detailed discussions.
- The `output_language` defines both the language of the transcript and the language of the audio. Here's some relevant information:
- Bottom-line: non-English transcripts are good enough but non-English audio is work-in-progress.
- Transcripts are generated using Google's Gemini 1.5 Pro by default, which supports 100+ languages. Other user-defined models may or may not support non-English languages.
- Audio is generated using `openai` (default), `elevenlabs`, `gemini`, `geminimulti` or `edge` TTS models.
- The `gemini`(Google) TTS model supports multiple languages and can be controlled by the `output_language` parameter and respective voice choices. Eg. `output_language="Tamil"`, `question="ta-IN-Standard-A"`, `answer="ta-IN-Standard-B"`. Refer to [Google Cloud Text-to-Speech documentation](https://cloud.google.com/text-to-speech/docs/voices) for more details.
- The `geminimulti`(Google) TTS model supports only English voices. Also, not every Google Cloud project might have access to multi-speaker voices (Eg. `en-US-Studio-MultiSpeaker`). In case if you get - `"Multi-speaker voices are only available to allowlisted projects."`, you can fallback to `gemini` TTS model.
- The `openai` TTS model supports multiple languages automatically, however non-English voices still present sub-par quality in my experience.
- The `elevenlabs` TTS model has English voices by default, in order to use a non-English voice you would need to download a custom voice for the target language in your `elevenlabs` account settings and then set the `text_to_speech.elevenlabs.default_voices` parameters to the voice you want to use in the [config.yaml file](https://github.com/pedroslopez/podcastfy/blob/main/podcastfy/config.yaml) (this config file is only available in the source code of the project, not in the pip package, hence if you are using the pip package you will not be able to change the ElevenLabs voice). For more information on ElevenLabs voices, visit [ElevenLabs Voice Library](https://elevenlabs.io/voice-library) | {
"source": "souzatharsis/podcastfy",
"title": "usage/conversation_custom.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/usage/conversation_custom.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 9719
} |
# Docker Setup Guide for Podcastfy
This guide explains how to use Docker to run Podcastfy in your local environment or for development.
## Prerequisites
- Docker installed on your system [1]
- Docker Compose [1]
- API keys [2]
[1] See Appendix A for detailed installation instructions.
[2] See [config.md](https://github.com/souzatharsis/podcastfy/blob/main/usage/config.md) for more details.
## Available Images
Podcastfy provides pre-built Docker images through GitHub Container Registry (ghcr.io):
1. **Production Image**: `ghcr.io/souzatharsis/podcastfy:latest`
- Contains the latest PyPI release
- Recommended for production use
2. **Development Image**: `ghcr.io/souzatharsis/podcastfy:dev`
- Includes development tools and dependencies
- Used for contributing and development
## Deployment
### Quick Deployment Steps
1. Create a new directory and navigate to it:
```bash
mkdir -p /path/to/podcastfy
cd /path/to/podcastfy
```
2. Create a `.env` file with your API keys (see [config.md](https://github.com/souzatharsis/podcastfy/blob/main/usage/config.md) for more details):
```plaintext
GEMINI_API_KEY=your_gemini_api_key
OPENAI_API_KEY=your_openai_api_key # Optional: only needed for OpenAI TTS
```
3. Create a `docker-compose.yml`:
```yaml
version: '3.8'
services:
podcastfy:
image: ghcr.io/souzatharsis/podcastfy:latest
environment:
- GEMINI_API_KEY=${GEMINI_API_KEY}
- OPENAI_API_KEY=${OPENAI_API_KEY}
ports:
- "8000:8000"
command: python3 -m podcastfy.server
healthcheck:
test: ["CMD", "python3", "-c", "import podcastfy"]
interval: 30s
timeout: 10s
retries: 3
```
4. Pull and start the container:
```bash
docker pull ghcr.io/souzatharsis/podcastfy:latest
docker-compose up podcastfy
```
The service will be available at `http://localhost:8000`
### Directory Structure
```
/path/to/podcastfy/
├── .env # Environment variables
└── docker-compose.yml # Docker Compose configuration
```
## Development Setup
### Using Pre-built Development Image
1. Pull the development image:
```bash
docker pull ghcr.io/souzatharsis/podcastfy:dev
```
2. Clone the repository and start development environment:
```bash
git clone https://github.com/souzatharsis/podcastfy.git
cd podcastfy
docker-compose up podcastfy-dev
```
### Building Locally
Alternatively, you can build the images locally:
```bash
# Build production image
docker-compose build podcastfy
# Build development image
docker-compose build podcastfy-dev
```
## Running Tests
Run the test suite using:
```bash
docker-compose up test
```
This will run tests in parallel using pytest-xdist.
## Environment Variables
Required environment variables:
- `GEMINI_API_KEY` - Your Google Gemini API key
- `OPENAI_API_KEY` - Your OpenAI API key (optional: only needed for OpenAI TTS)
## Container Details
### Production Container
- Based on Ubuntu 24.04
- Installs Podcastfy from PyPI
- Includes FFmpeg for audio processing
- Runs in a Python virtual environment
- Exposed port: 8000
### Development Container
- Based on Ubuntu 24.04
- Includes development tools (flake8, pytest)
- Mounts local code for live development
- Runs in editable mode (`pip install -e .`)
- Exposed port: 8001
## Continuous Integration
The Docker images are automatically:
- Built and tested on every push to main branch
- Built and tested for all pull requests
- Published to GitHub Container Registry
- Tagged with version numbers for releases (v*.*.*)
## Health Checks
All services include health checks that:
- Run every 30 seconds
- Verify Podcastfy can be imported
- Timeout after 10 seconds
- Retry up to 3 times
## Common Commands
```bash
# Pull latest production image
docker pull ghcr.io/souzatharsis/podcastfy:latest
# Pull development image
docker pull ghcr.io/souzatharsis/podcastfy:dev
# Start production service
docker-compose up podcastfy
# Start development environment
docker-compose up podcastfy-dev
# Run tests
docker-compose up test
# Build images locally
docker-compose build
# View logs
docker-compose logs
# Stop all containers
docker-compose down
```
## Troubleshooting
### Common Issues
1. **API Key Errors**
- Verify your `.env` file exists and contains valid API keys
- Check if the environment variables are properly passed to the container
2. **Port Conflicts**
- Ensure ports 8000 (production) and 8001 (development) are available
- Modify the port mappings in `docker-compose.yml` if needed
3. **Volume Mounting Issues (Development)**
- Verify the correct path to your local code
- Check permissions on the mounted directories
4. **Image Pull Issues**
- Ensure you have access to the GitHub Container Registry
- If you see "unauthorized" errors, the image might be private
- Try authenticating with GitHub: `docker login ghcr.io -u YOUR_GITHUB_USERNAME`
### Verifying Installation
You can verify your installation by checking if the package can be imported:
```bash
# Check production version
docker run --rm ghcr.io/souzatharsis/podcastfy:latest python3 -c "import podcastfy"
# Check development setup
docker-compose exec podcastfy-dev python3 -c "import podcastfy"
```
## System Requirements
Minimum requirements:
- Docker Engine 20.10.0 or later
- Docker Compose 2.0.0 or later
- Sufficient disk space for Ubuntu base image (~400MB)
- Additional space for Python packages and FFmpeg
## Support
If you encounter any issues:
1. Check the container logs: `docker-compose logs`
2. Verify all prerequisites are installed
3. Ensure all required environment variables are set
4. Open an issue on the [Podcastfy GitHub repository](https://github.com/souzatharsis/podcastfy/issues)
## Appendix A: Detailed Installation Guide
### Installing Docker
#### Windows
1. Download and install [Docker Desktop for Windows](https://docs.docker.com/desktop/install/windows-install/)
- For Windows 10/11 Pro, Enterprise, or Education: Enable WSL 2 and Hyper-V
- For Windows 10 Home: Enable WSL 2
2. After installation, start Docker Desktop
3. Verify installation:
```bash
docker --version
```
#### macOS
1. Download and install [Docker Desktop for Mac](https://docs.docker.com/desktop/install/mac-install/)
- For Intel chip: Download Intel package
- For Apple chip: Download Apple Silicon package
2. After installation, start Docker Desktop
3. Verify installation:
```bash
docker --version
```
#### Ubuntu/Debian
```bash
# Remove old versions
sudo apt-get remove docker docker-engine docker.io containerd runc
# Install prerequisites
sudo apt-get update
sudo apt-get install \
ca-certificates \
curl \
gnupg \
lsb-release
# Add Docker's official GPG key
sudo mkdir -p /etc/apt/keyrings
curl -fsSL https://download.docker.com/linux/ubuntu/gpg | sudo gpg --dearmor -o /etc/apt/keyrings/docker.gpg
# Set up repository
echo \
"deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.gpg] https://download.docker.com/linux/ubuntu \
$(lsb_release -cs) stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
# Install Docker Engine
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io docker-compose-plugin
# Add your user to docker group (optional, to run docker without sudo)
sudo usermod -aG docker $USER
newgrp docker
# Verify installation
docker --version
```
#### Other Linux Distributions
- [CentOS](https://docs.docker.com/engine/install/centos/)
- [Fedora](https://docs.docker.com/engine/install/fedora/)
- [RHEL](https://docs.docker.com/engine/install/rhel/)
### Installing Docker Compose
Docker Compose is included with Docker Desktop for Windows and macOS. For Linux:
```bash
# Download the current stable release
sudo curl -L "https://github.com/docker/compose/releases/download/v2.24.1/docker-compose-$(uname -s)-$(uname -m)" -o /usr/local/bin/docker-compose
# Apply executable permissions
sudo chmod +x /usr/local/bin/docker-compose
# Verify installation
docker-compose --version
```
### Post-Installation Steps
1. Verify Docker is running:
```bash
docker run hello-world
```
2. Configure Docker to start on boot (Linux only):
```bash
sudo systemctl enable docker.service
sudo systemctl enable containerd.service
```
## Appendix B: Getting API Keys
### Google Gemini API Key
1. Visit [Google AI Studio](https://makersuite.google.com/app/apikey)
2. Create or sign in to your Google account
3. Click "Create API Key"
4. Copy and save your API key
### OpenAI API Key
You only need an OpenAI API key if you want to use the OpenAI Text-to-Speech model.
1. Visit [OpenAI API Keys](https://platform.openai.com/api-keys)
2. Create or sign in to your OpenAI account
3. Click "Create new secret key"
4. Copy and save your API key
## Appendix C: Installation Validation
After installing all prerequisites, verify everything is set up correctly:
```bash
# Check Docker version
docker --version
# Check Docker Compose version
docker-compose --version
# Verify Docker daemon is running
docker ps
# Test Docker functionality
docker run hello-world
``` | {
"source": "souzatharsis/podcastfy",
"title": "usage/docker.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/usage/docker.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 9079
} |
# How to
All assume you have podcastfy installed and running.
## Table of Contents
- [Custom LLM Support](#custom-llm-support)
- [Running Local LLMs](#running-local-llms)
- [How to use your own voice in audio podcasts](#how-to-use-your-own-voice-in-audio-podcasts)
- [How to customize the conversation](#how-to-customize-the-conversation)
- [How to generate multilingual content](#how-to-generate-multilingual-content)
- [How to steer the conversation](#how-to-steer-the-conversation)
- [How to generate longform podcasts](#how-to-generate-longform-podcasts)
## Custom LLM Support
Podcastfy offers a range of LLM models for generating transcripts including OpenAI, Anthropic, Google as well as local LLM models.
### Cloud-based LLMs
By default, Podcastfy uses Google's `gemini-1.5-pro-latest` model. To select a particular cloud-based LLM model, users can pass the `llm_model_name` and `api_key_label` parameters to the `generate_podcast` function. See [full list of supported models](https://docs.litellm.ai/docs/providers) for more details.
For example, to use OpenAI's `gpt-4-turbo` model, users can pass `llm_model_name="gpt-4-turbo"` and `api_key_label="OPENAI_API_KEY"`.
```python
audio_file = generate_podcast(
urls=["https://en.wikipedia.org/wiki/Artificial_intelligence"],
llm_model_name="gpt-4-turbo",
api_key_label="OPENAI_API_KEY"
)
```
Remember to have the correct API key label and value in your environment variables (`.env` file).
### Running Local LLMs
See [local_llm.md](local_llm.md) for more details.
## How to use your own voice in audio podcasts
You just need to use ElevenLabs TSS backend and pass a custom config to use your voice instead of podcastfy's default:
1. Create elevenlabs account, get and [set up](https://github.com/souzatharsis/podcastfy/blob/main/usage/config.md) eleven labs API KEY
2. Clone your voice on elevenlabs website (let's say its name is 'Robbert')
4. Create custom conversation config (let's call it custom_config.yaml) to use your voice name instead of the default as described [here](https://github.com/souzatharsis/podcastfy/blob/main/usage/conversation_custom.md#text-to-speech-tts-settings). Set either question or answer voice below to 'Robbert' in elevenlabs > default_voices.
6. Run podcastfy with tts-model param as elevenlabs
CLI
```
python -m podcastfy.client --url https://example.com/article1 --url https://example.com/article2 --tts-model elevenlabs --conversation-config path/to/custom_config.yaml
```
For Python example, checkout Customization section at [python notebook](https://github.com/souzatharsis/podcastfy/blob/main/podcastfy.ipynb).
## How to customize the conversation
You can customize the conversation by passing a custom [conversation_config.yaml](https://github.com/souzatharsis/podcastfy/blob/main/podcastfy/conversation_config.yaml) file to the CLI:
```
python -m podcastfy.client --url https://example.com/article1 --url https://example.com/article2 --tts-model elevenlabs --conversation-config path/to/custom_config.yaml
```
You can also pass a dictionary with the custom config to the python interface generate_podcast function:
```python
from podcastfy.client import generate_podcast
custom_config = {
"word_count": 200,
"conversation_style": ["casual", "humorous"],
"podcast_name": "Tech Chuckles",
"creativity": 0.7
}
generate_podcast(
urls=["https://example.com/tech-news"],
conversation_config=custom_config
)
```
For more details, checkout [conversation_custom.md](https://github.com/souzatharsis/podcastfy/blob/main/usage/conversation_custom.md).
## How to generate multilingual content
In order to generate transcripts in a target language, simply set `output_language` = your target language. See [How to customize the conversation](#how-to-customize-the-conversation) on how to pass custom configuration to podcastfy. Set --transcript-only to get only the transcript without audio generation.
In order to generation audio, you can simply use openai TTS model which by default is multilingual. However, in my experience OpenAI's TTS multilingual quality is subpar. Instead, consdier using elevenlabs backend. See [How to use your own voice in audio podcasts](#how-to-use-your-own-voice-in-audio-podcasts) but instead of using your own voice you should download and set a voice in your target language for it to work.
Sample audio:
- [French](https://github.com/souzatharsis/podcastfy/blob/main/data/audio/podcast_FR_AGRO.mp3)
- [Portugue-BR](https://github.com/souzatharsis/podcastfy/blob/main/data/audio/podcast_thatupiso_BR.mp3)
The PT-BR audio actually uses my own cloned voice as AI Host 2.
## How to steer the conversation
You can guide the conversation focus and topics by setting the `user_instructions` parameter in your custom configuration. This allows you to provide specific instructions to the AI hosts about what aspects they should emphasize or explore.
Things to try:
- Focus on a specific topic (e.g. "Focus the discussion on key capabilities and limitations of modern AI models")
- Target a specific audience (e.g. "Explain concepts in a way that's accessible to someone new to Computer Science")
For example, using the CLI with a custom YAML:
```yaml
user_instructions: "Make connections with quantum computing"
```
```
python -m podcastfy.client --url https://en.wikipedia.org/wiki/Artificial_intelligence --conversation-config path/to/custom_config.yaml
```
## How to generate longform podcasts
By default, Podcastfy generates shortform podcasts. However, users can generate longform podcasts by setting the `longform` parameter to `True`.
```python
audio_file = generate_podcast(
urls=["https://example.com/article1", "https://example.com/article2"],
longform=True
)
```
LLMs have a limited ability to output long text responses. Most LLMs have a `max_output_tokens` of around 4096 and 8192 tokens. Hence, long-form podcast transcript generation is challeging. We have implemented a technique I call "Content Chunking with Contextual Linking" to enable long-form podcast generation by breaking down the input content into smaller chunks and generating a conversation for each chunk while ensuring the combined transcript is coherent and linked to the original input.
By default, shortform podcasts (default configuration) generate audio of about 2-5 minutes while longform podcasts may reach 20-30 minutes.
Users may adjust lonform podcast length by setting the following parameters in your customization params (conversation_config.yaml):
- `max_num_chunks` (default: 7): Sets maximum number of rounds of discussions.
- `min_chunk_size` (default: 600): Sets minimum number of characters to generate a round of discussion.
A "round of discussion" is the output transcript obtained from a single LLM call. The higher the `max_num_chunks` and the lower the `min_chunk_size`, the longer the generated podcast will be.
Today, this technique allows the user to generate long-form podcasts of any length if input content is long enough. However, the conversation quality may decrease and its length may converge to a maximum if `max_num_chunks`/`min_chunk_size` is to high/low particularly if input content length is limited.
Current implementation limitations:
- Images are not yet supported for longform podcast generation
- Base LLM model is fixed to Gemini
Above limitations are somewhat easily fixable however we chose to make updates in smaller but quick iterations rather than making all-in changes. | {
"source": "souzatharsis/podcastfy",
"title": "usage/how-to.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/usage/how-to.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 7523
} |
## Attribution
1. If you use `Podcastfy` in your software, we kindly ask you to add attribution. "Powered by Podcastfy.ai" would suffice. Please reach out, we would love to learn more how you are using `Podcastfy` and how we can better enable your use case.
2. Feel free to add your product to the the "[Built with Podcastfy](https://github.com/souzatharsis/podcastfy?tab=readme-ov-file#built-with-podcastfy-)" list by submitting a PR to our README.
## License
Additionally, `Podcastfy` is licensed under Apache 2.0. The Apache License 2.0 is a permissive free software license that allows you to use this sotfware for both non-commercial or commercial purposes.
Please review the [License](../LICENSE) in order to know your obligations.
here is a set of steps I will list without any warranty or liability:
1. Include a copy of the license in your project:
In your project root, create a NOTICE.txt or THIRD_PARTY_LICENSES.txt file and include the content from the file [NOTICE](../NOTICE)
2. Add attribution in your README.md:
```markdown
## Acknowledgments
This project includes code from Podcastfy(https://github.com/souzatharsis/podcastfy/), licensed under the Apache License 2.0.
```
3. Keep the original copyright notices in any files you copy/modify
4. If you modified the code, indicate your changes:
```python
# Modified from original source: [Podcastfy](https://github.com/souzatharsis/podcastfy/)
# Changes made:
# - Added feature X
# - Modified function Y
# - Removed component Z
```
Important points:
- You don't need to use the same license for your project
- You must preserve all copyright, patent, trademark notices
- State significant modifications you made
- Include the original Apache 2.0 license text
- Attribution should be clear and reasonable | {
"source": "souzatharsis/podcastfy",
"title": "usage/license-guide.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/usage/license-guide.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 1780
} |
# Local LLM Support
Running local LLMs can offer several advantages such as:
- Enhanced privacy and data security
- Cost control and no API rate limits
- Greater customization and fine-tuning options
- Reduced vendor lock-in
We enable serving local LLMs with [llamafile](https://github.com/Mozilla-Ocho/llamafile). In the API, local LLM support is available through the `is_local` parameter. If `is_local=True`, then a local (llamafile) LLM model is used to generate the podcast transcript. Llamafiles of LLM models can be found on [HuggingFace, which today offers 156+ models](https://huggingface.co/models?library=llamafile).
All you need to do is:
1. Download a llamafile from HuggingFace
2. Make the file executable
3. Run the file
Here's a simple bash script that shows all 3 setup steps for running TinyLlama-1.1B locally:
```bash
# Download a llamafile from HuggingFace
wget https://huggingface.co/jartine/TinyLlama-1.1B-Chat-v1.0-GGUF/resolve/main/TinyLlama-1.1B-Chat-v1.0.Q5_K_M.llamafile
# Make the file executable. On Windows, instead just rename the file to end in ".exe".
chmod +x TinyLlama-1.1B-Chat-v1.0.Q5_K_M.llamafile
# Start the model server. Listens at http://localhost:8080 by default.
./TinyLlama-1.1B-Chat-v1.0.Q5_K_M.llamafile --server --nobrowser
```
Now you can use the local LLM to generate a podcast transcript (or audio) by setting the `is_local` parameter to `True`.
## Python API
```python
from podcastfy.client import generate_podcast
# Generate a tech debate podcast about artificial intelligence
generate_podcast(
urls=["www.souzatharsis.com"],
is_local=True # Using a local LLM
)
```
## CLI
To use a local LLM model via the command-line interface, you can use the `--local` or `-l` flag. Here's an example of how to generate a transcript using a local LLM:
```bash
python -m podcastfy.client --url https://example.com/article1 --transcript-only --local
```
## Notes of caution
When using local LLM models versus widely known private large language models:
1. Performance: Local LLMs often have lower performance compared to large private models due to size and training limitations.
2. Resource requirements: Running local LLMs can be computationally intensive, requiring significant CPU/GPU resources.
3. Limited capabilities: Local models may struggle with complex tasks or specialized knowledge that larger models handle well.
5. Reduced multimodal abilities: Local LLMs will be assumed to be text-only capable
6. Potential instability: Local models may produce less consistent or stable outputs compared to well-tested private models oftentimes producing transcripts that cannot be used for podcast generation (TTS) out-of-the-box
7. Limited context window: Local models often have smaller context windows, limiting their ability to process long inputs.
Always evaluate the trade-offs between using local LLMs and private models based on your specific use case and requirements. We highly recommend extensively testing your local LLM before productionizing an end-to-end podcast generation and/or manually checking the transcript before passing to TTS model. | {
"source": "souzatharsis/podcastfy",
"title": "usage/local_llm.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/usage/local_llm.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 3130
} |
<a name="readme-top"></a>
# Podcastfy.ai 🎙️🤖
[](https://pypi.org/project/podcastfy/)
[](https://pepy.tech/project/podcastfy)
[](https://github.com/souzatharsis/podcastfy/issues)
[](https://podcastfy.readthedocs.io/en/latest/?badge=latest)
[](https://creativecommons.org/licenses/by-nc-sa/4.0/)

[](https://colab.research.google.com/github/souzatharsis/podcastfy/blob/main/podcastfy.ipynb)
Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI
https://github.com/user-attachments/assets/f1559e70-9cf9-4576-b48b-87e7dad1dd0b
Podcastfy is an open-source Python package that transforms multi-modal content (text, images) into engaging, multi-lingual audio conversations using GenAI. Input content include websites, PDFs, youtube videos as well as images.
Unlike UI-based tools focused primarily on note-taking or research synthesis (e.g. NotebookLM ❤️), Podcastfy focuses on the programmatic and bespoke generation of engaging, conversational transcripts and audio from a multitude of multi-modal sources enabling customization and scale.
## Audio Examples 🔊
This sample collection is also [available at audio.com](https://audio.com/thatupiso/collections/podcastfy).
### Images
| Image Set | Description | Audio |
|:--|:--|:--|
| <img src="data/images/Senecio.jpeg" alt="Senecio, 1922 (Paul Klee)" width="20%" height="auto"> <img src="data/images/connection.jpg" alt="Connection of Civilizations (2017) by Gheorghe Virtosu " width="21.5%" height="auto"> | Senecio, 1922 (Paul Klee) and Connection of Civilizations (2017) by Gheorghe Virtosu | [<span style="font-size: 25px;">🔊</span>](https://audio.com/thatupiso/audio/output-file-abstract-art) |
| <img src="data/images/japan_1.jpg" alt="The Great Wave off Kanagawa, 1831 (Hokusai)" width="20%" height="auto"> <img src="data/images/japan2.jpg" alt="Takiyasha the Witch and the Skeleton Spectre, c. 1844 (Kuniyoshi)" width="21.5%" height="auto"> | The Great Wave off Kanagawa, 1831 (Hokusai) and Takiyasha the Witch and the Skeleton Spectre, c. 1844 (Kuniyoshi) | [<span style="font-size: 25px;">🔊</span>](https://audio.com/thatupiso/audio/output-file-japan) |
| <img src="data/images/taylor.png" alt="Taylor Swift" width="28%" height="auto"> <img src="data/images/monalisa.jpeg" alt="Mona Lisa" width="10.5%" height="auto"> | Pop culture icon Taylor Swift and Mona Lisa, 1503 (Leonardo da Vinci) | [<span style="font-size: 25px;">🔊</span>](https://audio.com/thatupiso/audio/taylor-monalisa) |
### Text
| Content Type | Description | Audio | Source |
|--------------|-------------|-------|--------|
| Youtube Video | YCombinator on LLMs | [Audio](https://audio.com/thatupiso/audio/ycombinator-llms) | [YouTube](https://www.youtube.com/watch?v=eBVi_sLaYsc) |
| PDF | Book: Networks, Crowds, and Markets | [Audio](https://audio.com/thatupiso/audio/networks) | book pdf |
| Research Paper | Climate Change in France | [Audio](https://audio.com/thatupiso/audio/agro-paper) | [PDF](./data/pdf/s41598-024-58826-w.pdf) |
| Website | My Personal Website | [Audio](https://audio.com/thatupiso/audio/tharsis) | [Website](https://www.souzatharsis.com) |
| Website + YouTube | My Personal Website + YouTube Video on AI | [Audio](https://audio.com/thatupiso/audio/tharsis-ai) | [Website](https://www.souzatharsis.com), [YouTube](https://www.youtube.com/watch?v=sJE1dE2dulg) |
### Multi-Lingual Text
| Language | Content Type | Description | Audio | Source |
|----------|--------------|-------------|-------|--------|
| French | Website | Agroclimate research information | [Audio](https://audio.com/thatupiso/audio/podcast-fr-agro) | [Website](https://agroclim.inrae.fr/) |
| Portuguese-BR | News Article | Election polls in São Paulo | [Audio](https://audio.com/thatupiso/audio/podcast-thatupiso-br) | [Website](https://noticias.uol.com.br/eleicoes/2024/10/03/nova-pesquisa-datafolha-quem-subiu-e-quem-caiu-na-disputa-de-sp-03-10.htm) |
## Features ✨
- Generate conversational content from multiple-sources and formats (images, websites, YouTube, and PDFs)
- Customizable transcript and audio generation (e.g. style, language, structure, length)
- Create podcasts from pre-existing or edited transcripts
- Support for advanced text-to-speech models (OpenAI, ElevenLabs and Edge)
- Seamless CLI and Python package integration for automated workflows
- Multi-language support for global content creation (experimental!)
## Updates 🚀
### v0.2.2 release
- Podcastfy is now multi-modal! Users can generate audio from images as well as text inputs!
- Added API reference docs and published it to https://podcastfy.readthedocs.io/en/latest/
### v0.2.0 release
- Users can now customize podcast style, structure, and content
- Integration with LangChain for better LLM management
## Quickstart 💻
### Prerequisites
- Python 3.11 or higher
- `$ pip install ffmpeg` (for audio processing)
### Setup
1. Install from PyPI
`$ pip install podcastfy`
2. Set up your [API keys](usage/config.md)
### Python
```python
from podcastfy.client import generate_podcast
audio_file = generate_podcast(urls=["<url1>", "<url2>"])
```
### CLI
```
python -m podcastfy.client --url <url1> --url <url2>
```
## Usage 💻
- [Python Package Quickstart](podcastfy.ipynb)
- [API Reference Manual](https://podcastfy.readthedocs.io/en/latest/podcastfy.html)
- [CLI](usage/cli.md)
Experience Podcastfy with our [HuggingFace](https://huggingface.co/spaces/thatupiso/Podcastfy.ai_demo) 🤗 Spaces app for a simple URL-to-Audio demo. (Note: This UI app is less extensively tested and capable than the Python package.)
## Customization 🔧
Podcastfy offers a range of [Conversation Customization](usage/conversation_custom.md) options to tailor your AI-generated podcasts. Whether you're creating educational content, storytelling experiences, or anything in between, these configuration options allow you to fine-tune your podcast's tone, length, and format.
## Contributing 🤝
We welcome contributions! Please submit [Issues](https://github.com/souzatharsis/podcastfy/issues) or Pull Requests. Feel free to fork the repo and create your own applications. We're excited to learn about your use cases!
## Example Use Cases 🎧🎶
1. **Content Summarization**: Busy professionals can stay informed on industry trends by listening to concise audio summaries of multiple articles, saving time and gaining knowledge efficiently.
2. **Language Localization**: Non-native English speakers can access English content in their preferred language, breaking down language barriers and expanding access to global information.
3. **Website Content Marketing**: Companies can increase engagement by repurposing written website content into audio format, providing visitors with the option to read or listen.
4. **Personal Branding**: Job seekers can create unique audio-based personal presentations from their CV or LinkedIn profile, making a memorable impression on potential employers.
5. **Research Paper Summaries**: Graduate students and researchers can quickly review multiple academic papers by listening to concise audio summaries, speeding up the research process.
6. **Long-form Podcast Summarization**: Podcast enthusiasts with limited time can stay updated on their favorite shows by listening to condensed versions of lengthy episodes.
7. **News Briefings**: Commuters can stay informed about daily news during travel time with personalized audio news briefings compiled from their preferred sources.
8. **Educational Content Creation**: Educators can enhance learning accessibility by providing audio versions of course materials, catering to students with different learning preferences.
9. **Book Summaries**: Avid readers can preview books efficiently through audio summaries, helping them make informed decisions about which books to read in full.
10. **Conference and Event Recaps**: Professionals can stay updated on important industry events they couldn't attend by listening to audio recaps of conference highlights and key takeaways.
## License
This project is licensed under the [Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License](https://creativecommons.org/licenses/by-nc-sa/4.0/).
## Contributors
<a href="https://github.com/souzatharsis/podcastfy/graphs/contributors">
<img alt="contributors" src="https://contrib.rocks/image?repo=souzatharsis/podcastfy"/>
</a>
## Disclaimer
This tool is designed for personal or educational use. Please ensure you have the necessary rights or permissions before using content from external sources for podcast creation. All audio content is AI-generated and it is not intended to clone real-life humans!
<p align="right" style="font-size: 14px; color: #555; margin-top: 20px;">
<a href="#readme-top" style="text-decoration: none; color: #007bff; font-weight: bold;">
↑ Back to Top ↑
</a>
</p> | {
"source": "souzatharsis/podcastfy",
"title": "docs/source/README.md",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/docs/source/README.md",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 9382
} |
.. podcastfy documentation master file, created by
sphinx-quickstart on Sat Oct 12 21:09:23 2024.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Podcastfy.ai API Referece Manual
==========================
This documentation site is focused on the Podcastfy Python package, its classes, functions, and methods.
For additional documentation, see the `Podcastfy <https://github.com/souzatharsis/podcastfy/>`_ GitHub repository.
.. toctree::
:maxdepth: 2
:caption: API Reference:
podcastfy
Quickstart
----------
Prerequisites
^^^^^^^^^^^^^
- Python 3.11 or higher
- ``$ pip install ffmpeg`` (for audio processing)
Installation
^^^^^^^^^^^^
1. Install from PyPI:
``$ pip install podcastfy``
2. Set up your `API keys <https://github.com/souzatharsis/podcastfy/blob/main/usage/config.md>`_
Python
^^^^^^
.. code-block:: python
from podcastfy.client import generate_podcast
audio_file = generate_podcast(urls=["<url1>", "<url2>"])
CLI
^^^
.. code-block:: bash
python -m podcastfy.client --url <url1> --url <url2>
Usage
-----
- `Python Package <https://github.com/souzatharsis/podcastfy/blob/main/podcastfy.ipynb>`_
- `CLI <https://github.com/souzatharsis/podcastfy/blob/main/usage/cli.md>`_
Experience Podcastfy with our `HuggingFace <https://huggingface.co/spaces/thatupiso/Podcastfy.ai_demo>`_ 🤗 Spaces app for a simple URL-to-Audio demo. (Note: This UI app is less extensively tested and capable than the Python package.)
Customization
-------------
Podcastfy offers a range of customization options to tailor your AI-generated podcasts:
* Customize podcast `Conversation <https://github.com/souzatharsis/podcastfy/blob/main/usage/conversation_custom.md>`_ (e.g. format, style)
* Choose to run `Local LLMs <https://github.com/souzatharsis/podcastfy/blob/main/usage/local_llm.md>`_ (156+ HuggingFace models)
* Set `System Settings <https://github.com/souzatharsis/podcastfy/blob/main/usage/config_custom.md>`_ (e.g. text-to-speech and output directory settings)
Collaborate
===========
Fork me at https://github.com/souzatharsis/podcastfy.
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
Licensed under Apache 2.0 | {
"source": "souzatharsis/podcastfy",
"title": "docs/source/index.rst",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/docs/source/index.rst",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 2285
} |
podcastfy
=========
.. toctree::
:maxdepth: 4
podcastfy | {
"source": "souzatharsis/podcastfy",
"title": "docs/source/modules.rst",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/docs/source/modules.rst",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 63
} |
podcastfy.content\_parser package
=================================
Submodules
----------
podcastfy.content\_parser.content\_extractor module
---------------------------------------------------
.. automodule:: podcastfy.content_parser.content_extractor
:members:
:undoc-members:
:show-inheritance:
podcastfy.content\_parser.pdf\_extractor module
-----------------------------------------------
.. automodule:: podcastfy.content_parser.pdf_extractor
:members:
:undoc-members:
:show-inheritance:
podcastfy.content\_parser.website\_extractor module
---------------------------------------------------
.. automodule:: podcastfy.content_parser.website_extractor
:members:
:undoc-members:
:show-inheritance:
podcastfy.content\_parser.youtube\_transcriber module
-----------------------------------------------------
.. automodule:: podcastfy.content_parser.youtube_transcriber
:members:
:undoc-members:
:show-inheritance:
Module contents
---------------
.. automodule:: podcastfy.content_parser
:members:
:undoc-members:
:show-inheritance: | {
"source": "souzatharsis/podcastfy",
"title": "docs/source/podcastfy.content_parser.rst",
"url": "https://github.com/souzatharsis/podcastfy/blob/main/docs/source/podcastfy.content_parser.rst",
"date": "2024-09-30T22:35:09",
"stars": 3232,
"description": "An Open Source Python alternative to NotebookLM's podcast feature: Transforming Multimodal Content into Captivating Multilingual Audio Conversations with GenAI",
"file_size": 1089
} |
Subsets and Splits