import pydantic from pydantic import BaseModel from typing import Optional class…
- User
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
import pydantic from pydantic import BaseModel from typing import Optional
class ChatMessageItemReq(BaseModel): role: str = pydantic.Field(..., description="角色") content: str = pydantic.Field(..., description="内容") images: Optional[str] = pydantic.Field(default=None, description="图片列表,Base64编码")
class ChatMessageReq(BaseModel): messages: list[ChatMessageItemReq] = pydantic.Field(..., description="消息列表") UPLOAD_DIR = "./uploaded_images"
def save_base64_image(base64_str: str, upload_dir: str = UPLOAD_DIR) -> str: try: # 生成唯一文件名 filename = f"{uuid.uuid4().hex}.png" file_path = os.path.join(upload_dir, filename)
# 解码 Base64 并保存为文件
with open(file_path, "wb") as f:
f.write(base64.b64decode(base64_str))
return file_path
except Exception as e:
raise RuntimeError(f"保存图片失败: {str(e)}")
@router.post("/chat_sse") async def chat_sse( req: ChatMessageReq = Body(), user_id: int = require_perm(PermTypeEnum.PERM_SPAC_CREATE_SPAC.value.code) # 接口权限定义 ) -> StreamingResponse: messages = req if messages is None: return StreamingResponse("messages is None", status_code=400)
# input为最后一个message内容
input = messages.messages[-1].content
logger_helper.get_server_logger().info(f"user_id={user_id} chat,input: {input} .")
images_base64 = input.images
if images_base64:
image_path = save_base64_image(images_base64)
logger_helper.get_server_logger().info(f"用户上传图片已保存: {image_path}")
# 移除最后一个message
messages = messages.messages[:-1]
# 查询RAG
rag_list = rag_service.search_similar_docs(input)
rag_content = ""
# 提取rag list的内容
for item in rag_list:
rag_content += item.page_content + "\n"
logger_helper.get_server_logger().info(f"user_id={user_id} chat,rag content: {rag_content} .")
input = "请根据以下内容生成回复:\n" + rag_content + "\n\n" + input
# 调用chat_service.chat
historyMessage = ChatMessageReq(messages=messages)
return chat_service.chat(input, history=historyMessage)
这是我的后端支持每轮对话附带一张图片。
帮我修改一下前端代码支持每轮对话选择上传一张使用base64编码的图片。
Okay, let's modify your Vue frontend code to support uploading one image per message using Base64 encoding.
Here's the updated <script setup> and <template> section:
<template>
<div class="app-container">
<div class="chat">
<!-- Chat Message Display Area -->
<div class="chat-messages" ref="messagesContainer">
<div v-for="(message, index) in messages" :key="index"
:class="['message', message.role === 'user' ? 'user-message' : 'assistant-message']">
<!-- Display User/Assistant Avatar/Name if needed -->
<!-- Display Text Content -->
<el-text :type="message.role === 'user' ? 'primary' : 'info'">{{ message.content }}</el-text>
<!-- Display User Image if sent -->
<div v-if="message.role === 'user' && message.images" class="message-image">
<!-- Use the full data URL stored for display -->
<el-image
style="max-width: 200px; max-height: 200px; margin-top: 5px;"
:src="message.imageDataUrl"
:preview-src-list="[message.imageDataUrl]"
fit="contain"
lazy
hide-on-click-modal
/>
</div>
</div>
<!-- Loading Skeleton -->
<div v-if="isLoading && !hasBotResponseStarted" class="message assistant-message">
<el-text type="info">
<el-skeleton :rows="1" animated />
</el-text>
</div>
</div>
<!-- Input Area -->
<div class="chat-input-area">
<!-- Image Preview and Clear Button -->
<div v-if="imagePreviewUrl" class="image-preview-container">
<el-image
style="width: 60px; height: 60px; border-radius: 4px;"
:src="imagePreviewUrl"
fit="cover"
/>
<el-button type="danger" icon="el-icon-close" circle size="small" @click="clearSelectedImage" class="clear-image-btn"></el-button>
</div>
<!-- Input Row (Textarea, Upload, Send) -->
<div class="chat-input-row">
<el-input
v-model="userInput"
type="textarea"
:rows="3"
placeholder="输入消息 (Ctrl+Enter 发送)"
@keydown.enter.ctrl.prevent="sendMessage"
class="chat-textarea"
/>
<div class="chat-input-buttons">
<el-button icon="el-icon-picture-outline" @click="triggerImageUpload" title="上传图片"></el-button>
<el-button
type="primary"
@click="sendMessage"
:loading="isLoading"
:disabled="!userInput.trim() && !selectedImageBase64"
icon="el-icon-s-promotion"
>
发送
</el-button>
</div>
</div>
</div>
</div>
<!-- Hidden File Input -->
<input type="file" ref="imageInput" @change="handleImageChange" accept="image/*" style="display: none;" />
</div>
</template>
<script setup>
import { ref, onMounted, nextTick, watch } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus'; // Import ElMessageBox if needed for errors
import { streamChatMessage } from '@/api/sse.js'; // Assuming this path is correct
// Import icons if not globally registered (Element Plus >= 2.7.0)
// import { Upload, Close, Promotion, Picture } from '@element-plus/icons-vue' // Uncomment if needed
const userInput = ref('');
const messages = ref([]); // Stores { role: 'user' | 'assistant', content: string, images?: string (base64 without prefix), imageDataUrl?: string (full data url for display) }
const isLoading = ref(false);
const messagesContainer = ref(null);
const hasBotResponseStarted = ref(false);
const assistantMessage = ref(null); // Holds the reactive assistant message object being built
// Refs for image handling
const imageInput = ref(null); // Ref for the hidden file input element
const selectedImageBase64 = ref(null); // Stores the Base64 string *without* the data: prefix
const imagePreviewUrl = ref(null); // Stores the object URL for preview
// --- Image Handling ---
// Trigger the hidden file input click
const triggerImageUpload = () => {
imageInput.value?.click();
};
// Handle file selection
const handleImageChange = (event) => {
const file = event.target.files?.[0];
if (!file) {
return;
}
// Basic validation (type and size)
if (!file.type.startsWith('image/')) {
ElMessage.error('请选择图片文件');
clearFileInput();
return;
}
const maxSize = 5 * 1024 * 1024; // 5MB limit (adjust as needed)
if (file.size > maxSize) {
ElMessage.error(`图片大小不能超过 ${maxSize / 1024 / 1024}MB`);
clearFileInput();
return;
}
// Generate preview URL
if (imagePreviewUrl.value) {
URL.revokeObjectURL(imagePreviewUrl.value); // Clean up previous preview URL
}
imagePreviewUrl.value = URL.createObjectURL(file);
// Read file as Base64
const reader = new FileReader();
reader.onload = (e) => {
const fullDataUrl = e.target.result;
// Store the base64 part *without* the "data:image/...;base64," prefix for the backend
selectedImageBase64.value = fullDataUrl.split(',')[1];
// Optional: Store the full data URL if needed elsewhere, e.g., for immediate display
// selectedImageDataUrl.value = fullDataUrl;
};
reader.onerror = (error) => {
console.error('Error reading file:', error);
ElMessage.error('读取图片文件失败');
clearSelectedImage(); // Clear preview and data on error
};
reader.readAsDataURL(file);
// Reset file input value so selecting the same file again triggers the change event
clearFileInput();
};
// Clear the selected image preview and data
const clearSelectedImage = () => {
if (imagePreviewUrl.value) {
URL.revokeObjectURL(imagePreviewUrl.value);
}
selectedImageBase64.value = null;
imagePreviewUrl.value = null;
clearFileInput(); // Also clear the file input's value
};
// Helper to reset the file input's value
const clearFileInput = () => {
if (imageInput.value) {
imageInput.value.value = ''; // Reset the input value
}
}
// --- Chat Logic ---
// Scroll to the bottom of the chat messages
const scrollToBottom = async () => {
await nextTick();
if (messagesContainer.value) {
messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
}
};
// Watch messages array changes to scroll down
watch(messages, () => {
scrollToBottom();
}, { deep: true }); // Use deep watch if needed, though length change should suffice
// Send message (text and/or image)
const sendMessage = async () => {
const textInput = userInput.value.trim();
const imageInputBase64 = selectedImageBase64.value;
// Require at least text or an image
if (!textInput && !imageInputBase64) {
ElMessage.warning('请输入消息或选择图片');
return;
}
// 1. Prepare the user message object
const userMessage = {
role: 'user',
content: textInput,
// Include the raw base64 string (no prefix) if an image was selected
images: imageInputBase64,
// Include the full data URL for displaying the image in the chat history
imageDataUrl: imageInputBase64 ? `data:image/png;base64,${imageInputBase64}` : null // Assuming PNG, adjust if needed or get type from file
};
messages.value.push(userMessage);
// 2. Clear input fields after adding message
userInput.value = '';
clearSelectedImage(); // Clear image selection and preview
// 3. Prepare for backend call
isLoading.value = true;
hasBotResponseStarted.value = false;
assistantMessage.value = null; // Reset the assistant message ref
// 4. Construct payload for the backend API
// The backend expects an object with a "messages" key containing the list
const payload = {
messages: messages.value.map(msg => ({ // Ensure only needed fields are sent
role: msg.role,
content: msg.content,
images: msg.images || null // Send null if no image for this message
}))
// messages: [...messages.value] // Send a copy of the current messages array
};
// 5. Call the backend API
try {
await streamChatMessage(payload, { // Pass the payload and callbacks
onMessage: (chunk) => {
if (!assistantMessage.value) {
// First chunk: create the assistant message object
assistantMessage.value = { role: 'assistant', content: chunk };
messages.value.push(assistantMessage.value); // Add to messages array reactively
hasBotResponseStarted.value = true;
} else {
// Subsequent chunks: append to the existing assistant message content
assistantMessage.value.content += chunk;
}
},
onError: (error) => { // Add an onError callback in your streamChatMessage utility
console.error('Streaming Error:', error);
ElMessage.error(error.message || '与服务器连接中断');
// Maybe add a specific error message to the chat?
messages.value.push({ role: 'assistant', content: `错误: ${error.message || '与服务器连接中断'}` });
isLoading.value = false; // Ensure loading stops on stream error
},
onClose: () => { // Add an onClose callback
console.log('Stream closed');
isLoading.value = false;
setTimeout(() => {
hasBotResponseStarted.value = false; // Reset skeleton state after a short delay
}, 100);
}
});
} catch (error) { // Catch errors during the initial request setup
console.error('Error sending message:', error);
ElMessage.error('发送消息失败');
isLoading.value = false;
// Remove the user message if the request fails immediately? Optional.
// messages.value.pop();
}
// 'finally' block is handled by onClose/onError callbacks in the streaming utility now
};
onMounted(() => {
scrollToBottom();
// If using Element Plus Icons dynamically:
// app.component('UploadIcon', Upload) // Register globally or locally
});
</script>
<style scoped>
.app-container {
display: flex;
justify-content: center;
padding: 20px;
height: calc(100vh - 90px); /* Adjust based on your layout */
box-sizing: border-box;
}
.chat {
width: 100%;
max-width: 800px; /* Adjust as needed */
height: 100%;
display: flex;
flex-direction: column;
border: 1px solid #dcdfe6;
border-radius: 8px;
overflow: hidden;
background-color: #fff;
}
.chat-messages {
flex-grow: 1;
overflow-y: auto;
padding: 15px;
background-color: #f9fafb; /* Lighter background for messages */
border-bottom: 1px solid #e4e7ed;
}
.message {
margin-bottom: 15px;
display: flex;
flex-direction: column; /* Stack text and image vertically */
}
.user-message {
align-items: flex-end; /* Align user messages to the right */
}
.user-message .el-text {
background-color: #ecf5ff; /* Light blue background for user */
padding: 8px 12px;
border-radius: 10px 10px 0 10px;
max-width: 70%;
word-wrap: break-word;
}
.user-message .message-image {
margin-top: 5px;
align-self: flex-end; /* Ensure image also aligns right */
}
.assistant-message {
align-items: flex-start; /* Align assistant messages to the left */
}
.assistant-message .el-text {
background-color: #f0f2f5; /* Light grey background for assistant */
padding: 8px 12px;
border-radius: 10px 10px 10px 0;
max-width: 70%;
word-wrap: break-word;
}
.assistant-message .message-image {
margin-top: 5px;
align-self: flex-start; /* Ensure image also aligns left */
}
.el-image {
border-radius: 4px; /* Rounded corners for images */
}
/* Input Area Styling */
.chat-input-area {
padding: 10px 15px;
background-color: #fff;
}
.image-preview-container {
position: relative;
display: inline-block; /* Or block with margin */
margin-bottom: 8px;
border: 1px dashed #dcdfe6;
padding: 3px;
border-radius: 4px;
}
.clear-image-btn {
position: absolute;
top: -8px;
right: -8px;
/* Make it small and subtle */
transform: scale(0.8);
}
/* Make button visible on hover */
/* .image-preview-container:hover .clear-image-btn {
opacity: 1;
} */
.chat-input-row {
display: flex;
align-items: flex-end; /* Align items to bottom */
}
.chat-textarea {
flex-grow: 1;
margin-right: 10px;
}
.chat-textarea .el-textarea__inner {
padding-right: 5px; /* Prevent scrollbar overlapping text */
}
.chat-input-buttons {
display: flex;
flex-direction: column; /* Stack buttons vertically */
gap: 5px; /* Space between buttons */
}
/* Adjust button styles if needed */
.chat-input-buttons .el-button {
margin-left: 0; /* Remove default left margin */
height: 32px; /* Match typical input height */
width: 40px; /* Fixed width for icon button */
padding: 0; /* Reset padding for icon centering */
}
.chat-input-buttons .el-button--primary {
width: auto; /* Let primary button size naturally */
padding: 8px 15px; /* Restore padding for text button */
height: auto;
}
/* Loading Skeleton adjustments */
.assistant-message .el-skeleton {
padding: 8px 12px;
width: 100px; /* Example width */
}
</style>
Key Changes Explained:
HTML (<template>):
<input type="file" ref="imageInput" ...> which is hidden via style="display: none;". It accepts only image files (accept="image/*").el-button with a picture icon (el-icon-picture-outline) next to the send button. Clicking this button triggers triggerImageUpload.div.image-preview-container that appears only when imagePreviewUrl has a value. It shows a small preview (el-image) and a small circular "close" button (el-button) to clear the selection (clearSelectedImage).v-for loop, added a div with v-if="message.role === 'user' && message.images" to display the sent image using el-image. The src is bound to message.imageDataUrl (which we'll store alongside the raw base64).:disabled) if both the text input is empty and no image is selected (!userInput.trim() && !selectedImageBase64).Ctrl+Enter (@keydown.enter.ctrl.prevent="sendMessage") because Enter alone is often used for newlines in textareas.chat-input-row, chat-input-buttons) for better alignment of the textarea and buttons. Buttons are stacked vertically. Added some basic CSS for layout and appearance.JavaScript (<script setup>):
imageInput, selectedImageBase64, and imagePreviewUrl refs to manage the file input element, the raw Base64 string (without prefix), and the preview URL.triggerImageUpload: A simple function to programmatically click the hidden file input.handleImageChange:
File object.URL.createObjectURL for the preview (imagePreviewUrl). Important: These URLs should be revoked when no longer needed to free up memory (done in clearSelectedImage).FileReader to read the file as a dataURL.reader.onload, it extracts only the Base64 part (by splitting at the comma) and stores it in selectedImageBase64. This is what the backend expects.clearFileInput to reset the input element, allowing the user to select the same file again.clearSelectedImage: Revokes the object URL, clears the selectedImageBase64 and imagePreviewUrl refs, and calls clearFileInput.clearFileInput: Helper to reset the <input type="file"> value.sendMessage:
userMessage object, including the content (text) and images (raw Base64 string, or null). It also adds imageDataUrl (the full data: URL) to the message object specifically for rendering the image in the chat history on the frontend.userMessage to the messages array.clearSelectedImage() to reset the image selection state after the message is added locally.payload for the API call. It now sends an object { messages: [...] }, matching the ChatMessageReq Pydantic model. It maps over messages.value to ensure only the role, content, and images fields required by the backend are sent.streamChatMessage with the correct payload structure.onMessage, onError, and onClose callbacks within the streamChatMessage options object for better handling of the streaming lifecycle and errors.messages Array Structure: The comments now clarify that items in messages.value can contain images (raw base64 for backend) and imageDataUrl (full data URL for frontend display).streamChatMessage call now passes { messages: mappedMessages } as the first argument (payload) and the callbacks object as the second. You might need to adjust your sse.js wrapper if it doesn't expect this structure. The backend code req: ChatMessageReq = Body() clearly indicates the entire request body should be the JSON representation of ChatMessageReq, which is {"messages": [...]}.CSS (<style scoped>): Added styles for the image preview, clear button positioning, input area layout, and message/image alignment. Adjust these styles to fit your application's design.
Remember to install Element Plus icons if needed (npm install @element-plus/icons-vue) and potentially register them globally or import them as shown in the script comments. Adjust the API path in @/api/sse.js if necessary.