0
openai functioncall 에러 메세지

 Error code: 400 - {'error': {'message': "Invalid parameter: messages with role 'tool' must be a response to a preceeding message with 'tool_calls'.", 'type': 'invalid_request_error', 'param': 'messages.[1].role', 'code': None}}


이번 업데이트된 버전으로 코드를 수정하고 있습니다.


그러던 중 functioncall 기능을 이용한 코드를 수정하였는데, 위와 같은 오류가 발생했습니다.


코드의 구조는 openai에서 제시하고 있는 기본 코드 구조인 다음의 형태를 그대로 따랐지만....


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
from openai import OpenAI
import json
 
client = OpenAI()
 
# Example dummy function hard coded to return the same weather
# In production, this could be your backend API or an external API
def get_current_weather(location, unit="fahrenheit"):
    """Get the current weather in a given location"""
    if "tokyo" in location.lower():
        return json.dumps({"location""Tokyo""temperature""10""unit""celsius"})
    elif "san francisco" in location.lower():
        return json.dumps({"location""San Francisco""temperature""72""unit""fahrenheit"})
    elif "paris" in location.lower():
        return json.dumps({"location""Paris""temperature""22""unit""celsius"})
    else:
        return json.dumps({"location": location, "temperature""unknown"})
 
def run_conversation():
    # Step 1: send the conversation and available functions to the model
    messages = [{"role""user""content""What's the weather like in San Francisco, Tokyo, and Paris?"}]
    tools = [
        {
            "type""function",
            "function": {
                "name""get_current_weather",
                "description""Get the current weather in a given location",
                "parameters": {
                    "type""object",
                    "properties": {
                        "location": {
                            "type""string",
                            "description""The city and state, e.g. San Francisco, CA",
                        },
                        "unit": {"type""string""enum": ["celsius""fahrenheit"]},
                    },
                    "required": ["location"],
                },
            },
        }
    ]
    response = client.chat.completions.create(
        model="gpt-3.5-turbo-1106",
        messages=messages,
        tools=tools,
        tool_choice="auto",  # auto is default, but we'll be explicit
    )
    response_message = response.choices[0].message
    tool_calls = response_message.tool_calls
    # Step 2: check if the model wanted to call a function
    if tool_calls:
        # Step 3: call the function
        # Note: the JSON response may not always be valid; be sure to handle errors
        available_functions = {
            "get_current_weather": get_current_weather,
        }  # only one function in this example, but you can have multiple
        messages.append(response_message)  # extend conversation with assistant's reply
        # Step 4: send the info for each function call and function response to the model
        for tool_call in tool_calls:
            function_name = tool_call.function.name
            function_to_call = available_functions[function_name]
            function_args = json.loads(tool_call.function.arguments)
            function_response = function_to_call(
                location=function_args.get("location"),
                unit=function_args.get("unit"),
            )
            messages.append(
                {
                    "tool_call_id": tool_call.id,
                    "role""tool",
                    "name": function_name,
                    "content": function_response,
                }
            )  # extend conversation with function response
        second_response = client.chat.completions.create(
            model="gpt-3.5-turbo-1106",
            messages=messages,
        )  # get a new response from the model where it can see the function response
        return second_response
print(run_conversation())
cs


오류가 발생했습니다. 


그래서 그냥 

                    "tool_call_id": tool_call.id,
                    "role""tool",
                    "name": function_name,
                    "content": function_response,


이부분을 지우고 

role : assistant 로 넣고 content를 function_respose로 붙여서 임시 방편으로 해결했습니다.


혹시 정확한 해결방법을 아시는 분은 알려주세요!!


티쳐✨ 전라남도
소개
::: Foreducator.com을 운영하는 수학교사 ::: '수학하는 즐거움 시리즈', '수업의 과정' 저자
로그인 후 댓글을 작성하실 수 있습니다.

Activity Logs

There are 2 new tasks for you in “AirPlus Mobile App” project:
Added at 4:23 PM by
img
Meeting with customer
Application Design
img
img
A
In Progress
View
Project Delivery Preparation
CRM System Development
img
B
Completed
View
Invitation for crafting engaging designs that speak human workshop
Sent at 4:23 PM by
img
Task #45890merged with #45890in “Ads Pro Admin Dashboard project:
Initiated at 4:23 PM by
img
3 new application design concepts added:
Created at 4:23 PM by
img
New case #67890is assigned to you in Multi-platform Database Design project
Added at 4:23 PM by
Alice Tan
You have received a new order:
Placed at 5:05 AM by
img

Database Backup Process Completed!

Login into Admin Dashboard to make sure the data integrity is OK
Proceed
New order #67890is placed for Workshow Planning & Budget Estimation
Placed at 4:23 PM by
Jimmy Bold
Pic
Brian Cox 2 mins
현재 준비 중입니다. 추후 chatgpt를 간단히 이용할 수 있도록 구성해 놓겠습니다
5 mins You
Pic
고맙습니다 기다릴게요
Pic
Brian Cox 1 Hour
기다려주셔서 감사합니다!
2 Hours You
Pic
You’ll receive notifications for all issues, pull requests!
Pic
Brian Cox 3 Hours
You can unwatch this repository immediately by clicking here: Keenthemes.com
4 Hours You
Pic
Most purchased Business courses during this sale!
Pic
Brian Cox 5 Hours
Company BBQ to celebrate the last quater achievements and goals. Food and drinks provided
Just now You
Pic
Pic
Brian Cox Just now
Right before vacation season we have the next Big Deal for you.

Shopping Cart

Iblender The best kitchen gadget in 2022
$ 350 for 5
SmartCleaner Smart tool for cooking
$ 650 for 4
CameraMaxr Professional camera for edge
$ 150 for 3
$D Printer Manfactoring unique objekts
$ 1450 for 7
MotionWire Perfect animation tool
$ 650 for 7
Samsung Profile info,Timeline etc
$ 720 for 6
$D Printer Manfactoring unique objekts
$ 430 for 8