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 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190
| import uuid import gradio as gr from sqlalchemy import create_engine from langchain_core.messages import HumanMessage from langchain_core.prompts import ChatPromptTemplate, MessagesPlaceholder from langchain_core.runnables import RunnableWithMessageHistory from langchain_community.chat_message_histories import SQLChatMessageHistory
from my_llm import multiModal_llm from utils import image_to_base64, audio_to_base64
prompt = ChatPromptTemplate.from_messages([ ("system", "你是一个多模态AI助手,可以处理文本、图片和语音输入。请用中文友好地回答用户的问题。"), MessagesPlaceholder(variable_name="messages"), ("system", "当前对话历史:"), MessagesPlaceholder(variable_name="history"), ])
chain = prompt | multiModal_llm
def get_session_history(session_id: str): """获取或创建会话历史""" engine = create_engine('sqlite:///chat_history.db') return SQLChatMessageHistory( session_id=session_id, connection=engine, table_name="chat_history" )
chain_with_history = RunnableWithMessageHistory( chain, get_session_history, input_messages_key="messages", history_messages_key="history" )
session_id = str(uuid.uuid4())
def process_inputs(text: str, audio: str, image: str, chat_history: list): """处理用户输入并生成响应""" content = [] user_display = [] if image: img_data = image_to_base64(image) if img_data: content.append(img_data) user_display.append("[图片]") if audio: audio_data = audio_to_base64(audio) if audio_data: content.append(audio_data) user_display.append("[语音]") if text and text.strip(): content.append({"type": "text", "text": text}) user_display.append(text) if not content: chat_history.append(("", "请输入文本、上传图片或录制语音!")) return "", None, None, chat_history user_message = HumanMessage(content=content) display_text = " ".join(user_display) if user_display else "[多媒体内容]" try: response = chain_with_history.invoke( {"messages": [user_message]}, config={"configurable": {"session_id": session_id}} ) chat_history.append((display_text, response.content)) except Exception as e: error_msg = f"请求失败: {str(e)}" print(f"[ERROR] {error_msg}") chat_history.append((display_text, error_msg)) return "", None, None, chat_history
def create_interface(): """创建Gradio界面""" with gr.Blocks( title="多模态聊天机器人", theme=gr.themes.Soft(), css=""" .chatbot { min-height: 500px; } .input-row { margin-top: 20px; } """ ) as demo: gr.Markdown(""" # 🤖 多模态聊天机器人 支持**文字**、**图片**、**语音**输入 | 具备上下文记忆 """) chatbot = gr.Chatbot( label="对话历史", height=500, bubble_full_width=False, show_copy_button=True ) with gr.Row(variant="panel", elem_classes="input-row"): text_input = gr.Textbox( placeholder="输入文字消息...", label="文本输入", scale=4, container=False ) submit_btn = gr.Button("发送", variant="primary", scale=1) with gr.Row(): audio_input = gr.Audio( sources=["microphone"], type="filepath", label="语音输入", interactive=True ) image_input = gr.Image( type="filepath", label="图片上传", sources=["upload"], interactive=True ) submit_btn.click( fn=process_inputs, inputs=[text_input, audio_input, image_input, chatbot], outputs=[text_input, audio_input, image_input, chatbot], queue=True ) text_input.submit( fn=process_inputs, inputs=[text_input, audio_input, image_input, chatbot], outputs=[text_input, audio_input, image_input, chatbot], queue=True ) with gr.Row(): clear_btn = gr.Button("清空对话", variant="secondary") clear_btn.click( fn=lambda: ([], "", None, None), outputs=[chatbot, text_input, audio_input, image_input], queue=False ) return demo
if __name__ == "__main__": demo = create_interface() demo.queue( max_size=20, default_concurrency_limit=5 ) demo.launch( server_name="0.0.0.0", server_port=7860, share=False, show_error=True, debug=True )
|