Spaces:
Sleeping
Sleeping
File size: 1,754 Bytes
3691aa7 9680c0d 3691aa7 9680c0d 3691aa7 9680c0d 3691aa7 9680c0d 3691aa7 9680c0d 3691aa7 9680c0d 3691aa7 9680c0d 3691aa7 9680c0d 3691aa7 9680c0d 3691aa7 9680c0d 3691aa7 9680c0d 3691aa7 9680c0d |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 |
import gradio as gr
from openai import OpenAI
def respond(
message,
history: list[dict[str, str]],
system_message,
max_tokens,
temperature,
top_p,
openai_api_key,
):
"""
Chat with OpenAI GPT-3.5-turbo-instruct, streaming word by word.
"""
if not openai_api_key:
yield "⚠️ Please provide a valid OpenAI API key."
return
client = OpenAI(api_key=openai_api_key)
messages = [{"role": "system", "content": system_message}]
messages.extend(history)
messages.append({"role": "user", "content": message})
response = ""
stream = client.completions.create(
model="gpt-3.5-turbo-instruct",
prompt="\n".join([f"{m['role']}: {m['content']}" for m in messages]),
max_tokens=max_tokens,
temperature=temperature,
top_p=top_p,
stream=True,
)
for event in stream:
if hasattr(event, "choices") and event.choices:
chunk = event.choices[0].text or ""
response += chunk
yield response
chatbot = gr.ChatInterface(
respond,
type="messages",
additional_inputs=[
gr.Textbox(value="You are a helpful assistant.", label="System message"),
gr.Slider(minimum=1, maximum=1024, value=256, step=1, label="Max new tokens"),
gr.Slider(minimum=0.0, maximum=2.0, value=0.7, step=0.1, label="Temperature"),
gr.Slider(minimum=0.1, maximum=1.0, value=1.0, step=0.05, label="Top-p"),
gr.Textbox(
placeholder="sk-... paste your OpenAI API key here",
label="🔑 OpenAI API Key",
type="password",
),
],
)
with gr.Blocks() as demo:
chatbot.render()
if __name__ == "__main__":
demo.launch()
|