(위 이미지를 클릭하면 이 강의의 동영상을 볼 수 있습니다)
AI 에이전트의 메타인지
AI 에이전트의 메타인지에 대한 강의에 오신 것을 환영합니다! 이 장은 AI 에이전트가 자신의 사고 과정을 어떻게 생각할 수 있는지 궁금해하는 초보자를 위해 설계되었습니다. 이 강의를 마치면 주요 개념을 이해하고 AI 에이전트 설계에서 메타인지를 적용할 수 있는 실용적인 예제를 익힐 수 있습니다.
이 강의를 완료한 후, 여러분은 다음을 할 수 있습니다:
메타인지는 자신의 사고를 생각하는 고차원적인 인지 과정을 의미합니다. AI 에이전트의 경우, 이는 자기 인식과 과거 경험을 바탕으로 자신의 행동을 평가하고 조정할 수 있는 능력을 의미합니다. 메타인지, 즉 “생각에 대한 생각”은 에이전트형 AI 시스템 개발에서 중요한 개념입니다. 이는 AI 시스템이 자신의 내부 과정을 인식하고, 행동을 모니터링, 조절, 적응할 수 있도록 합니다. 우리가 상황을 파악하거나 문제를 분석할 때처럼 말이죠. 이러한 자기 인식은 AI 시스템이 더 나은 결정을 내리고, 오류를 식별하며, 시간이 지남에 따라 성능을 향상시키는 데 도움을 줄 수 있습니다. 이는 다시 튜링 테스트와 AI가 세상을 지배할 것인지에 대한 논쟁으로 연결됩니다.
에이전트형 AI 시스템의 맥락에서 메타인지는 다음과 같은 여러 과제를 해결하는 데 도움을 줄 수 있습니다:
메타인지, 즉 “생각에 대한 생각”은 자기 인식과 자신의 인지 과정을 자기 조절하는 고차원적인 인지 과정입니다. AI의 영역에서 메타인지는 에이전트가 자신의 전략과 행동을 평가하고 조정할 수 있는 능력을 부여하여 문제 해결 및 의사 결정 능력을 향상시킵니다. 메타인지를 이해함으로써, 여러분은 더 지능적이고 적응력이 뛰어나며 효율적인 AI 에이전트를 설계할 수 있습니다. 진정한 메타인지에서는 AI가 자신의 추론에 대해 명시적으로 추론하는 모습을 볼 수 있습니다.
예: “저렴한 항공편을 우선시했는데… 직항 항공편을 놓쳤을 수도 있으니 다시 확인해 보자.”
메타인지는 여러 가지 이유로 AI 에이전트 설계에서 중요한 역할을 합니다:
메타인지 과정을 다루기 전에, AI 에이전트의 기본 구성 요소를 이해하는 것이 중요합니다. AI 에이전트는 일반적으로 다음으로 구성됩니다:
이러한 구성 요소는 특정 작업을 수행할 수 있는 “전문성 단위”를 만듭니다.
예시: 여행 에이전트를 생각해 보세요. 이 에이전트는 단순히 휴가를 계획하는 것뿐만 아니라, 실시간 데이터와 과거 고객 경험을 바탕으로 경로를 조정합니다.
여러분이 AI로 구동되는 여행 에이전트 서비스를 설계한다고 상상해 보세요. 이 에이전트, “여행 에이전트”는 사용자가 휴가를 계획하는 데 도움을 줍니다. 메타인지를 통합하려면, 여행 에이전트는 자기 인식과 과거 경험을 바탕으로 자신의 행동을 평가하고 조정해야 합니다. 메타인지가 어떻게 작용할 수 있는지 살펴보겠습니다:
현재 작업은 사용자가 파리 여행을 계획하도록 돕는 것입니다.
여행 에이전트는 메타인지를 사용하여 자신의 성과를 평가하고 과거 경험에서 학습합니다. 예를 들어:
다음은 메타인지를 통합한 여행 에이전트의 코드가 어떻게 보일 수 있는지에 대한 간단한 예입니다:
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)
메타인지를 통합함으로써, 여행 에이전트는 더 개인화되고 정확한 여행 추천을 제공하여 전체 사용자 경험을 향상시킬 수 있습니다.
계획은 AI 에이전트 행동의 중요한 구성 요소입니다. 이는 현재 상태, 자원, 가능한 장애물을 고려하여 목표를 달성하기 위한 단계를 개략적으로 설명하는 것을 포함합니다.
예시: 다음은 여행 에이전트가 사용자의 여행 계획을 효과적으로 돕기 위해 수행해야 할 단계입니다:
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)
우선 RAG 도구와 사전 컨텍스트 로드의 차이를 이해해 봅시다.
RAG는 검색 시스템과 생성 모델을 결합합니다. 쿼리가 이루어지면, 검색 시스템이 외부 소스에서 관련 문서나 데이터를 가져오고, 이 검색된 정보는 생성 모델의 입력을 보강하는 데 사용됩니다. 이를 통해 모델이 더 정확하고 맥락에 맞는 응답을 생성할 수 있습니다.
RAG 시스템에서는 에이전트가 지식 기반에서 관련 정보를 검색하고 이를 사용하여 적절한 응답이나 행동을 생성합니다.
교정 RAG 접근법은 RAG 기술을 사용하여 오류를 수정하고 AI 에이전트의 정확성을 향상시키는 데 중점을 둡니다. 이는 다음을 포함합니다:
웹에서 정보를 검색하여 사용자 쿼리에 답변하는 검색 에이전트를 생각해 보세요. 교정 RAG 접근법은 다음을 포함할 수 있습니다:
교정 RAG (Retrieval-Augmented Generation)는 AI가 정보를 검색하고 생성하는 능력을 향상시키면서 부정확성을 수정합니다. 여행 에이전트가 교정 RAG 접근법을 사용하여 더 정확하고 관련성 높은 여행 추천을 제공하는 방법을 살펴보겠습니다.
이는 다음을 포함합니다:
예:
preferences = {
"destination": "Paris",
"dates": "2025-04-01 to 2025-04-10",
"budget": "moderate",
"interests": ["museums", "cuisine"]
}
예:
flights = search_flights(preferences)
hotels = search_hotels(preferences)
attractions = search_attractions(preferences)
예:
itinerary = create_itinerary(flights, hotels, attractions)
print("Suggested Itinerary:", itinerary)
예:
feedback = {
"liked": ["Louvre Museum"],
"disliked": ["Eiffel Tower (too crowded)"]
}
예:
if "disliked" in feedback:
preferences["avoid"] = feedback["disliked"]
예:
new_attractions = search_attractions(preferences)
new_itinerary = create_itinerary(flights, hotels, new_attractions)
print("Updated Itinerary:", new_itinerary)
예:
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 코드 예시입니다:
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"))
초기화 (__init__
메서드): TravelAgent
클래스는 파리, 도쿄, 뉴욕, 시드니와 같은 인기 여행지에 대한 정보를 포함한 딕셔너리를 미리 로드합니다. 이 딕셔너리에는 각 여행지의 국가, 통화, 언어, 주요 명소와 같은 세부 정보가 포함되어 있습니다.
정보 검색 (get_destination_info
메서드): 사용자가 특정 여행지에 대해 문의하면, get_destination_info
메서드는 미리 로드된 컨텍스트 딕셔너리에서 관련 정보를 가져옵니다.
컨텍스트를 미리 로드함으로써, 여행사 애플리케이션은 실시간으로 외부 소스에서 정보를 검색하지 않고도 사용자 쿼리에 빠르게 응답할 수 있습니다. 이는 애플리케이션을 더 효율적이고 반응적으로 만듭니다.
목표를 설정한 후 계획을 시작하는 것은 명확한 목표나 원하는 결과를 염두에 두고 작업을 시작하는 것을 의미합니다. 이 목표를 사전에 정의함으로써, 모델은 이를 반복 과정 동안 지침으로 사용할 수 있습니다. 이는 각 반복이 원하는 결과에 더 가까워지도록 하여 과정을 더 효율적이고 집중되게 만듭니다.
다음은 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)
초기화 (__init__
메서드): TravelAgent
클래스는 이름, 비용, 활동 유형과 같은 속성을 가진 잠재적인 여행지 목록으로 초기화됩니다.
계획 부트스트래핑 (bootstrap_plan
메서드): 이 메서드는 고객의 선호도와 예산을 기반으로 초기 여행 계획을 생성합니다. 여행지 목록을 순회하며, 고객의 선호도와 예산에 맞는 여행지를 계획에 추가합니다.
선호도 매칭 (match_preferences
메서드): 이 메서드는 특정 여행지가 고객의 선호도와 일치하는지 확인합니다.
계획 반복 (iterate_plan
메서드): 이 메서드는 초기 계획을 개선하기 위해 계획에 포함된 각 여행지를 더 나은 선택지로 교체하려고 시도합니다. 이 과정에서 고객의 선호도와 예산 제약을 고려합니다.
비용 계산 (calculate_cost
메서드): 이 메서드는 현재 계획의 총 비용을 계산하며, 새로운 여행지를 포함한 경우도 고려합니다.
목표(예: 고객 만족도 극대화)를 명확히 설정하고 이를 반복적으로 개선함으로써, 여행사는 고객의 선호도와 예산에 맞는 맞춤형 최적화된 여행 일정을 만들 수 있습니다. 이 접근법은 여행 계획이 처음부터 고객의 요구에 부합하도록 하고, 반복을 통해 점점 더 개선되도록 보장합니다.
대규모 언어 모델(LLM)은 검색된 문서나 생성된 응답의 관련성과 품질을 평가하여 재정렬 및 점수 매기기에 활용될 수 있습니다. 작동 방식은 다음과 같습니다:
검색: 초기 검색 단계에서 쿼리에 따라 후보 문서나 응답 세트를 가져옵니다.
재정렬: LLM은 이 후보들을 평가하고, 관련성과 품질에 따라 순위를 다시 매깁니다. 이 단계는 가장 관련성이 높고 품질이 좋은 정보가 먼저 제공되도록 보장합니다.
점수 매기기: LLM은 각 후보에 점수를 부여하여 관련성과 품질을 반영합니다. 이를 통해 사용자에게 가장 적합한 응답이나 문서를 선택할 수 있습니다.
LLM을 활용한 재정렬 및 점수 매기기를 통해 시스템은 더 정확하고 맥락적으로 적합한 정보를 제공하여 전체 사용자 경험을 향상시킬 수 있습니다.
다음은 Python으로 작성된 여행사 애플리케이션에서 사용자 선호도에 따라 여행지를 재정렬하고 점수를 매기는 방법의 예입니다:
여행사가 고객의 선호도에 따라 최고의 여행지를 추천하려고 합니다. LLM은 여행지를 재정렬하고 점수를 매겨 가장 관련성 높은 옵션이 제공되도록 도와줍니다.
다음은 Azure OpenAI 서비스를 사용하는 예제입니다:
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)
초기화: TravelAgent
클래스는 이름과 설명과 같은 속성을 가진 잠재적인 여행지 목록으로 초기화됩니다.
추천 받기 (get_recommendations
메서드): 이 메서드는 사용자의 선호도를 기반으로 Azure OpenAI 서비스에 보낼 프롬프트를 생성하고, Azure OpenAI API에 HTTP POST 요청을 보냅니다. 응답에는 재정렬되고 점수가 매겨진 여행지가 포함됩니다.
프롬프트 생성 (generate_prompt
메서드): 이 메서드는 사용자의 선호도와 여행지 목록을 포함한 Azure OpenAI 프롬프트를 구성합니다. 프롬프트는 모델이 제공된 선호도를 기반으로 여행지를 재정렬하고 점수를 매기도록 안내합니다.
API 호출: requests
라이브러리를 사용하여 Azure OpenAI API 엔드포인트에 HTTP POST 요청을 보냅니다. 응답에는 재정렬되고 점수가 매겨진 여행지가 포함됩니다.
사용 예시: 여행사는 사용자 선호도(예: 관광 및 다양한 문화에 대한 관심)를 수집하고, Azure OpenAI 서비스를 사용하여 재정렬되고 점수가 매겨진 여행지 추천을 받습니다.
your_azure_openai_api_key
를 실제 Azure OpenAI API 키로, https://your-endpoint.com/...
을 Azure OpenAI 배포의 실제 엔드포인트 URL로 교체하세요.
LLM을 활용한 재정렬 및 점수 매기기를 통해, 여행사는 고객에게 더 개인화되고 관련성 높은 여행 추천을 제공하여 전체 경험을 향상시킬 수 있습니다.
정보 검색 기반 생성(RAG)은 AI 에이전트 개발에서 프롬프트 기법과 도구로 모두 활용될 수 있습니다. RAG의 차이를 이해하면 프로젝트에서 이를 더 효과적으로 활용할 수 있습니다.
정의:
작동 방식:
여행사 예시:
정의:
작동 방식:
여행사 예시:
측면 | 프롬프트 기법 | 도구 |
---|---|---|
수동 vs 자동 | 각 쿼리에 대해 프롬프트를 수동으로 작성. | 검색 및 생성을 자동화. |
제어 | 검색 프로세스에 대한 더 많은 제어 제공. | 검색 및 생성 프로세스를 간소화하고 자동화. |
유연성 | 특정 요구에 따라 맞춤형 프롬프트 작성 가능. | 대규모 구현에 더 효율적. |
복잡성 | 프롬프트 작성 및 조정 필요. | AI 에이전트 아키텍처에 쉽게 통합 가능. |
프롬프트 기법 예시:
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)
도구 예시:
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 에이전트 성능의 중요한 측면입니다. 이는 에이전트가 검색하고 생성한 정보가 사용자에게 적합하고 정확하며 유용한지 확인하는 데 도움을 줍니다. 관련성을 평가하는 방법과 실용적인 예시를 살펴보겠습니다.
예시:
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
예시:
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
예시:
def process_query(query):
# Use NLP to extract key information from the user's query
processed_query = nlp(query)
return processed_query
예시:
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
다음은 여행사가 여행 추천의 관련성을 평가하는 방법에 대한 실용적 예시입니다:
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)
의도 기반 검색은 사용자의 쿼리 뒤에 숨겨진 목적이나 목표를 이해하고 해석하여 가장 관련성 높고 유용한 정보를 검색하고 생성하는 것을 의미합니다. 이 접근법은 단순히 키워드를 일치시키는 것을 넘어 사용자의 실제 요구와 맥락을 파악하는 데 중점을 둡니다.
여행 에이전트를 예로 들어, 의도를 활용한 검색이 어떻게 구현될 수 있는지 살펴보겠습니다.
사용자 선호도 수집
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
사용자 의도 이해
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"
상황 인식
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
검색 및 결과 개인화
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
사용 예시
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)
코드 생성 에이전트는 AI 모델을 사용해 코드를 작성하고 실행하여 복잡한 문제를 해결하고 작업을 자동화합니다.
코드 생성 에이전트는 생성형 AI 모델을 사용해 코드를 작성하고 실행합니다. 이 에이전트는 복잡한 문제를 해결하고 작업을 자동화하며, 다양한 프로그래밍 언어로 코드를 생성하고 실행하여 유용한 통찰을 제공합니다.
코드 생성 에이전트를 설계한다고 가정해 봅시다. 다음은 그 작동 방식입니다:
이번 예제에서는 여행 계획을 돕기 위해 코드 생성 및 실행을 수행하는 여행 에이전트를 설계합니다. 이 에이전트는 여행 옵션 검색, 결과 필터링, 생성형 AI를 활용한 일정 작성 등의 작업을 처리할 수 있습니다.
사용자 선호도 수집
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
데이터 검색을 위한 코드 생성
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
생성된 코드 실행
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)
일정 생성
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)
피드백 기반 조정
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)
테이블 스키마를 기반으로 쿼리 생성 프로세스를 개선하기 위해 환경 인식 및 추론을 활용할 수 있습니다.
다음은 이를 구현하는 방법의 예입니다:
다음은 이러한 개념을 통합한 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)
schema
딕셔너리는 피드백을 기반으로 선호도를 어떻게 조정해야 하는지 정의합니다. 여기에는 favorites
와 avoid
같은 필드와 해당 조정이 포함됩니다.adjust_based_on_feedback
메서드): 이 메서드는 사용자 피드백과 스키마를 기반으로 선호도를 조정합니다.adjust_based_on_environment
메서드): 이 메서드는 스키마와 피드백을 기반으로 조정을 맞춤화합니다.시스템이 환경을 인식하고 스키마를 기반으로 추론함으로써, 더 정확하고 관련성 높은 쿼리를 생성할 수 있어, 더 나은 여행 추천과 개인화된 사용자 경험을 제공합니다.
SQL(구조적 질의 언어)은 데이터베이스와 상호작용하기 위한 강력한 도구입니다. Retrieval-Augmented Generation (RAG) 접근 방식의 일부로 SQL을 사용하면, 데이터베이스에서 관련 데이터를 검색하여 AI 에이전트의 응답이나 작업을 생성하는 데 활용할 수 있습니다. 여행 에이전트의 맥락에서 SQL을 RAG 기법으로 사용하는 방법을 살펴보겠습니다.
예제: 데이터 분석 에이전트:
사용자 선호도 수집
class Travel_Agent:
def __init__(self):
self.user_preferences = {}
def gather_preferences(self, preferences):
self.user_preferences = preferences
SQL 쿼리 생성
def generate_sql_query(table, preferences):
query = f"SELECT * FROM {table} WHERE "
conditions = []
for key, value in preferences.items():
conditions.append(f"{key}='{value}'")
query += " AND ".join(conditions)
return query
SQL 쿼리 실행
import sqlite3
def execute_sql_query(query, database="travel.db"):
connection = sqlite3.connect(database)
cursor = connection.cursor()
cursor.execute(query)
results = cursor.fetchall()
connection.close()
return results
추천 생성
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)
항공편 쿼리
SELECT * FROM flights WHERE destination='Paris' AND dates='2025-04-01 to 2025-04-10' AND budget='moderate';
호텔 쿼리
SELECT * FROM hotels WHERE destination='Paris' AND budget='moderate';
관광지 쿼리
SELECT * FROM attractions WHERE destination='Paris' AND interests='museums, cuisine';
SQL을 Retrieval-Augmented Generation (RAG) 기법의 일부로 활용함으로써, 여행 에이전트와 같은 AI 에이전트는 관련 데이터를 동적으로 검색하고 활용하여 정확하고 개인화된 추천을 제공할 수 있습니다.
메타인지 구현을 보여주기 위해, 문제를 해결하는 동안 자신의 의사결정 과정을 반성하는 간단한 에이전트를 만들어 보겠습니다. 이번 예제에서는 에이전트가 호텔 선택을 최적화하려고 하지만, 오류나 비효율적인 선택을 할 경우 자신의 전략을 평가하고 조정하는 시스템을 구축합니다.
다음은 예제입니다:
class HotelRecommendationAgent:
def __init__(self):
self.previous_choices = [] # Stores the hotels chosen previously
self.corrected_choices = [] # Stores the corrected choices
self.recommendation_strategies = ['cheapest', 'highest_quality'] # Available strategies
def recommend_hotel(self, hotels, strategy):
"""
Recommend a hotel based on the chosen strategy.
The strategy can either be 'cheapest' or 'highest_quality'.
"""
if strategy == 'cheapest':
recommended = min(hotels, key=lambda x: x['price'])
elif strategy == 'highest_quality':
recommended = max(hotels, key=lambda x: x['quality'])
else:
recommended = None
self.previous_choices.append((strategy, recommended))
return recommended
def reflect_on_choice(self):
"""
Reflect on the last choice made and decide if the agent should adjust its strategy.
The agent considers if the previous choice led to a poor outcome.
"""
if not self.previous_choices:
return "No choices made yet."
last_choice_strategy, last_choice = self.previous_choices[-1]
# Let's assume we have some user feedback that tells us whether the last choice was good or not
user_feedback = self.get_user_feedback(last_choice)
if user_feedback == "bad":
# Adjust strategy if the previous choice was unsatisfactory
new_strategy = 'highest_quality' if last_choice_strategy == 'cheapest' else 'cheapest'
self.corrected_choices.append((new_strategy, last_choice))
return f"Reflecting on choice. Adjusting strategy to {new_strategy}."
else:
return "The choice was good. No need to adjust."
def get_user_feedback(self, hotel):
"""
Simulate user feedback based on hotel attributes.
For simplicity, assume if the hotel is too cheap, the feedback is "bad".
If the hotel has quality less than 7, feedback is "bad".
"""
if hotel['price'] < 100 or hotel['quality'] < 7:
return "bad"
return "good"
# Simulate a list of hotels (price and quality)
hotels = [
{'name': 'Budget Inn', 'price': 80, 'quality': 6},
{'name': 'Comfort Suites', 'price': 120, 'quality': 8},
{'name': 'Luxury Stay', 'price': 200, 'quality': 9}
]
# Create an agent
agent = HotelRecommendationAgent()
# Step 1: The agent recommends a hotel using the "cheapest" strategy
recommended_hotel = agent.recommend_hotel(hotels, 'cheapest')
print(f"Recommended hotel (cheapest): {recommended_hotel['name']}")
# Step 2: The agent reflects on the choice and adjusts strategy if necessary
reflection_result = agent.reflect_on_choice()
print(reflection_result)
# Step 3: The agent recommends again, this time using the adjusted strategy
adjusted_recommendation = agent.recommend_hotel(hotels, 'highest_quality')
print(f"Adjusted hotel recommendation (highest_quality): {adjusted_recommendation['name']}")
이 예제의 핵심은 에이전트가:
이는 시스템이 내부 피드백을 기반으로 추론 과정을 조정할 수 있는 간단한 형태의 메타인지입니다.
메타인지는 AI 에이전트의 능력을 크게 향상시킬 수 있는 강력한 도구입니다. 메타인지 프로세스를 통합함으로써, 더 지능적이고 적응력이 뛰어나며 효율적인 에이전트를 설계할 수 있습니다. 추가 자료를 활용해 AI 에이전트에서 메타인지의 흥미로운 세계를 더 탐구해 보세요.
Azure AI Foundry Discord에 참여하여 다른 학습자들과 만나고, 오피스 아워에 참석하며 AI 에이전트에 대한 질문에 답을 얻으세요.
면책 조항:
이 문서는 AI 번역 서비스 Co-op Translator를 사용하여 번역되었습니다. 정확성을 위해 최선을 다하고 있으나, 자동 번역에는 오류나 부정확성이 포함될 수 있습니다. 원본 문서를 해당 언어로 작성된 상태에서 권위 있는 자료로 간주해야 합니다. 중요한 정보의 경우, 전문적인 인간 번역을 권장합니다. 이 번역 사용으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다.