File size: 8,264 Bytes
aca9481
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
https://huggingface.co/spaces/fffiloni/langchain-chat-with-pdf-openai
"""
import argparse
import json
import time
from typing import List, Tuple

import gradio as gr
from openai import OpenAI
from threading import Thread
import _queue
from queue import Queue

import project_settings as settings


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


def greet(question: str, history: List[Tuple[str, str]]):
    answer = "Hello " + question + "!"
    result = history + [(question, answer)]
    return result


def get_message_list(client: OpenAI, thread_id: str):
    messages = client.beta.threads.messages.list(
        thread_id=thread_id
    )

    result = list()
    for message in messages.data:

        content = list()
        for msg in message.content:
            content.append({
                "text": {
                    "annotations": msg.text.annotations,
                    "value": msg.text.value,
                },
                "type": msg.type,

            })

        result.append({
            "id": message.id,
            "assistant_id": message.assistant_id,
            "content": content,
            "created_at": message.created_at,
            "file_ids": message.file_ids,
            "metadata": message.metadata,
            "object": message.object,
            "role": message.role,
            "run_id": message.run_id,
            "thread_id": message.thread_id,

        })

    result = list(sorted(result, key=lambda x: x["created_at"]))
    return result


def convert_message_list_to_response(message_list: List[dict]) -> str:
    response = ""
    for message in message_list:
        role = message["role"]
        content = message["content"]

        for c in content:
            if c["type"] != "text":
                continue
            text: dict = c["text"]
            msg = "{}: \n{}\n".format(role, text["value"])
            response += msg
            response += "-" * 80
            response += "\n"

    return response


def streaming_refresh(openai_api_key: str,
                      thread_id: str,
                      queue: Queue,
                      ):
    delta_time = 0.3
    last_response = None
    no_updates_count = 0
    max_no_updates_count = 5
    while True:
        time.sleep(delta_time)

        this_response = refresh(openai_api_key, thread_id)

        if this_response == last_response:
            no_updates_count += 1
        if no_updates_count >= max_no_updates_count:
            break
        last_response = this_response

        queue.put(this_response, block=True, timeout=2)

    return last_response


def refresh(openai_api_key: str,
            thread_id: str,
            ):
    client = OpenAI(
        api_key=openai_api_key,
    )

    message_list = get_message_list(client, thread_id=thread_id)
    response = convert_message_list_to_response(message_list)
    return response


def add_and_run(openai_api_key: str,
                assistant_id: str,
                thread_id: str,
                name: str,
                instructions: str,
                model: str,
                query: str,
                ):
    client = OpenAI(
        api_key=openai_api_key,
    )
    if assistant_id is None or len(assistant_id.strip()) == 0:
        assistant = client.beta.assistants.create(
            name=name,
            instructions=instructions,
            # tools=[{"type": "code_interpreter"}],
            model=model,
        )
        assistant_id = assistant.id

    if thread_id is None or len(thread_id.strip()) == 0:
        thread = client.beta.threads.create()
        thread_id = thread.id

    message = client.beta.threads.messages.create(
        thread_id=thread_id,
        role="user",
        content=query
    )
    run = client.beta.threads.runs.create(
        thread_id=thread_id,
        assistant_id=assistant_id,
    )
    run = client.beta.threads.runs.retrieve(
        thread_id=thread_id,
        run_id=run.id
    )

    response_queue = Queue(maxsize=10)
    refresh_kwargs = dict(
        openai_api_key=openai_api_key,
        thread_id=thread_id,
        queue=response_queue,
    )
    thread = Thread(target=streaming_refresh, kwargs=refresh_kwargs)
    thread.start()

    delta_time = 0.1
    last_response = None
    no_updates_count = 0
    max_no_updates_count = 10
    while True:
        time.sleep(delta_time)

        try:
            this_response = response_queue.get(block=True, timeout=2)
        except _queue.Empty:
            break

        if this_response == last_response:
            no_updates_count += 1
        if no_updates_count >= max_no_updates_count:
            break
        last_response = this_response

        result = [
            assistant_id, thread_id,
            last_response
        ]
        yield result


def main():
    args = get_args()

    description = """
    chat llm
    """

    # ui
    with gr.Blocks() as blocks:
        gr.Markdown(value=description)

        with gr.Row():
            # settings
            with gr.Column(scale=3):
                with gr.Tabs():
                    with gr.TabItem("create assistant"):
                        openai_api_key = gr.Text(
                            value=args.openai_api_key,
                            label="openai_api_key",
                            placeholder="Fill with your `openai_api_key`"
                        )

                        name = gr.Textbox(label="name")
                        instructions = gr.Textbox(label="instructions")

                        model = gr.Dropdown(["gpt-4-1106-preview"], value="gpt-4-1106-preview", label="model")

                        # functions
                        functions = gr.TextArea(label="functions")

                        # upload files
                        retrieval_files = gr.Files(label="retrieval files")

            # chat
            with gr.Column(scale=5):
                response = gr.Textbox(lines=5, max_lines=80, label="response")
                query = gr.Textbox(lines=2, label="query")

                # chat_bot = gr.Chatbot([], elem_id="context", height=400)
                # text_box = gr.Textbox(show_label=False, placeholder="Enter text and press enter", container=False)

                with gr.Row():
                    with gr.Column(scale=1):
                        add_and_run_button = gr.Button("Add and run")
                    with gr.Column(scale=1):
                        refresh_button = gr.Button("Refresh")

            # states
            with gr.Column(scale=2):
                # upload files
                assistant_id = gr.Textbox(value=None, label="assistant_id")
                thread_id = gr.Textbox(value=None, label="thread_id")

        # examples
        with gr.Row():
            gr.Examples(
                examples=[
                    [
                        "Math Tutor",
                        "You are a personal math tutor. Write and run code to answer math questions.",
                        "gpt-4-1106-preview",
                        "123 * 524 等于多少?"
                    ]
                ],
                inputs=[
                    name, instructions, model,
                    query,
                ],
                examples_per_page=5
            )

        # add and run
        add_and_run_button.click(
            add_and_run,
            inputs=[
                openai_api_key,
                assistant_id, thread_id,
                name, instructions, model,
                query,
            ],
            outputs=[
                assistant_id, thread_id,
                response,
            ],
        )

        # refresh

        refresh_button.click(
            refresh,
            inputs=[
                openai_api_key,
                thread_id,
            ],
            outputs=[
                response
            ]
        )

    blocks.queue().launch()

    return


if __name__ == '__main__':
    main()