Spaces:
Sleeping
Sleeping
Create app.py
Browse files
app.py
ADDED
@@ -0,0 +1,147 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from openai import AsyncAssistantEventHandler
|
2 |
+
from openai import AsyncOpenAI
|
3 |
+
import gradio as gr
|
4 |
+
import asyncio
|
5 |
+
import os
|
6 |
+
|
7 |
+
# set the keys
|
8 |
+
client = AsyncOpenAI(
|
9 |
+
api_key=os.getenv("OPENAI_API_KEY")
|
10 |
+
)
|
11 |
+
|
12 |
+
assistantID = os.getenv("OPENAI_ASSISTANT_ID")
|
13 |
+
username = os.getenv("YOUR_ID")
|
14 |
+
password = os.getenv("YOUR_PASSWORD")
|
15 |
+
|
16 |
+
mytitle = "<h1 align=center>RTL AI News Reader : Qu'est-ce qui s'est passé dans le pays 🇱🇺 et dans le monde 🌎 ?</h1>"
|
17 |
+
|
18 |
+
mydescription="""
|
19 |
+
<h3 align='center'>Quel sujet vous intéresse : 🐶 🏃🏻♂️ 🌗 🍇 🌈 🍽️ 🏆 🚘 ✈️ 🩺 </h3>
|
20 |
+
<table width=100%>
|
21 |
+
<tr>
|
22 |
+
<th width=50% bgcolor="Moccasin">Posez vos questions en français ou dans une autre langue :</th>
|
23 |
+
<th bgcolor="Khaki">Réponse de l'Assistant file-search OpenAI :</th>
|
24 |
+
</tr>
|
25 |
+
</table>
|
26 |
+
"""
|
27 |
+
|
28 |
+
myarticle ="""
|
29 |
+
<h3>Contexte :</h3>
|
30 |
+
<p>Cette démo de HuggingFace Space a été réalisée par <a href="https://github.com/mbarnig">Marco Barnig</a>.
|
31 |
+
En tant qu'intelligence artificielle, le <a href="https://platform.openai.com/docs/models">modèle OpenAI</a> gpt-4o-mini-2024-07-18 est utilisé via une API,
|
32 |
+
qui peut utiliser jusqu'à 128 000 tokens comme contexte, fournir une réponse d'un maximum de 16 384 tokens à une question,
|
33 |
+
et traiter jusqu'à 200 000 tokens par minute (TPM).
|
34 |
+
L'ensemble du contenu français de RTL.lu depuis le début 2013 jusqu'en septembre 2024 a été découpé en 25 fichiers JSON
|
35 |
+
et chargé dans un Vector Store de l'Assistant file-search d'OpenAI "RTL French News Reader".
|
36 |
+
Chaque fichier contient moins de 5 millions de tokens, ce qui est une limite supérieure pour le modèle d'IA.
|
37 |
+
Il est possible de charger jusqu'à 10 000 fichiers sur un Assistant OpenAI. Les réponses des exemples sont mises en cache et donc affichées sans délai.</p>
|
38 |
+
"""
|
39 |
+
|
40 |
+
myinput = gr.Textbox(lines=3, label="Que voulez-vous savoir ?")
|
41 |
+
|
42 |
+
myexamples = [
|
43 |
+
"Qui est Schlimé ?",
|
44 |
+
"Quel est le plus ancien message dans la base de données locale ?",
|
45 |
+
"Quels étaient les événements qui ont marqué l'année 2017 ?"
|
46 |
+
]
|
47 |
+
|
48 |
+
class EventHandler(AsyncAssistantEventHandler):
|
49 |
+
def __init__(self) -> None:
|
50 |
+
super().__init__()
|
51 |
+
self.response_text = ""
|
52 |
+
|
53 |
+
async def on_text_created(self, text) -> None:
|
54 |
+
self.response_text += str(text)
|
55 |
+
|
56 |
+
async def on_text_delta(self, delta, snapshot):
|
57 |
+
self.response_text += str(delta.value)
|
58 |
+
|
59 |
+
async def on_text_done(self, text):
|
60 |
+
pass
|
61 |
+
|
62 |
+
async def on_tool_call_created(self, tool_call):
|
63 |
+
self.response_text += f"\n[Tool Call]: {str(tool_call.type)}\n"
|
64 |
+
|
65 |
+
async def on_tool_call_delta(self, delta, snapshot):
|
66 |
+
if snapshot.id != getattr(self, "current_tool_call", None):
|
67 |
+
self.current_tool_call = snapshot.id
|
68 |
+
self.response_text += f"\n[Tool Call Delta]: {str(delta.type)}\n"
|
69 |
+
|
70 |
+
if delta.type == 'code_interpreter':
|
71 |
+
if delta.code_interpreter.input:
|
72 |
+
self.response_text += str(delta.code_interpreter.input)
|
73 |
+
if delta.code_interpreter.outputs:
|
74 |
+
self.response_text += "\n\n[Output]:\n"
|
75 |
+
for output in delta.code_interpreter.outputs:
|
76 |
+
if output.type == "logs":
|
77 |
+
self.response_text += f"\n{str(output.logs)}"
|
78 |
+
|
79 |
+
async def on_tool_call_done(self, text):
|
80 |
+
pass
|
81 |
+
|
82 |
+
# Initialize session variables
|
83 |
+
session_data = {"assistant_id": assistantID, "thread_id": None}
|
84 |
+
|
85 |
+
async def initialize_thread():
|
86 |
+
# Create a Thread
|
87 |
+
thread = await client.beta.threads.create()
|
88 |
+
# Store thread ID in session_data for later use
|
89 |
+
session_data["thread_id"] = thread.id
|
90 |
+
|
91 |
+
async def generate_response(user_input):
|
92 |
+
assistant_id = session_data["assistant_id"]
|
93 |
+
thread_id = session_data["thread_id"]
|
94 |
+
|
95 |
+
# Add a Message to the Thread
|
96 |
+
oai_message = await client.beta.threads.messages.create(
|
97 |
+
thread_id=thread_id,
|
98 |
+
role="user",
|
99 |
+
content=user_input
|
100 |
+
)
|
101 |
+
|
102 |
+
# Create and Stream a Run
|
103 |
+
event_handler = EventHandler()
|
104 |
+
|
105 |
+
async with client.beta.threads.runs.stream(
|
106 |
+
thread_id=thread_id,
|
107 |
+
assistant_id=assistant_id,
|
108 |
+
instructions="Please assist the user with their query.",
|
109 |
+
event_handler=event_handler,
|
110 |
+
) as stream:
|
111 |
+
# Yield incremental updates
|
112 |
+
async for _ in stream:
|
113 |
+
await asyncio.sleep(0.1) # Small delay to mimic streaming
|
114 |
+
yield event_handler.response_text
|
115 |
+
|
116 |
+
# Gradio interface function (generator)
|
117 |
+
async def gradio_chat_interface(user_input):
|
118 |
+
# Create a new event loop if none exists (or if we are in a new thread)
|
119 |
+
try:
|
120 |
+
loop = asyncio.get_running_loop()
|
121 |
+
except RuntimeError:
|
122 |
+
loop = asyncio.new_event_loop()
|
123 |
+
asyncio.set_event_loop(loop)
|
124 |
+
|
125 |
+
# Initialize the thread if not already done
|
126 |
+
if session_data["thread_id"] is None:
|
127 |
+
await initialize_thread()
|
128 |
+
|
129 |
+
# Generate and yield responses
|
130 |
+
async for response in generate_response(user_input):
|
131 |
+
yield response
|
132 |
+
|
133 |
+
# Set up Gradio interface with streaming
|
134 |
+
interface = gr.Interface(
|
135 |
+
fn=gradio_chat_interface,
|
136 |
+
inputs=myinput,
|
137 |
+
outputs="markdown",
|
138 |
+
title=mytitle,
|
139 |
+
description=mydescription,
|
140 |
+
article=myarticle,
|
141 |
+
live=False,
|
142 |
+
allow_flagging="never",
|
143 |
+
examples=myexamples
|
144 |
+
)
|
145 |
+
|
146 |
+
# Launch the Gradio app
|
147 |
+
interface.launch(auth=(username, password), auth_message="<h1>Lecteur de nouvelles IA de RTL</h1><p>Ce HuggingFace Space est un prototype et n'est pas encore accessible à tout le monde. Le projet est basé sur un assistant de recherche de fichiers via l'API d'OpenAI et utilise le modèle GPT-4o-mini. Vous devez utiliser un navigateur Chrome. Les spécialistes en IA intéressés peuvent demander un identifiant et un mot de passe en contactant [email protected].</p>")
|