Upload chat.py
Browse files
chat.py
ADDED
|
@@ -0,0 +1,54 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import gradio as gr
|
| 2 |
+
from openai import OpenAI
|
| 3 |
+
|
| 4 |
+
# Point to the local server
|
| 5 |
+
client = OpenAI(base_url="http://localhost:1234/v1", api_key="lm-studio")
|
| 6 |
+
|
| 7 |
+
def chat(message, history):
|
| 8 |
+
"""
|
| 9 |
+
Handles user input and sends it to the model.
|
| 10 |
+
"""
|
| 11 |
+
# Append user message to history immediately
|
| 12 |
+
history.append((message, None))
|
| 13 |
+
|
| 14 |
+
# Format messages for OpenAI API
|
| 15 |
+
messages = [{"role": "system", "content": "Always answer in rhymes."}]
|
| 16 |
+
for user_msg, assistant_msg in history:
|
| 17 |
+
messages.append({"role": "user", "content": user_msg})
|
| 18 |
+
# Only add assistant message if it exists
|
| 19 |
+
if assistant_msg:
|
| 20 |
+
messages.append({"role": "assistant", "content": assistant_msg})
|
| 21 |
+
|
| 22 |
+
# Create chat completion
|
| 23 |
+
completion = client.chat.completions.create(
|
| 24 |
+
model="lmstudio-community/Meta-Llama-3-8B-Instruct-GGUF",
|
| 25 |
+
messages=messages,
|
| 26 |
+
temperature=0.7,
|
| 27 |
+
)
|
| 28 |
+
|
| 29 |
+
# Check if choices is not empty
|
| 30 |
+
if completion.choices:
|
| 31 |
+
response = completion.choices[0].message.content
|
| 32 |
+
# Update the last message in history with the response
|
| 33 |
+
history[-1] = (message, response)
|
| 34 |
+
else:
|
| 35 |
+
response = "No response received from the model."
|
| 36 |
+
# No need to update history here as the message is already added
|
| 37 |
+
|
| 38 |
+
return history, response
|
| 39 |
+
|
| 40 |
+
# Create the Gradio interface using gr.Blocks
|
| 41 |
+
# Create the Gradio interface using gr.Blocks
|
| 42 |
+
with gr.Blocks() as iface:
|
| 43 |
+
chat_history = gr.Chatbot(label="Conversation History")
|
| 44 |
+
message_input = gr.Textbox(label="Your message")
|
| 45 |
+
send_button = gr.Button(value="Send")
|
| 46 |
+
|
| 47 |
+
# Connect components with the chat function within gr.Blocks context
|
| 48 |
+
# outputs から message_input を削除
|
| 49 |
+
send_button.click(
|
| 50 |
+
chat, inputs=[message_input, chat_history], outputs=[chat_history]
|
| 51 |
+
)
|
| 52 |
+
|
| 53 |
+
# Launch the Gradio interface
|
| 54 |
+
iface.launch(share=False)
|