Spaces:
Runtime error

File size: 3,210 Bytes
2c68e5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
import os  
import gradio as gr  
from langchain import OpenAI, LLMChain  
from langchain.prompts import PromptTemplate  
from langchain.memory import ConversationBufferMemory  
from langchain.chat_models import ChatOpenAI  

# 确保安装了 python-dotenv 以加载 .env 文件中的环境变量  
from dotenv import load_dotenv  

load_dotenv()  

# 获取 OpenAI API Key  
openai_api_key = os.getenv("OPENAI_API_KEY")  
if not openai_api_key:  
    raise ValueError("未找到 OPENAI_API_KEY 环境变量。请确保已正确设置。")  

# 配置 LangChain 的 ChatOpenAI  
llm = ChatOpenAI(  
    openai_api_key=openai_api_key,  
    model_name="gpt-3.5-turbo",  # 您也可以选择其他模型,比如 "gpt-4"  
    temperature=0.7,  
    max_tokens=150  
)  

# 定义提示模板  
prompt_template = """  
你是一个乐于助人的 AI 助手。请根据以下对话内容进行回复:  

{history}  
用户: {input}  

AI:  
"""  

# 创建提示模板对象  
prompt = PromptTemplate(  
    input_variables=["history", "input"],  
    template=prompt_template  
)  

# 创建记忆模块  
memory = ConversationBufferMemory(  
    memory_key="history",  
    return_messages=True  
)  

# 创建 LLMChain  
chain = LLMChain(  
    llm=llm,  
    prompt=prompt,  
    memory=memory  
)  

def generate_response(input_text):  
    """  
    使用 LangChain 生成 AI 回复。  

    Args:  
        input_text (str): 用户输入的消息  

    Returns:  
        str: AI 生成的回复  
    """  
    response = chain.run(input_text)  
    return response  

def reset_chat():  
    """  
    重置聊天记录。  

    Returns:  
        str: 重置后的聊天记录  
    """  
    memory.clear()  
    return ""  

# 使用 Gradio Blocks 构建界面  
with gr.Blocks() as demo:  
    gr.Markdown("# LangChain + Gradio GPT 聊天机器人")  
    gr.Markdown("这是一个示例,使用了 LangChain 的模板和记忆模块。")  
    
    # 聊天组件  
    chatbot = gr.Chatbot()  
    
    # 用户输入框  
    user_input = gr.Textbox(  
        show_label=False,  
        placeholder="输入你的问题并按回车...",  
        lines=1  
    )  
    
    # 按钮  
    send_button = gr.Button("发送")  
    reset_button = gr.Button("重置聊天")  
    
    # 记录对话历史  
    def respond(message, chat_history):  
        """  
        处理用户输入并生成回复。  

        Args:  
            message (str): 用户输入  
            chat_history (list): 当前聊天记录  

        Returns:  
            list: 更新后的聊天记录  
        """  
        if message:  
            # 生成 AI 回复  
            ai_reply = generate_response(message)  
            # 更新聊天记录  
            chat_history.append((message, ai_reply))  
        return chat_history  

    # 监听发送按钮和回车事件  
    send_button.click(respond, inputs=[user_input, chatbot], outputs=chatbot)  
    user_input.submit(respond, inputs=[user_input, chatbot], outputs=chatbot)  
    
    # 重置聊天按钮  
    reset_button.click(reset_chat, outputs=chatbot)  

# 启动 Gradio 界面  
if __name__ == "__main__":  
    demo.launch()