Azure AI 搜索错误:参数名称:$skip 异常详细信息:ParameterValueOutOfRange 值必须介于 0 和 100000 之间

问题描述 投票:0回答:1

当我执行以下代码时,结果是

raise HttpResponseError(response=response, model=error)
azure.core.exceptions.HttpResponseError: (InvalidRequestParameter) Value must be between 0 and 100000.  
Code: InvalidRequestParameter
Message: Value must be between 0 and 100000.
Parameter name: $skip
Exception Details:      (ParameterValueOutOfRange) Value must be between 0 and 100000.
        Code: ParameterValueOutOfRange
        Message: Value must be between 0 and 100000.

我的知识库中的文档数量只有 14000 个,但我不明白为什么它超过了 100,000 个。

代码片段如下所示:

import asyncio
import os
import semantic_kernel as sk
from semantic_kernel.connectors.ai.open_ai import AzureTextCompletion,AzureChatCompletion
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient
from azure.search.documents.models import QueryType
from services import Service

# Initialize the Semantic Kernel
kernel = sk.Kernel()

# Initialize Azure Cognitive Search client
search_client = SearchClient(
    endpoint=AZURE_SEARCH_ENDPOINT,
    index_name=AZURE_SEARCH_INDEX_NAME,
    credential=AzureKeyCredential(AZURE_SEARCH_API_KEY)
)

class SearchPlugin:
    def search_documents(self, query: str) -> str:
        search_parameters = {
            "top": 50,  # Number of results to return
            "skip": 0   # Number of results to skip
        }
        results = search_client.search(search_text=query, query_type=QueryType.SIMPLE)
        #, **search_parameters)
        print("Number of documents = ", len(list(results)))
        response = [doc['content'] for doc in results]
        return '\n'.join(response)


# Manually register the plugins with the kernel
plugins = {"SearchPlugin": SearchPlugin()}

# Define a function to interact with the AI agent
def interact_with_agent(plugins, plugin_name, function_name, **kwargs):
    plugin = plugins.get(plugin_name)
    if not plugin:
        raise ValueError(f"Plugin {plugin_name} not found.")
    func = getattr(plugin, function_name, None)
    if not func:
        raise ValueError(f"Function {function_name} not found in plugin {plugin_name}.")
    return func(**kwargs)

# System prompt for the chat completion
prompt = "You are an AI language model assistant."
from semantic_kernel.connectors.ai.open_ai import OpenAIChatPromptExecutionSettings
from semantic_kernel.prompt_template import InputVariable, PromptTemplateConfig

selectedService = Service.AzureOpenAI
service_id="gpt-4o"
chat_completion = AzureChatCompletion(service_id=service_id,
    endpoint=AZURE_OPENAI_ENDPOINT,
    api_key=AZURE_OPENAI_API_KEY,
    deployment_name=AZURE_OPENAI_DEPLOYMENT_NAME
)

kernel.add_service(chat_completion)

execution_settings = kernel.get_prompt_execution_settings_from_service_id(
    service_id=service_id
)

execution_settings.max_tokens = 2000
execution_settings.temperature = 0.7
execution_settings.top_p = 0.8

prompt_template_config = PromptTemplateConfig(
    template=prompt,
    name="PMI Chatbot",
    template_format="semantic-kernel",
    input_variables=[
        InputVariable(name="input", description="The user input", is_required=True),
    ],
    execution_settings=execution_settings,
)

Respnose_Func = kernel.add_function(
    function_name=interact_with_agent(plugins, "SearchPlugin", "search_documents", query=service_query), 
    plugin_name="SearchPlugin",
    prompt_template_config=prompt_template_config,
)
   
# Run your prompt
# Note: functions are run asynchronously
async def main():
    input_text = "What is Project Management"
    result = await kernel.invoke(Respnose_Func, input=input_text)
    print(result) 

if __name__ == "__main__":
    asyncio.run(main())

有人可以帮我使上面的代码可执行吗? TIA

我尝试上网,但没有找到解决方案。我希望这段代码运行时不会出现错误。

python-3.x azure-ai azure-ai-search semantic-kernel
1个回答
0
投票

为了解决 Azure AI 搜索中有关

$skip
参数值超出范围的错误问题,我们需要确保
$skip
的值在 0 到 100,000 的有效范围内。
The error message  indicates that the value of 
$跳过
is exceeding this limit.

  • 添加
    search_client.search
    方法应正确使用
    skip
    top
    参数来迭代结果,而不超出 Azure AI 搜索限制。

下面的代码使用 Python 中的语义内核将 Azure 认知搜索与 Azure OpenAI 服务集成

我参考了此链接,通过语义内核在数据上使用 Azure OpenAI。

我参考了 this 使用 Python 进行 Azure 搜索。

import asyncio
import os
import semantic_kernel as sk
from azure.core.credentials import AzureKeyCredential
from azure.search.documents import SearchClient
from azure.search.documents.models import QueryType
from semantic_kernel.connectors.ai.open_ai import AzureChatCompletion
from semantic_kernel.prompt_template import InputVariable, PromptTemplateConfig
from azure.core.exceptions import HttpResponseError, ClientAuthenticationError

AZURE_SEARCH_ENDPOINT = "PUT-YOUR-SEARCH-ENDPOINT-HERE"
AZURE_SEARCH_INDEX_NAME = "indexnmae"
AZURE_SEARCH_API_KEY =  "PUT-YOUR-SEARCH-API-KEY-HERE"


kernel = sk.Kernel()


search_client = SearchClient(
    endpoint=AZURE_SEARCH_ENDPOINT,
    index_name=AZURE_SEARCH_INDEX_NAME,
    credential=AzureKeyCredential(AZURE_SEARCH_API_KEY)
)


class SearchPlugin:
    def search_documents(self, query: str, skip: int, top: int) -> str:
        search_parameters = {
            "skip": skip,
            "top": top,
        }
        try:
            results = search_client.search(search_text=query, query_type=QueryType.SIMPLE, **search_parameters)
            
          
            for doc in results:
                print("Document:", doc)
            
        
            response = [doc.get('description', 'No description available') for doc in results]
            return '\n'.join(response)
        except ClientAuthenticationError as auth_err:
            print(f"Authentication error: {auth_err}")
            return "Authentication error: Unable to authenticate with Azure Cognitive Search."
        except HttpResponseError as http_err:
            print(f"HTTP error occurred: {http_err}")
            return f"HTTP error occurred: {http_err.response.status_code} - {http_err.message}"


plugins = {"SearchPlugin": SearchPlugin()}


service_id = "gpt-4o"
chat_completion = AzureChatCompletion(
    service_id=service_id,
    endpoint="AZURE_OPENAI_ENDPOINT",
    api_key="AZURE_OPENAI_API_KEY",
    deployment_name="AZURE_OPENAI_DEPLOYMENT_NAME"
)


kernel.add_service(chat_completion)


prompt_template_config = PromptTemplateConfig(
    template="You are an AI language model assistant.",
    name="PMI Chatbot",
    template_format="semantic-kernel",
    input_variables=[
        InputVariable(name="input", description="The user input", is_required=True),
    ],
)

s
async def main():
   
    service_query = "What is Project Management"
    
   
    skip = 0
    top = 50
    
    
    search_function = plugins["SearchPlugin"].search_documents
    
    
    result = search_function(query=service_query, skip=skip, top=top)
    
    print(result) 

if __name__ == "__main__":
    asyncio.run(main())


输出: enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.