Проблема с отправкой правильного ответа от инструментов в модель Azure Open AI (Python) ⇐ Python

Программы на Python
Anonymous
Проблема с отправкой правильного ответа от инструментов в модель Azure Open AI (Python)

Сообщение Anonymous »

Я создаю приложение для обучения и развлечения, которое использует функции: у меня есть данные о погоде (из курса на Udemy), и я добавляю новую функцию, которая запрашивает у пользователя учетные данные на основе определенных вопросов, и получить их данные из базы данных.
Поэтому я создаю строку сообщений в списке сообщений, начиная с системы, а затем добавляя пользователя и помощника.

Код: Выделить всё

messages = [
{
"role": "system",
"content": (
"You are an assistant and you help answer questions only in Polish: "
"If the user asks about their personal data (e.g., provide my email, age, address, or account status, etc.), use the 'logowanie' function unless the requested information has already been retrieved by this function in the message. "
"If the user asks about the weather in a specific location, you respond using the getWeather function. "
"For legal questions, you respond using Azure Search and the ustawa123 index. "
)
}]
prompt = input("Спросите о чем-нибудь или напишите выход в конце: ")

Код: Выделить всё

while prompt != "exit":
messages.append({"role":"user", "content":prompt+" (answer only in polish)"})

response = get_response(messages)
Моя функция get_response выглядит следующим образом:

Код: Выделить всё

def get_response(messages):
tools = [
{
"type": "function",
"function": {
"name": "getWeather",
"description": "Get real-time weather information/data for a specific location/place",
"parameters": {
"type": "object",
"properties": {
"location": {
"type": "string",
"description": "the exact location for which the current weather is to be determined",
},
},
"required": ["location"]
},
}
},
{
"type": "function",
"function": {
"name": "logowanie",
"description": "If a user asks for their personal information (e.g.  my email, age, account balance, and other data that the model normally does not have access to), use this function",
"parameters": {
"type": "object",
"properties": {},
},
}
}
]

response = client.chat.completions.create(
model = "4pl1",
messages = messages ,
max_tokens=800,
temperature=0.4,
top_p=0.7,
frequency_penalty=0,
presence_penalty=0,
extra_body={
"data_sources":[
{
"type": "azure_search",
"parameters": {
"endpoint": "xxx",
"index_name": "ustawa123",
"in_scope": False,
"authentication": {
"type": "api_key",
"key": "xxx",
}
}
}
],
},
tools=tools,
tool_choice="auto"
)
return response
И теперь, когда функция вызывается, я хочу сначала добавить информацию о вызове функции в сообщения, а затем информацию из инструмента

Код: Выделить всё

   if hasattr(response.choices[0].message, 'tool_calls') and response.choices[0].message.tool_calls is not None :
function_name = response.choices[0].message.tool_calls[0].function.name
call_id = response.choices[0].message.tool_calls[0].id
function_argument = json.loads(response.choices[0].message.tool_calls[0].function.arguments)
messages.append({
"role": "assistant",
"content": None,
"tool_calls": {
"tool_call_id": call_id,
"functions":{"name": function_name,
"arguments": json.dumps(function_argument),
"type": "function"  }

}
})
Но это выдает ошибку:

Код: Выделить всё

openai.BadRequestError: Error code: 400 - {'error': {'requestid': 'b3356dff-7a7d-4c3a-a047-ce3fbcf16de9', 'code': 400, 'message': 'Validation error at #/messages/3/name: Extra inputs are not permitted'}}
Я пытаюсь добавить инструмент согласно документации Microsoft

Код: Выделить всё

 messages.append({
"tool_call_id": call_id,
"role": "tool",
"name": function_name,
"content": function_response,
})
Но здесь тоже всегда кричит, что имени здесь быть не должно и когда я его удаляю, модель не замечает, что у нее уже есть ответы.
Я использую последнюю версию библиотеки openai и попробовал несколько версий API, сегодня установил:

Код: Выделить всё

client = AzureOpenAI(
api_key = "xxx",
api_version = "2024-05-01-preview",# "2023-07-01-preview" "2024-02-01",
azure_endpoint = "xxx"
)

Подробнее здесь: https://stackoverflow.com/questions/790 ... n-ai-model

Вернуться в «Python»