|
import time |
|
import gradio as gr |
|
import openai |
|
import os |
|
import requests |
|
import json |
|
|
|
|
|
api_key = os.getenv('OPENAI_API_KEY') |
|
if not api_key: |
|
raise ValueError("請設置 'OPENAI_API_KEY' 環境變數") |
|
|
|
|
|
openai_api_key = api_key |
|
|
|
|
|
def transform_history(history): |
|
new_history = [] |
|
for chat in history: |
|
new_history.append({"role": "user", "content": chat[0]}) |
|
new_history.append({"role": "assistant", "content": chat[1]}) |
|
return new_history |
|
|
|
|
|
def response(message, history): |
|
global conversation_history |
|
|
|
|
|
conversation_history = transform_history(history) |
|
|
|
url = "https://api.openai.com/v1/chat/completions" |
|
headers = { |
|
"Content-Type": "application/json", |
|
"Authorization": f"Bearer {openai_api_key}" |
|
} |
|
|
|
|
|
prompt_instruction = """ |
|
你是一位知名的眼科醫師,名字叫"林醫師", 正在為病人做遠距諮詢服務,要以專業、親切的的口氣與病人互動並解答問題,請病人用3句話苗市自己的症狀並且根據病人的描述給予建議: |
|
""" |
|
prompt_to_gpt = prompt_instruction + message |
|
|
|
|
|
conversation_history.append({"role": "system", "content": prompt_to_gpt}) |
|
|
|
|
|
data = { |
|
"model": "gpt-4o", |
|
"messages": conversation_history, |
|
"max_tokens": 500 |
|
} |
|
|
|
|
|
response = requests.post(url, headers=headers, data=json.dumps(data)) |
|
|
|
|
|
response_json = response.json() |
|
|
|
|
|
if 'choices' in response_json and len(response_json['choices']) > 0: |
|
model_response = response_json['choices'][0]['message']['content'] |
|
conversation_history.append({"role": "assistant", "content": model_response}) |
|
|
|
|
|
for i in range(len(model_response)): |
|
time.sleep(0.05) |
|
yield model_response[: i+1] |
|
else: |
|
yield "Error: No response from the model." |
|
|
|
|
|
gr.ChatInterface(response, |
|
title='OpenAI Chat', |
|
textbox=gr.Textbox(placeholder="Question to OpenAI")).launch(share=True) |
|
|