-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.py
626 lines (555 loc) · 22.3 KB
/
app.py
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
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
# !/usr/bin/env python
# coding: utf-8
# Filename: app.py
# Run command: python -m app
"""
This is the main operations of the script
"""
import argparse
import asyncio
import inspect
import json
import os
import sys
from pathlib import Path
import httpx
import tiktoken
from openai import AsyncOpenAI
from rich.console import Console
from rich.markdown import Markdown
from rich.prompt import Prompt
from config import (
MAIN_SYSTEM_PROMPT,
OPENAI_API_KEY,
OPENAI_MODEL,
OPENAI_TEMP,
OPENAI_TOP_P,
OPENAI_MAX_TOKENS,
live_spinner,
)
from utils.openai_model_tools import (
ask_chat_gpt_4_0314_synchronous,
ask_chat_gpt_4_0314_asynchronous,
ask_chat_gpt_4_32k_0314_synchronous,
ask_chat_gpt_4_32k_0314_asynchronous,
ask_chat_gpt_4_0613_synchronous,
ask_chat_gpt_4_0613_asynchronous,
ask_gpt_4_vision,
)
from utils.openai_dalle_tools import generate_an_image_with_dalle3
from utils.core_tools import get_current_date_time, display_help
from output_methods.audio_pyttsx3 import tts_output
from plugins.plugins_enabled import enable_plugins
sys.path.append(str(Path(__file__).parent))
# Define the rich console
console = Console()
# Define the main OpenAI client
openai_model = OPENAI_MODEL
# Define the main OpenAI client
main_client = AsyncOpenAI(
api_key=OPENAI_API_KEY,
http_client=httpx.AsyncClient(
limits=httpx.Limits(
max_connections=1000,
max_keepalive_connections=100,
)
)
)
# Define the parameters for the OpenAI main client.
openai_defaults = {
"model": OPENAI_MODEL,
"temperature": OPENAI_TEMP,
"top_p": OPENAI_TOP_P,
"max_tokens": OPENAI_MAX_TOKENS,
"frequency_penalty": 0,
"presence_penalty": 0,
}
def join_messages(memory: list[dict]):
"""
This function joins messages for conversation memory.
Args:
memory: The conversation memory.
Returns:
The joined messages.
"""
text = ""
for m in memory:
content = m.get("content")
if content is not None:
text += content + "\n"
return text
def check_under_context_limit(text: str, limit: int, model: str):
"""
This function checks if the context is under the token limit.
Args:
text: The text to check.
limit: The token limit.
model: The model to use.
Returns:
Whether the context is under the token limit.
"""
enc = tiktoken.encoding_for_model(model)
numtokens = len(enc.encode(text))
return numtokens <= limit
async def follow_conversation(
user_text: str, memory: list[dict], mem_size: int, model: str
):
"""
This function follows the conversation.
Args:
user_text: The user text.
memory: The conversation memory.
mem_size: The memory size.
model: The model to use.
Returns:
The conversation memory.
"""
ind = min(mem_size, len(memory))
if ind == 0:
memory = [{"role": "system", "content": MAIN_SYSTEM_PROMPT}]
memory.append({"role": "user", "content": user_text})
while (
not check_under_context_limit(
join_messages(memory),
128000,
model
) and ind > 1
):
ind -= 1
memory.pop(0)
response = await main_client.chat.completions.create(
model=model, messages=memory[-ind:]
)
if (
response.choices
and response.choices[0].message
and response.choices[0].message.content is not None
):
tr = response.choices[0].message.content
memory.append({"role": "assistant", "content": tr})
else:
memory.append(
{
"role": "assistant",
"content": "I'm not sure how to respond to that."
}
)
return memory
async def run_conversation(
messages,
tools,
available_functions,
original_user_input,
memory,
mem_size,
**kwargs,
):
"""
This function runs the conversation.
Args:
messages: The messages.
tools: The tools.
available_functions: The available functions.
original_user_input: The original user input.
memory: The conversation memory.
mem_size: The memory size.
**kwargs: The keyword arguments.
Returns:
The final response from the model.
"""
memory = await follow_conversation(
user_text=original_user_input,
memory=memory,
mem_size=mem_size,
model=openai_defaults["model"],
)
memory.append({"role": "user", "content": original_user_input})
while len(json.dumps(memory)) > 128000:
memory.pop(0)
response = await main_client.chat.completions.create(
model=openai_defaults["model"],
messages=memory[-mem_size:],
tools=tools,
tool_choice="auto",
temperature=openai_defaults["temperature"],
top_p=openai_defaults["top_p"],
max_tokens=openai_defaults["max_tokens"],
frequency_penalty=openai_defaults["frequency_penalty"],
presence_penalty=openai_defaults["presence_penalty"],
)
response_message = response.choices[0].message
tool_calls = (
response_message.tool_calls if hasattr(
response_message, "tool_calls"
) else []
)
if response_message.content is not None:
memory.append(
{
"role": "assistant", "content": response_message.content
}
)
if tool_calls:
messages.append(response_message)
executed_tool_call_ids = []
for tool_call in tool_calls:
function_name = tool_call.function.name
if function_name not in available_functions:
continue
function_to_call = available_functions[function_name]
function_args = json.loads(tool_call.function.arguments)
if inspect.iscoroutinefunction(function_to_call):
function_response = await function_to_call(**function_args)
else:
function_response = function_to_call(**function_args)
if function_response is None:
function_response = "No response received from the function."
elif not isinstance(function_response, str):
function_response = json.dumps(function_response)
function_response_message = {
"role": "tool",
"name": function_name,
"content": function_response,
"tool_call_id": tool_call.id,
}
messages.append(function_response_message)
executed_tool_call_ids.append(tool_call.id)
messages.append(
{
"role": "user",
"content": (
f"Using any data received from the tool calls, dynamically structure the workflow to "
f"process and integrate the information. Continue to perform necessary operations, "
f"including additional requests and tool calls, to ensure the accuracy and completeness "
f"of the response. Your goal is to provide a well-reasoned and verified answer to the "
f"original user request, which was: '{original_user_input}'. Adapt the workflow as needed "
f"to address all aspects of the user's request and deliver a comprehensive solution."
),
}
)
second_response = await main_client.chat.completions.create(
model=openai_defaults["model"],
messages=messages,
tools=tools,
tool_choice="auto",
temperature=openai_defaults["temperature"],
top_p=openai_defaults["top_p"],
max_tokens=openai_defaults["max_tokens"],
frequency_penalty=openai_defaults["frequency_penalty"],
presence_penalty=openai_defaults["presence_penalty"],
)
return second_response, memory
else:
return response, memory
async def main():
"""
This is the main function of the script.
Returns:
The final response from the LLM to the user.
"""
os.system("cls" if os.name == "nt" else "clear")
parser = argparse.ArgumentParser(
description="GPT_ALL - A GPT-4-turbo based Mixture of Expert tools."
)
parser.add_argument(
"--talk", action="store_true", help="Use TTS for the final response"
)
args = parser.parse_args()
use_tts = args.talk
console.print(Markdown("# 👋 GPT_ALL 👋"), style="bold blue")
available_functions = {
"get_current_date_time": get_current_date_time,
"ask_chat_gpt_4_0314_synchronous": ask_chat_gpt_4_0314_synchronous,
"ask_chat_gpt_4_0314_asynchronous": ask_chat_gpt_4_0314_asynchronous,
"ask_chat_gpt_4_32k_0314_synchronous": ask_chat_gpt_4_32k_0314_synchronous,
"ask_chat_gpt_4_32k_0314_asynchronous": ask_chat_gpt_4_32k_0314_asynchronous,
"ask_chat_gpt_4_0613_synchronous": ask_chat_gpt_4_0613_synchronous,
"ask_chat_gpt_4_0613_asynchronous": ask_chat_gpt_4_0613_asynchronous,
"generate_an_image_with_dalle3": generate_an_image_with_dalle3,
"ask_gpt_4_vision": ask_gpt_4_vision,
}
tools = [
{
"type": "function",
"function": {
"name": "get_current_date_time",
"description": "Get the current date and time from the local machine.",
},
},
{
"type": "function",
"function": {
"name": "ask_chat_gpt_4_0314_synchronous",
"description": "This function allows you to ask a larger AI LLM for assistance synchronously, like asking a more experienced colleague for assistance.",
"parameters": {
"type": "object",
"properties": {
"temperature": {
"type": "integer",
"description": "The temperature associated with request: 0 for factual, 2 for creative.",
},
"question": {
"type": "string",
"description": "What are you, the ai assistant, requesting to be done with the text you are providing?",
},
"text": {
"type": "string",
"description": "The text to be analyzed",
},
},
"required": ["question", "text"],
},
},
},
{
"type": "function",
"function": {
"name": "ask_chat_gpt_4_0314_asynchronous",
"description": "This function allows you to ask a larger AI LLM for assistance asynchronously, like asking a more experienced colleague for assistance.",
"parameters": {
"type": "object",
"properties": {
"temperature": {
"type": "integer",
"description": "The temperature associated with request: 0 for factual, 2 for creative.",
},
"question": {
"type": "string",
"description": "What are you, the ai assistant, requesting to be done with the text you are providing?",
},
"text": {
"type": "string",
"description": "The text to be analyzed",
},
},
"required": ["question", "text"],
},
},
},
{
"type": "function",
"function": {
"name": "ask_chat_gpt_4_32k_0314_synchronous",
"description": "This function allows you to ask a larger AI LLM for assistance synchronously, like asking a more experienced colleague for assistance.",
"parameters": {
"type": "object",
"properties": {
"temperature": {
"type": "integer",
"description": "The temperature associated with request: 0 for factual, 2 for creative.",
},
"question": {
"type": "string",
"description": "What are you, the ai assistant, requesting to be done with the text you are providing?",
},
"text": {
"type": "string",
"description": "The text to be analyzed",
},
},
"required": ["question", "text"],
},
},
},
{
"type": "function",
"function": {
"name": "ask_chat_gpt_4_32k_0314_asynchronous",
"description": "This function allows you to ask a larger AI LLM for assistance asynchronously, like asking a more experienced colleague for assistance.",
"parameters": {
"type": "object",
"properties": {
"temperature": {
"type": "integer",
"description": "The temperature associated with request: 0 for factual, 2 for creative.",
},
"question": {
"type": "string",
"description": "What are you, the ai assistant, requesting to be done with the text you are providing?",
},
"text": {
"type": "string",
"description": "The text to be analyzed",
},
},
"required": ["question", "text"],
},
},
},
{
"type": "function",
"function": {
"name": "ask_chat_gpt_4_0613_synchronous",
"description": "This function allows you to ask a larger AI LLM for assistance synchronously, like asking a more experienced colleague for assistance.",
"parameters": {
"type": "object",
"properties": {
"temperature": {
"type": "integer",
"description": "The temperature associated with request: 0 for factual, 2 for creative.",
},
"question": {
"type": "string",
"description": "What are you, the ai assistant, requesting to be done with the text you are providing?",
},
"text": {
"type": "string",
"description": "The text to be analyzed",
},
"tools": {
"type": "string",
"description": "The tools to use for the request.",
},
"tool_choice": {
"type": "string",
"description": "The tool choice to use for the request.",
},
},
"required": ["question", "text"],
},
},
},
{
"type": "function",
"function": {
"name": "ask_chat_gpt_4_0613_asynchronous",
"description": "This function allows you to ask a larger AI LLM for assistance asynchronously, like asking a more experienced colleague for assistance.",
"parameters": {
"type": "object",
"properties": {
"temperature": {
"type": "integer",
"description": "The temperature associated with request: 0 for factual, 2 for creative.",
},
"question": {
"type": "string",
"description": "What are you, the ai assistant, requesting to be done with the text you are providing?",
},
"text": {
"type": "string",
"description": "The text to be analyzed",
},
"tools": {
"type": "string",
"description": "The tools to use for the request.",
},
"tool_choice": {
"type": "string",
"description": "The tool choice to use for the request.",
},
},
"required": ["question", "text"],
},
},
},
{
"type": "function",
"function": {
"name": "ask_gpt_4_vision",
"description": "Ask GPT-4 Vision a question about a specific image file located in the 'uploads' folder.",
"parameters": {
"type": "object",
"properties": {
"image_name": {
"type": "string",
"description": "The name of the image file in the 'uploads' folder.",
},
},
"required": ["image_name"],
},
},
},
{
"type": "function",
"function": {
"name": "generate_an_image_with_dalle3",
"description": "Generate an image with DALL-E 3.",
"parameters": {
"type": "object",
"properties": {
"prompt": {
"type": "string",
"description": "The prompt to use for image generation.",
},
"n": {
"type": "integer",
"description": "The number of images to generate.",
},
"size": {
"type": "string",
"description": "The image size to generate.",
},
"quality": {
"type": "string",
"description": "The image quality to generate.",
},
"style": {
"type": "string",
"description": "The image style to generate. natural or vivid",
},
"response_format": {
"type": "string",
"description": "The response format to use for image generation b64_json or url.",
},
},
"required": ["prompt"],
},
},
},
]
available_functions, tools = await enable_plugins(
available_functions,
tools
)
memory = []
# Main Loop
while True:
user_input = Prompt.ask(
"\nHow can I be of assistance? ([yellow]/tools[/yellow] or [bold yellow]quit[/bold yellow])",
)
if user_input.lower() == "quit":
console.print("\nQuitting the program.", style="bold red")
break
elif user_input.lower() == "/tools":
display_help(tools)
continue
messages = [
{
"role": "system",
"content": f"{MAIN_SYSTEM_PROMPT}",
},
{
"role": "assistant",
"content": "Understood. As we continue, feel free to direct any requests or tasks you'd like assistance with. Whether it's querying information, managing schedules, processing data, or utilizing any of the tools and functionalities I have available, I'm here to help. Just let me know what you need, and I'll do my best to assist you effectively and efficiently.",
},
{"role": "user", "content": f"{user_input}"},
]
with live_spinner:
live_spinner.start()
final_response, memory = await run_conversation(
messages=messages,
tools=tools,
available_functions=available_functions,
original_user_input=user_input,
mem_size=200,
memory=memory,
)
live_spinner.stop()
if final_response:
response_message = final_response.choices[0].message
if response_message.content is not None:
final_text = response_message.content
if use_tts:
console.print("\n" + final_text, style="green")
tts_output(final_text)
else:
console.print("\n" + final_text, style="green")
else:
console.print("\nI'm not sure how to help with that.", style="red")
else:
console.print("\nI'm not sure how to help with that.", style="red")
# Remove tools from the tools list after processing
tools[:] = [tool for tool in tools if not tool.get("function", {}).get("name", "").lower() in user_input.lower()]
# Run the main function
if __name__ == "__main__":
asyncio.run(main())