|
|
import gradio as gr |
|
|
import openai |
|
|
from prisma import Prisma |
|
|
from prisma.models import public_users as Public_Users, Assistants, Chats, Messages |
|
|
import asyncio |
|
|
|
|
|
|
|
|
prisma = Prisma() |
|
|
|
|
|
async def chat_with_atlas(api_key, assistant_id, user_message): |
|
|
if not api_key or not assistant_id: |
|
|
return "Please provide both an API key and an Assistant ID." |
|
|
|
|
|
|
|
|
if not prisma.is_connected(): |
|
|
await prisma.connect() |
|
|
|
|
|
|
|
|
user: Public_Users = await prisma.public_users.find_unique(where={'apiKey': api_key}) |
|
|
if not user: |
|
|
return "Invalid API key" |
|
|
|
|
|
assistant_settings: Assistants = await prisma.assistants.find_unique(where={'id': assistant_id}) |
|
|
if not assistant_settings: |
|
|
return "Assistant not found" |
|
|
|
|
|
|
|
|
openai.api_key = user.openai_api_key |
|
|
openai_assistant_id = assistant_settings.openai_assistant_id |
|
|
if not openai_assistant_id: |
|
|
return "OpenAI Assistant ID not found for this assistant" |
|
|
|
|
|
|
|
|
assistant = openai.Assistant.create( |
|
|
name="Atlas Assistant", |
|
|
instructions="You are a personal website assistant. You answer user questions.", |
|
|
tools=[{"type": "code_interpreter"}], |
|
|
model=assistant_settings.model or "gpt-4-1106-preview" |
|
|
) |
|
|
|
|
|
|
|
|
thread = openai.Thread.create() |
|
|
|
|
|
|
|
|
message = openai.Message.create( |
|
|
thread_id=thread.id, |
|
|
role="user", |
|
|
content=user_message |
|
|
) |
|
|
|
|
|
|
|
|
run = openai.Run.create( |
|
|
thread_id=thread.id, |
|
|
assistant_id=assistant.id |
|
|
) |
|
|
|
|
|
|
|
|
run_status = openai.Run.retrieve( |
|
|
thread_id=thread.id, |
|
|
run_id=run.id |
|
|
) |
|
|
while run_status['status'] != 'completed': |
|
|
|
|
|
run_status = openai.Run.retrieve( |
|
|
thread_id=thread.id, |
|
|
run_id=run.id |
|
|
) |
|
|
|
|
|
|
|
|
messages = openai.Message.list( |
|
|
thread_id=thread.id |
|
|
) |
|
|
|
|
|
|
|
|
response_content = next( |
|
|
(msg['content'] for msg in messages['data'] if msg['role'] == 'assistant'), |
|
|
"No response from the assistant." |
|
|
).strip() |
|
|
|
|
|
return response_content |
|
|
|
|
|
iface = gr.Interface( |
|
|
fn=chat_with_atlas, |
|
|
inputs=["text", "text", "text"], |
|
|
outputs="text", |
|
|
live=True |
|
|
) |
|
|
iface.launch() |