# Please update your assistant id and api key here: API_KEY = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJEVkNBU1NJIiwic3ViIjoiQlVJTFRJTkFETUlOIiwiYXVkIjpbIkRWQ0FTU0kiXSwiaWF0IjoxNzMxNDg3NTM1LCJqdGkiOiJjYzAwMWEwZS0yNWEwLTQzYmMtOGIxYi1mM2I4ZjJkNDQxY2IifQ.Ye45WBKwIS1PIHZ0dyEJ4AFtVL_1wIfPpfpi7vPuNOs" ASSISTANT_ID = "asst_dvc_r1iHNC1t7pRZzlrT7G983GsW" ASSISTANT_API = "https://prod.dvcbot.net/api/assts/v1" import micropip; await micropip.install('openai==1.39.0'); from pyodide.http import pyfetch; import httpx; import gradio as gr from openai import AsyncOpenAI from datetime import datetime import json class Transport(httpx.AsyncBaseTransport): async def handle_async_request(self, request: httpx.Request): resp = await pyfetch(str(request.url), method=request.method, headers=dict(request.headers.items()), body=json.dumps(json.loads(request.content), ensure_ascii=False).encode() if request.method != 'GET' and request.method != 'DELETE' else None) return httpx.Response(resp.status, headers=resp.headers, stream=httpx.ByteStream(await resp.bytes())) client = AsyncOpenAI(base_url=ASSISTANT_API, api_key=API_KEY, http_client=httpx.AsyncClient(transport=Transport())) if __name__ == "__main__": async def send_message(message, history): thread = await client.beta.threads.create(messages=[{"role": "user" if i == 0 else "assistant", "content": c} for p in history for i, c in enumerate(p)]) await client.beta.threads.messages.create(thread_id=thread.id, role='user', content=message) run = await client.beta.threads.runs.create_and_poll(thread_id=thread.id, assistant_id=ASSISTANT_ID, additional_instructions=f"\nThe current time is: {datetime.now()}", timeout=2.0) while run.status == 'requires_action' and run.required_action: outputs = [] for call in run.required_action.submit_tool_outputs.tool_calls: resp = await client._client.post(ASSISTANT_API+'/pluginapi', params={"tid": thread.id, "aid": ASSISTANT_ID, "pid": call.function.name}, headers={"Authorization": "Bearer " + API_KEY}, json=json.loads(call.function.arguments)) outputs.append({"tool_call_id": call.id, "output": resp.text[:8000]}) run = await client.beta.threads.runs.submit_tool_outputs_and_poll(run_id=run.id, thread_id=thread.id, tool_outputs=outputs, timeout=2.0) if run.status == 'failed' and run.last_error: return run.last_error.model_dump_json() msgs = await client.beta.threads.messages.list(thread_id=thread.id, order='desc') await client.beta.threads.delete(thread_id=thread.id) return msgs.data[0].content[0].text.value demo = gr.ChatInterface(send_message) demo.launch()