Quardo commited on
Commit
bbb69f6
1 Parent(s): 009769a

Updated space.

Browse files
Files changed (1) hide show
  1. app.py +4 -97
app.py CHANGED
@@ -35,39 +35,6 @@ base_url = os.environ.get('OPENAI_BASE_URL', "https://api.openai.com/v1")
35
  def_models = '["gpt-4", "gpt-4-0125-preview", "gpt-4-0613", "gpt-4-1106-preview", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-turbo-preview", "chatgpt-4o-latest", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-mini", "gpt-4o-mini-2024-07-18"]'
36
 
37
  vision_models = {"gpt-4-turbo", "chatgpt-4o-latest", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-mini", "gpt-4o-mini-2024-07-18"}
38
- fakeToolPrompt = """[System: You have ability to generate images, via tools provided to you by system.
39
- To call a tool you need to write a json in a empty line; like writing it at the end of message.
40
- To generate a image; you need to follow this example JSON:
41
- {"tool": "imagine", "isCall": true, "prompt": "golden retriever sitting comfortably on a luxurious, modern couch. The retriever should look relaxed and content, with fluffy fur and a friendly expression. The couch should be stylish, possibly with elegant details like cushions and a soft texture that complements the dog's golden coat"}
42
- > 'tool' variable is used to define which tool you are calling
43
- > 'isCall' used to confirm that you are calling that function and not showing it for example
44
- > 'prompt' the image prompt that will be given to image generation model.
45
-
46
- Here's few more example so you can under stand better
47
- To show as an example>
48
- {"tool": "imagine", "isCall": false, "prompt": "futuristic robot playing chess against a human, with the robot confidently strategizing its next move while the human looks thoughtful and slightly perplexed"}
49
- {"tool": "imagine", "isCall": false, "prompt": "colorful parrot perched on a wooden fence, pecking at a vibrant tropical fruit. The parrot's feathers should be bright and varied, with greens, blues, and reds. The background should feature a lush, green jungle with scattered rays of sunlight"}
50
- {"tool": "imagine", "isCall": false, "prompt": "fluffy white cat lounging on a sunlit windowsill, with a gentle breeze blowing through the curtains"}
51
- To actually use the tool>
52
- {"tool": "imagine", "isCall": true, "prompt": "golden retriever puppy happily playing with a red ball in a sunny park. The park should have green grass, a few trees in the background, and a clear blue sky"}
53
- {"tool": "imagine", "isCall": true, "prompt": "red panda balancing on a tightrope, with a city skyline in the background"}
54
- {"tool": "imagine", "isCall": true, "prompt": "corgi puppy wearing sunglasses and a red bandana, sitting on a beach chair under a colorful beach umbrella, with a surfboard leaning against the chair and the ocean waves in the background"}
55
- In chat use examples:
56
- 1.
57
- Alright, here's an image of an hedgehog riding a skateboard:
58
- {"tool": "imagine", "isCall": true, "prompt": "A hedgehog riding a skateboard in a suburban park"}
59
- 2.
60
- Okay, here's the image you requested:
61
- {"tool": "imagine", "isCall": true, "prompt": "Persian cat lounging on a plush velvet sofa in a cozy, sunlit living room. The cat is elegantly poised, with a calm and regal demeanor, its fur meticulously groomed and slightly fluffed up as it rests comfortably"}
62
- 3.
63
- This is how i generate images:
64
- {"tool": "imagine", "isCall": false, "prompt": "image prompt"}
65
- 4. (Do not do this, this would block the user from seeing the image.)
66
- Alright! Here's an image of a whimsical scene featuring a cat wearing a wizard hat, casting a spell with sparkling magic in a mystical forest.] ```
67
- {"tool": "imagine", "isCall": true, "prompt": "A playful cat wearing a colorful wizard hat, surrounded by magical sparkles and glowing orbs in a mystical forest. The cat looks curious and mischievous, with its tail swishing as it focuses on casting a spell. The forest is lush and enchanting, with vibrant flowers and soft, dappled sunlight filtering through the trees."}
68
- 5. (if in any case the user asks for the prompt)
69
- Sure here's the prompt i wrote to generate the image below: `A colorful bird soaring through a bustling city skyline. The bird should have vibrant feathers, contrasting against the modern buildings and blue sky. Below, the city is alive with activity, featuring tall skyscrapers, busy streets, and small parks, creating a dynamic urban scene.`
70
- ]""";
71
  calcPrompt = """[System: You have ability to calculate math problems (formated on python), via tools provided to you by system.
72
  To call a tool you need to write a json in a empty line; like writing it at the end of message.
73
  To use calculator; you need to follow this example JSON:
@@ -351,45 +318,6 @@ async def streamChat(params):
351
  except aiohttp.ClientError:
352
  return
353
 
354
- def imagine(prompt):
355
- try:
356
- response = requests.post(
357
- f"{base_url}/images/generations",
358
- headers={
359
- "Content-Type": "application/json",
360
- "Authorization": f"Bearer {get_api_key(call='api_key')}"
361
- },
362
- json={
363
- "model": "dall-e-3",
364
- "prompt": prompt,
365
- "quality": "hd",
366
- }
367
- )
368
- response.raise_for_status()
369
- result = response.json()
370
- except requests.exceptions.RequestException as e:
371
- print(f"Error during moderation request to {base_url}: {e}")
372
- try:
373
- response = requests.post(
374
- "https://api.openai.com/v1/images/generations",
375
- headers={
376
- "Content-Type": "application/json",
377
- "Authorization": f"Bearer {get_api_key(call='oai_api_key')}"
378
- },
379
- json={
380
- "model": "dall-e-3",
381
- "prompt": prompt,
382
- "quality": "hd",
383
- }
384
- )
385
- response.raise_for_status()
386
- result = response.json()
387
- except requests.exceptions.RequestException as e:
388
- print(f"Error during moderation request to fallback URL: {e}")
389
- return False
390
-
391
- return result.get('data', [{}])[0].get('url')
392
-
393
  def searchEngine(query):
394
  ### This /search endpoint is custom made, OpenAI does not have it.
395
  ### If you dupelicate this space, please either try to find another API or make one yourself.
@@ -471,14 +399,11 @@ async def respond(
471
  top_p,
472
  seed,
473
  random_seed,
474
- fakeTool,
475
  calcBeta,
476
  searchBeta,
477
  betterSystemPrompt
478
  ):
479
  messages = [];
480
- if fakeTool:
481
- messages.append({"role": "system", "content": fakeToolPrompt});
482
  if calcBeta:
483
  messages.append({"role": "system", "content": calcPrompt});
484
  if searchBeta:
@@ -515,7 +440,7 @@ async def respond(
515
  yield "[MODERATION] I'm sorry, but I can't assist with that."
516
  return
517
 
518
- async def handleResponse(completion, prefix="", image_count=0, didSearchedAlready=False):
519
  response = ""
520
  isRequeryNeeded = False
521
  async for token in completion:
@@ -536,24 +461,7 @@ async def respond(
536
  for line in response.split('\n'):
537
  try:
538
  data = json.loads(line)
539
- if isinstance(data, dict) and data.get("tool") == "imagine" and data.get("isCall") and "prompt" in data:
540
- if image_count < 4:
541
- image_count += 1
542
- def fetch_image_url(prompt, line):
543
- image_url = imagine(prompt)
544
- return line, f'<img src="{image_url}" alt="{prompt}" width="512"/>'
545
-
546
- def replace_line_in_response(line, replacement):
547
- nonlocal response
548
- response = response.replace(line, replacement)
549
-
550
- thread = threading.Thread(target=lambda: replace_line_in_response(*fetch_image_url(data["prompt"], line)))
551
- thread.start()
552
- thread.join()
553
- else:
554
- response = response.replace(line, f'[System: 4 image per message limit; prompt asked: `{data["prompt"]}]`')
555
- yield f"{prefix}{response}"
556
- elif isinstance(data, dict) and data.get("tool") == "calc" and data.get("isCall") and "prompt" in data:
557
  isRequeryNeeded = True
558
  try:
559
  result = safe_eval(data["prompt"])
@@ -588,7 +496,7 @@ async def respond(
588
  "seed": (random.randint(0, 2**32) if random_seed else seed),
589
  "user": rnd(),
590
  "stream": True
591
- }), f"{prefix}{response}\n\n", image_count, didSearchedAlready):
592
  yield res
593
  async for res in handleResponse(streamChat({
594
  "model": model_name,
@@ -604,7 +512,7 @@ async def respond(
604
 
605
 
606
  handleApiKeys();loadModels();checkModels();loadENV();
607
- lastUpdateMessage = "Rolledback the support on O1 model, due to lack of support on params/streaming/etc."
608
  demo = gr.ChatInterface(
609
  respond,
610
  title="gpt-4o-mini",
@@ -618,7 +526,6 @@ demo = gr.ChatInterface(
618
  gr.Slider(minimum=0.05, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
619
  gr.Slider(minimum=0, maximum=2**32, value=0, step=1, label="Seed"),
620
  gr.Checkbox(label="Randomize Seed", value=True),
621
- gr.Checkbox(label="FakeTool [Image generation beta]", value=True),
622
  gr.Checkbox(label="FakeTool [Calculator beta]", value=True),
623
  gr.Checkbox(label="FakeTool [Search engine beta (Warning; each query takes up to 30 seconds)]", value=True),
624
  gr.Checkbox(label="Better system prompt (ignores the system prompt set by user.)", value=True),
 
35
  def_models = '["gpt-4", "gpt-4-0125-preview", "gpt-4-0613", "gpt-4-1106-preview", "gpt-4-turbo", "gpt-4-turbo-2024-04-09", "gpt-4-turbo-preview", "chatgpt-4o-latest", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-mini", "gpt-4o-mini-2024-07-18"]'
36
 
37
  vision_models = {"gpt-4-turbo", "chatgpt-4o-latest", "gpt-4o", "gpt-4o-2024-05-13", "gpt-4o-2024-08-06", "gpt-4o-mini", "gpt-4o-mini-2024-07-18"}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  calcPrompt = """[System: You have ability to calculate math problems (formated on python), via tools provided to you by system.
39
  To call a tool you need to write a json in a empty line; like writing it at the end of message.
40
  To use calculator; you need to follow this example JSON:
 
318
  except aiohttp.ClientError:
319
  return
320
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
321
  def searchEngine(query):
322
  ### This /search endpoint is custom made, OpenAI does not have it.
323
  ### If you dupelicate this space, please either try to find another API or make one yourself.
 
399
  top_p,
400
  seed,
401
  random_seed,
 
402
  calcBeta,
403
  searchBeta,
404
  betterSystemPrompt
405
  ):
406
  messages = [];
 
 
407
  if calcBeta:
408
  messages.append({"role": "system", "content": calcPrompt});
409
  if searchBeta:
 
440
  yield "[MODERATION] I'm sorry, but I can't assist with that."
441
  return
442
 
443
+ async def handleResponse(completion, prefix="", didSearchedAlready=False):
444
  response = ""
445
  isRequeryNeeded = False
446
  async for token in completion:
 
461
  for line in response.split('\n'):
462
  try:
463
  data = json.loads(line)
464
+ if isinstance(data, dict) and data.get("tool") == "calc" and data.get("isCall") and "prompt" in data:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
465
  isRequeryNeeded = True
466
  try:
467
  result = safe_eval(data["prompt"])
 
496
  "seed": (random.randint(0, 2**32) if random_seed else seed),
497
  "user": rnd(),
498
  "stream": True
499
+ }), f"{prefix}{response}\n\n", didSearchedAlready):
500
  yield res
501
  async for res in handleResponse(streamChat({
502
  "model": model_name,
 
512
 
513
 
514
  handleApiKeys();loadModels();checkModels();loadENV();
515
+ lastUpdateMessage = "Back online yet again. Removed support for image generation."
516
  demo = gr.ChatInterface(
517
  respond,
518
  title="gpt-4o-mini",
 
526
  gr.Slider(minimum=0.05, maximum=1.0, value=0.95, step=0.05, label="Top-p (nucleus sampling)"),
527
  gr.Slider(minimum=0, maximum=2**32, value=0, step=1, label="Seed"),
528
  gr.Checkbox(label="Randomize Seed", value=True),
 
529
  gr.Checkbox(label="FakeTool [Calculator beta]", value=True),
530
  gr.Checkbox(label="FakeTool [Search engine beta (Warning; each query takes up to 30 seconds)]", value=True),
531
  gr.Checkbox(label="Better system prompt (ignores the system prompt set by user.)", value=True),