File size: 6,391 Bytes
44e1a5b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
https://platform.openai.com/docs/assistants/tools/function-calling
"""
import argparse
import json
import time

from openai import OpenAI
from openai.pagination import SyncCursorPage
from openai.types.beta.threads import ThreadMessage
from openai.types.beta.assistant import Assistant

from project_settings import environment, project_path


def get_args():
    parser = argparse.ArgumentParser()
    parser.add_argument(
        "--openai_api_key",
        default=environment.get("openai_api_key", default=None, dtype=str),
        type=str
    )
    args = parser.parse_args()
    return args


def get_current_weather(location, unit="fahrenheit"):
    if "tokyo" in location.lower():
        return json.dumps({"location": location, "temperature": "10", "unit": "celsius"})
    elif "san francisco" in location.lower():
        return json.dumps({"location": location, "temperature": "72", "unit": "fahrenheit"})
    else:
        return json.dumps({"location": location, "temperature": "22", "unit": "celsius"})


available_functions = {
    "get_current_weather": get_current_weather,
}


def main():
    """
    assistant.id: asst_9iUOSeG3dUgzBxYqfygvtKLi
    thread.id: thread_9C4dDj5i4jDCtkMCujyBleOc

    """
    args = get_args()

    client = OpenAI(
        api_key=args.openai_api_key
    )

    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"],
                },
            },
        }
    ]
    tools_ = json.dumps(tools, ensure_ascii=False)
    print(tools_.replace("\"", "\\\""))
    exit(0)

    assistant = client.beta.assistants.create(
        instructions="You are a weather bot. Use the provided functions to answer questions.",
        model="gpt-4-1106-preview",
        tools=tools
    )
    print(f"assistant.id: {assistant.id}")

    thread = client.beta.threads.create()
    print(f"thread.id: {thread.id}")

    message = client.beta.threads.messages.create(
        thread_id=thread.id,
        role="user",
        content="what's the whether San Francisco"
    )

    run = client.beta.threads.runs.create(
        thread_id=thread.id,
        assistant_id=assistant.id,
        instructions="Please address the user as Jane Doe. The user has a premium account."
    )

    delta_time = 0.3

    no_update_count = 0
    max_no_update_count = 10
    while True:
        if no_update_count > max_no_update_count:
            break
        time.sleep(delta_time)

        run = client.beta.threads.runs.retrieve(
            thread_id=thread.id,
            run_id=run.id
        )
        print("run.required_action: {}".format(run.required_action))
        if run.required_action is None:
            no_update_count += 1
            continue
        else:

            if run.required_action.type != "submit_tool_outputs":
                raise AssertionError

            tool_outputs = list()
            for tool_call in run.required_action.submit_tool_outputs.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"),
                )
                tool_outputs.append({
                    "tool_call_id": tool_call.id,
                    "output": function_response,
                })

            run = client.beta.threads.runs.submit_tool_outputs(
                thread_id=thread.id,
                run_id=run.id,
                tool_outputs=tool_outputs
            )
            no_update_count = 0

    # wait complete
    while True:
        time.sleep(delta_time)
        run = client.beta.threads.runs.retrieve(
            thread_id=thread.id,
            run_id=run.id
        )
        print(run.created_at)
        print(run.started_at)
        print(run.completed_at)
        print(run.failed_at)
        print(run.expires_at)
        print(run.cancelled_at)

        if run.completed_at is not None:
            break
        if run.failed_at is not None:
            break
        if run.expires_at is not None:
            break
        if run.cancelled_at is not None:
            break

    # messages
    messages = client.beta.threads.messages.list(
        thread_id=thread.id
    )
    messages = messages.model_dump(mode="json")
    messages = json.dumps(messages, indent=4, ensure_ascii=False)
    print(messages)

    return


def main2():
    """
    assistant.id: asst_OrPcAueQLrLYxtksFaPVVeJo
    thread.id: thread_2oJCtoSCYgguOhdssafJM7ab
    run: run_cA8DtX8EnoVGhmvu4VrvF63O
    run.required_action: None
    run id: 2090622954288
    run: run_cA8DtX8EnoVGhmvu4VrvF63O
    run.required_action: None
    run id: 2090623149056

    run.required_action: RequiredAction(submit_tool_outputs=RequiredActionSubmitToolOutputs(tool_calls=[RequiredActionFunctionToolCall(id='call_jalze5uKemfrnkPiJPRehVt0', function=Function(arguments='{"location":"San Francisco, CA"}', name='getCurrentWeather'), type='function')]), type='submit_tool_outputs')

    """
    args = get_args()

    client = OpenAI(
        api_key=args.openai_api_key
    )

    thread_id = "thread_2oJCtoSCYgguOhdssafJM7ab"
    run_id = "run_cA8DtX8EnoVGhmvu4VrvF63O"

    run = client.beta.threads.runs.retrieve(
        thread_id=thread_id,
        run_id=run_id
    )
    print("run: {}".format(run.id))
    print("run.required_action: {}".format(run.required_action))
    print("run id: {}".format(id(run)))

    messages = client.beta.threads.messages.list(
        thread_id=thread_id
    )
    print(messages)

    return


if __name__ == '__main__':
    main()