Skip to content

Instantly share code, notes, and snippets.

@tuki0918
Created May 26, 2024 19:00
Show Gist options
  • Save tuki0918/b356678a42d3c6a144b3c11c95ac5212 to your computer and use it in GitHub Desktop.
Save tuki0918/b356678a42d3c6a144b3c11c95ac5212 to your computer and use it in GitHub Desktop.
gradio x openai
import dotenv
import os
import openai
import gradio as gr
dotenv.load_dotenv()
openai.api_key = os.getenv("OPENAI_API_KEY")
model = "gpt-3.5-turbo"
# model = "gpt-4-turbo"
# model = "gpt-4o"
def predict(message, history):
history_openai_format = []
for human, assistant in history:
history_openai_format.append({"role": "user", "content": human })
history_openai_format.append({"role": "assistant", "content":assistant})
history_openai_format.append({"role": "user", "content": message})
response = openai.ChatCompletion.create(model=model,
messages= history_openai_format,
temperature=1.0,
stream=True)
partial_message = ""
for chunk in response:
if chunk.choices[0].delta and chunk.choices[0].delta.content is not None:
partial_message = partial_message + chunk.choices[0].delta.content
yield partial_message
gr.ChatInterface(predict).launch()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment