创建基于 RAG 的客户端应用程序

已完成

为上下文数据创建 Azure AI 搜索索引后,可以将它与 OpenAI 模型一起使用。 为了使用索引中的数据来为提示提供根据,Azure OpenAI SDK 支持通过索引的连接详细信息来扩展请求。

以下 Python 代码示例演示如何实现此模式。

from openai import AzureOpenAI

# Get an Azure OpenAI chat client
chat_client = AzureOpenAI(
    api_version = "2024-12-01-preview",
    azure_endpoint = open_ai_endpoint,
    api_key = open_ai_key
)

# Initialize prompt with system message
prompt = [
    {"role": "system", "content": "You are a helpful AI assistant."}
]

# Add a user input message to the prompt
input_text = input("Enter a question: ")
prompt.append({"role": "user", "content": input_text})

# Additional parameters to apply RAG pattern using the AI Search index
rag_params = {
    "data_sources": [
        {
            "type": "azure_search",
            "parameters": {
                "endpoint": search_url,
                "index_name": "index_name",
                "authentication": {
                    "type": "api_key",
                    "key": search_key,
                }
            }
        }
    ],
}

# Submit the prompt with the index information
response = chat_client.chat.completions.create(
    model="<model_deployment_name>",
    messages=prompt,
    extra_body=rag_params
)

# Print the contextualized response
completion = response.choices[0].message.content
print(completion)

在此示例中,针对索引的搜索 基于关键字 - 换句话说,查询由用户提示中的文本组成,这些文本与索引文档中的文本匹配。 使用支持它的索引时,另一种方法是使用 基于矢量 的查询,其中索引和查询使用数字向量来表示文本标记。 使用矢量进行搜索可以根据语义相似性和文本匹配进行匹配。

若要使用基于矢量的查询,可以修改 Azure AI 搜索数据源详细信息的规范,以包含嵌入模型;然后,用于向量化查询文本。

rag_params = {
    "data_sources": [
        {
            "type": "azure_search",
            "parameters": {
                "endpoint": search_url,
                "index_name": "index_name",
                "authentication": {
                    "type": "api_key",
                    "key": search_key,
                },
                # Params for vector-based query
                "query_type": "vector",
                "embedding_dependency": {
                    "type": "deployment_name",
                    "deployment_name": "<embedding_model_deployment_name>",
                },
            }
        }
    ],
}