다음을 통해 공유


RAG(Agent Retrieval Augmented Generation)

Microsoft Agent Framework는 AI 컨텍스트 공급자를 에이전트에 추가하여 에이전트에 RAG(검색 증강 세대) 기능을 쉽게 추가할 수 있도록 지원합니다.

TextSearchProvider 사용

클래스 TextSearchProvider 는 RAG 컨텍스트 공급자의 기본 구현입니다.

에이전트에 ChatClientAgent RAG 기능을 제공하는 옵션을 사용하여 AIContextProviderFactory 쉽게 연결할 수 있습니다.

// Create the AI agent with the TextSearchProvider as the AI context provider.
AIAgent agent = azureOpenAIClient
    .GetChatClient(deploymentName)
    .CreateAIAgent(new ChatClientAgentOptions
    {
        Instructions = "You are a helpful support specialist for Contoso Outdoors. Answer questions using the provided context and cite the source document when available.",
        AIContextProviderFactory = ctx => new TextSearchProvider(SearchAdapter, ctx.SerializedState, ctx.JsonSerializerOptions, textSearchOptions)
    });

쿼리 TextSearchProvider 가 제공된 경우 검색 결과를 제공하는 함수가 필요합니다. Azure AI Search 또는 웹 검색 엔진과 같은 모든 검색 기술을 사용하여 구현할 수 있습니다.

다음은 쿼리를 기반으로 미리 정의된 결과를 반환하는 모의 검색 함수의 예입니다. SourceName SourceLink 은 선택 사항이지만 제공된 경우 에이전트가 사용자의 질문에 대답할 때 정보 원본을 인용하는 데 사용됩니다.

static Task<IEnumerable<TextSearchProvider.TextSearchResult>> SearchAdapter(string query, CancellationToken cancellationToken)
{
    // The mock search inspects the user's question and returns pre-defined snippets
    // that resemble documents stored in an external knowledge source.
    List<TextSearchProvider.TextSearchResult> results = new();

    if (query.Contains("return", StringComparison.OrdinalIgnoreCase) || query.Contains("refund", StringComparison.OrdinalIgnoreCase))
    {
        results.Add(new()
        {
            SourceName = "Contoso Outdoors Return Policy",
            SourceLink = "https://contoso.com/policies/returns",
            Text = "Customers may return any item within 30 days of delivery. Items should be unused and include original packaging. Refunds are issued to the original payment method within 5 business days of inspection."
        });
    }

    return Task.FromResult<IEnumerable<TextSearchProvider.TextSearchResult>>(results);
}

TextSearchProvider 옵션

TextSearchProvider 클래스를 통해 TextSearchProviderOptions 사용자 지정할 수 있습니다. 다음은 모든 모델 호출 전에 검색을 실행하고 대화 컨텍스트의 짧은 롤링 창을 유지하는 옵션을 만드는 예제입니다.

TextSearchProviderOptions textSearchOptions = new()
{
    // Run the search prior to every model invocation and keep a short rolling window of conversation context.
    SearchTime = TextSearchProviderOptions.TextSearchBehavior.BeforeAIInvoke,
    RecentMessageMemoryLimit = 6,
};

클래스는 TextSearchProvider 클래스를 통해 다음 옵션을 지원합니다 TextSearchProviderOptions .

Option 유형 Description Default
SearchTime TextSearchProviderOptions.TextSearchBehavior 검색을 실행해야 하는 시기를 나타냅니다. 에이전트가 호출될 때마다 또는 함수 호출을 통해 요청 시 두 가지 옵션이 있습니다. TextSearchProviderOptions.TextSearchBehavior.BeforeAIInvoke
FunctionToolName string 주문형 모드에서 작동할 때 노출된 검색 도구의 이름입니다. "검색"
FunctionToolDescription string 주문형 모드에서 작동할 때 노출된 검색 도구에 대한 설명입니다. "사용자 질문에 대답하는 데 도움이 되는 추가 정보를 검색할 수 있습니다."
ContextPrompt string 컨텍스트 프롬프트는 모드에서 작동할 때 결과에 접두사로 추가됩니다 BeforeAIInvoke . "## 추가 컨텍스트\n사용자에게 응답할 때 원본 문서에서 다음 정보를 고려합니다."
CitationsPrompt string 모드에서 BeforeAIInvoke 작동할 때 인용을 요청하기 위해 결과 후에 추가된 명령입니다. "문서 이름과 링크를 사용할 수 있는 경우 문서 이름과 링크가 있는 원본 문서에 인용을 포함합니다."
ContextFormatter Func<IList<TextSearchProvider.TextSearchResult>, string> 모드에서 작동할 때 결과 목록의 서식을 완전히 사용자 지정하는 선택적 대리자 BeforeAIInvoke 입니다. 제공된 ContextPromptCitationsPrompt 경우 무시됩니다. null
RecentMessageMemoryLimit int 메모리에 유지하고 검색을 위한 BeforeAIInvoke 검색 입력을 생성할 때 포함할 최근 대화 메시지(사용자 및 도우미 모두)의 수입니다. 0 (사용 안 함)
RecentMessageRolesIncluded List<ChatRole> 검색 입력을 생성할 때 포함할 최근 메시지를 결정할 때 최근 메시지를 필터링할 형식 목록 ChatRole 입니다. ChatRole.User

에이전트 프레임워크에서 의미 체계 커널 VectorStore 사용

Agent Framework는 Semantic Kernel의 VectorStore 컬렉션을 사용하여 에이전트에 RAG 기능을 제공하도록 지원합니다. 이는 의미 체계 커널 검색 함수를 에이전트 프레임워크 도구로 변환하는 브리지 기능을 통해 수행됩니다.

중요합니다

이 기능을 사용하려면 버전 1.38 이상이 필요합니다 semantic-kernel .

VectorStore에서 검색 도구 만들기

Semantic Kernel VectorStore 컬렉션의 메서드는 create_search_function 를 사용하여 KernelFunction에이전트 프레임워크 도구로 변환할 수 있는 메서드를 반환 .as_agent_framework_tool() 합니다. 벡터 저장소 커넥터 설명서를 사용하여 다른 벡터 저장소 컬렉션을 설정하는 방법을 알아봅니다.

from semantic_kernel.connectors.ai.open_ai import OpenAITextEmbedding
from semantic_kernel.connectors.azure_ai_search import AzureAISearchCollection
from semantic_kernel.functions import KernelParameterMetadata
from agent_framework.openai import OpenAIResponsesClient

# Define your data model
class SupportArticle:
    article_id: str
    title: str
    content: str
    category: str
    # ... other fields

# Create an Azure AI Search collection
collection = AzureAISearchCollection[str, SupportArticle](
    record_type=SupportArticle,
    embedding_generator=OpenAITextEmbedding()
)

async with collection:
    await collection.ensure_collection_exists()
    # Load your knowledge base articles into the collection
    # await collection.upsert(articles)

    # Create a search function from the collection
    search_function = collection.create_search_function(
        function_name="search_knowledge_base",
        description="Search the knowledge base for support articles and product information.",
        search_type="keyword_hybrid",
        parameters=[
            KernelParameterMetadata(
                name="query",
                description="The search query to find relevant information.",
                type="str",
                is_required=True,
                type_object=str,
            ),
            KernelParameterMetadata(
                name="top",
                description="Number of results to return.",
                type="int",
                default_value=3,
                type_object=int,
            ),
        ],
        string_mapper=lambda x: f"[{x.record.category}] {x.record.title}: {x.record.content}",
    )

    # Convert the search function to an Agent Framework tool
    search_tool = search_function.as_agent_framework_tool()

    # Create an agent with the search tool
    agent = OpenAIResponsesClient(model_id="gpt-4o").create_agent(
        instructions="You are a helpful support specialist. Use the search tool to find relevant information before answering questions. Always cite your sources.",
        tools=search_tool
    )

    # Use the agent with RAG capabilities
    response = await agent.run("How do I return a product?")
    print(response.text)

검색 동작 사용자 지정

다양한 옵션을 사용하여 검색 함수를 사용자 지정할 수 있습니다.

# Create a search function with filtering and custom formatting
search_function = collection.create_search_function(
    function_name="search_support_articles",
    description="Search for support articles in specific categories.",
    search_type="keyword_hybrid",
    # Apply filters to restrict search scope
    filter=lambda x: x.is_published == True,
    parameters=[
        KernelParameterMetadata(
            name="query",
            description="What to search for in the knowledge base.",
            type="str",
            is_required=True,
            type_object=str,
        ),
        KernelParameterMetadata(
            name="category",
            description="Filter by category: returns, shipping, products, or billing.",
            type="str",
            type_object=str,
        ),
        KernelParameterMetadata(
            name="top",
            description="Maximum number of results to return.",
            type="int",
            default_value=5,
            type_object=int,
        ),
    ],
    # Customize how results are formatted for the agent
    string_mapper=lambda x: f"Article: {x.record.title}\nCategory: {x.record.category}\nContent: {x.record.content}\nSource: {x.record.article_id}",
)

사용할 수 있는 매개 변수에 대한 create_search_function자세한 내용은 의미 체계 커널 설명서를 참조하세요.

여러 검색 함수 사용

다양한 지식 도메인에 대해 에이전트에 여러 검색 도구를 제공할 수 있습니다.

# Create search functions for different knowledge bases
product_search = product_collection.create_search_function(
    function_name="search_products",
    description="Search for product information and specifications.",
    search_type="semantic_hybrid",
    string_mapper=lambda x: f"{x.record.name}: {x.record.description}",
).as_agent_framework_tool()

policy_search = policy_collection.create_search_function(
    function_name="search_policies",
    description="Search for company policies and procedures.",
    search_type="keyword_hybrid",
    string_mapper=lambda x: f"Policy: {x.record.title}\n{x.record.content}",
).as_agent_framework_tool()

# Create an agent with multiple search tools
agent = chat_client.create_agent(
    instructions="You are a support agent. Use the appropriate search tool to find information before answering. Cite your sources.",
    tools=[product_search, policy_search]
)

다른 설명 및 매개 변수를 사용하여 동일한 컬렉션에서 여러 검색 함수를 만들어 특수 검색 기능을 제공할 수도 있습니다.

# Create multiple search functions from the same collection
# Generic search for broad queries
general_search = support_collection.create_search_function(
    function_name="search_all_articles",
    description="Search all support articles for general information.",
    search_type="semantic_hybrid",
    parameters=[
        KernelParameterMetadata(
            name="query",
            description="The search query.",
            type="str",
            is_required=True,
            type_object=str,
        ),
    ],
    string_mapper=lambda x: f"{x.record.title}: {x.record.content}",
).as_agent_framework_tool()

# Detailed lookup for specific article IDs
detail_lookup = support_collection.create_search_function(
    function_name="get_article_details",
    description="Get detailed information for a specific article by its ID.",
    search_type="keyword",
    top=1,
    parameters=[
        KernelParameterMetadata(
            name="article_id",
            description="The specific article ID to retrieve.",
            type="str",
            is_required=True,
            type_object=str,
        ),
    ],
    string_mapper=lambda x: f"Title: {x.record.title}\nFull Content: {x.record.content}\nLast Updated: {x.record.updated_date}",
).as_agent_framework_tool()

# Create an agent with both search functions
agent = chat_client.create_agent(
    instructions="You are a support agent. Use search_all_articles for general queries and get_article_details when you need full details about a specific article.",
    tools=[general_search, detail_lookup]
)

이 방법을 사용하면 에이전트가 사용자의 쿼리에 따라 가장 적절한 검색 전략을 선택할 수 있습니다.

지원되는 VectorStore 커넥터

이 패턴은 다음을 비롯한 모든 의미 체계 커널 VectorStore 커넥터에서 작동합니다.

  • Azure AI Search(AzureAISearchCollection)
  • Qdrant(QdrantCollection)
  • 파인콘 (PineconeCollection)
  • Redis(RedisCollection)
  • Weaviate(WeaviateCollection)
  • In-Memory(InMemoryVectorStoreCollection)
  • 기타

각 커넥터는 에이전트 프레임워크 도구에 연결할 수 있는 동일한 create_search_function 방법을 제공하므로 요구에 가장 적합한 벡터 데이터베이스를 선택할 수 있습니다. 전체 목록은 여기를 참조하세요.

다음 단계