File size: 2,719 Bytes
e491cd7
2a9e960
 
e491cd7
 
 
 
2961390
e491cd7
 
 
 
 
 
 
2a9e960
 
 
 
 
 
 
e491cd7
 
 
 
 
2a9e960
 
e491cd7
 
 
 
 
 
 
 
 
cc92f7c
 
 
e491cd7
 
 
2a9e960
 
 
e491cd7
 
2961390
2a9e960
224450b
e491cd7
 
2a9e960
 
e491cd7
2a9e960
 
e491cd7
2a9e960
 
 
 
e491cd7
2a9e960
 
 
 
 
2961390
e491cd7
2a9e960
 
2961390
 
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
68
69
70
71
72
73
74
75
76
import time
import gradio as gr
import openai
import os
import requests
import json

# 從環境變數中讀取 OpenAI API 金鑰
api_key = os.getenv('OPENAI_API_KEY')
if not api_key:
    raise ValueError("請設置 'OPENAI_API_KEY' 環境變數")

# OpenAI API key
openai_api_key = api_key

# 將 Gradio 的歷史紀錄轉換為 OpenAI 格式
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

# 回應生成函數,使用 requests 來呼叫 OpenAI API
def response(message, history):
    global conversation_history

    # 將 Gradio 的歷史紀錄轉換為 OpenAI 的格式
    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
    prompt_instruction = """
    你是一名動物園導覽員,只會接觸到動物園遊客。你只能回答有關動物相關的問題,如果不能回答,
    請禮貌地回應遊客。請以專業、熱情、善解人意且非常有禮貌、親切的口氣,與遊客互動並解答問題,且每次回答時,都加入自己的名字’萬獸獅丸說:

    """
    prompt_to_gpt = prompt_instruction + message

    # 新增至 conversation_history
    conversation_history.append({"role": "system", "content": prompt_to_gpt})

    # 設置請求的數據
    data = {
        "model": "gpt-3.5-turbo",  # 使用的模型是 gpt-4 或 gpt-3.5-turbo
        "messages": conversation_history,
        "max_tokens": 500  # 控制生成的最大令牌數
    }

    # 發送請求到 OpenAI API
    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)  # 每個字符間隔 0.05 秒
            yield model_response[: i+1]
    else:
        yield "抱歉,我無法取得回應。"

# 建立 Gradio 聊天界面
gr.ChatInterface(response,
                 title='動物園導覽員',
                 textbox=gr.Textbox(placeholder="請輸入您的問題")).launch(share=True)