3a197f3333
- Added functionality for image uploads in chat, allowing users to attach images for multimodal Q&A. - Enhanced the input field to handle image selection via drag-and-drop and paste, with validation for file types and sizes. - Updated the backend to process images alongside text queries, including support for image analysis. - Introduced new UI components for image previews and management, improving user interaction with uploaded content. - Added localization strings for image upload features and error messages, enhancing accessibility for users in multiple languages. These changes significantly improve the chat experience by enabling users to incorporate images into their queries, facilitating richer interactions and responses.
191 lines
6.8 KiB
TypeScript
191 lines
6.8 KiB
TypeScript
import { fetchEventSource } from '@microsoft/fetch-event-source'
|
|
import { ref, type Ref, onUnmounted, nextTick } from 'vue'
|
|
import { generateRandomString } from '@/utils/index';
|
|
import i18n from '@/i18n';
|
|
|
|
|
|
|
|
interface StreamOptions {
|
|
// 请求方法 (默认POST)
|
|
method?: 'GET' | 'POST'
|
|
// 请求头
|
|
headers?: Record<string, string>
|
|
// 请求体自动序列化
|
|
body?: Record<string, any>
|
|
// 流式渲染间隔 (ms)
|
|
chunkInterval?: number
|
|
}
|
|
|
|
export function useStream() {
|
|
// 响应式状态
|
|
const output = ref('') // 显示内容
|
|
const isStreaming = ref(false) // 流状态
|
|
const isLoading = ref(false) // 初始加载
|
|
const error = ref<string | null>(null)// 错误信息
|
|
let controller = new AbortController()
|
|
|
|
// 流式渲染缓冲
|
|
let buffer: string[] = []
|
|
let renderTimer: number | null = null
|
|
|
|
// 启动流式请求
|
|
const startStream = async (params: { session_id: any; query: any; knowledge_base_ids?: string[]; knowledge_ids?: string[]; agent_enabled?: boolean; agent_id?: string; web_search_enabled?: boolean; enable_memory?: boolean; summary_model_id?: string; mcp_service_ids?: string[]; mentioned_items?: Array<{id: string; name: string; type: string; kb_type?: string}>; images?: Array<{data: string}>; method: string; url: string }) => {
|
|
// 重置状态
|
|
output.value = '';
|
|
error.value = null;
|
|
isStreaming.value = true;
|
|
isLoading.value = true;
|
|
|
|
// 获取API配置
|
|
const apiUrl = import.meta.env.VITE_IS_DOCKER ? "" : "http://localhost:8080";
|
|
|
|
// 获取JWT Token
|
|
const token = localStorage.getItem('weknora_token');
|
|
if (!token) {
|
|
error.value = i18n.global.t('error.tokenNotFound');
|
|
stopStream();
|
|
return;
|
|
}
|
|
|
|
// 获取跨租户访问请求头
|
|
const selectedTenantId = localStorage.getItem('weknora_selected_tenant_id');
|
|
const defaultTenantId = localStorage.getItem('weknora_tenant');
|
|
let tenantIdHeader: string | null = null;
|
|
if (selectedTenantId) {
|
|
try {
|
|
const defaultTenant = defaultTenantId ? JSON.parse(defaultTenantId) : null;
|
|
const defaultId = defaultTenant?.id ? String(defaultTenant.id) : null;
|
|
if (selectedTenantId !== defaultId) {
|
|
tenantIdHeader = selectedTenantId;
|
|
}
|
|
} catch (e) {
|
|
console.error('Failed to parse tenant info', e);
|
|
}
|
|
}
|
|
|
|
// Validate knowledge_base_ids for agent-chat requests
|
|
// Note: knowledge_base_ids can be empty if user hasn't selected any, but we allow it
|
|
// The backend will handle the case when no knowledge bases are selected
|
|
const isAgentChat = params.url === '/api/v1/agent-chat';
|
|
// Removed validation - allow empty knowledge_base_ids array
|
|
// The backend should handle this case appropriately
|
|
|
|
try {
|
|
let url =
|
|
params.method == "POST"
|
|
? `${apiUrl}${params.url}/${params.session_id}`
|
|
: `${apiUrl}${params.url}/${params.session_id}?message_id=${params.query}`;
|
|
|
|
// Prepare POST body with required fields for agent-chat
|
|
// knowledge_base_ids array and agent_enabled can update Session's SessionAgentConfig
|
|
const postBody: any = {
|
|
query: params.query,
|
|
agent_enabled: params.agent_enabled !== undefined ? params.agent_enabled : true
|
|
};
|
|
// Always include knowledge_base_ids for agent-chat (already validated above)
|
|
if (params.knowledge_base_ids !== undefined && params.knowledge_base_ids.length > 0) {
|
|
postBody.knowledge_base_ids = params.knowledge_base_ids;
|
|
}
|
|
// Include knowledge_ids if provided
|
|
if (params.knowledge_ids !== undefined && params.knowledge_ids.length > 0) {
|
|
postBody.knowledge_ids = params.knowledge_ids;
|
|
}
|
|
// Include agent_id if provided (backend resolves shared agent and tenant from share relation)
|
|
if (params.agent_id) {
|
|
postBody.agent_id = params.agent_id;
|
|
}
|
|
// Include web_search_enabled if provided
|
|
if (params.web_search_enabled !== undefined) {
|
|
postBody.web_search_enabled = params.web_search_enabled;
|
|
}
|
|
// Include enable_memory if provided
|
|
if (params.enable_memory !== undefined) {
|
|
postBody.enable_memory = params.enable_memory;
|
|
}
|
|
// Include summary_model_id if provided (for non-Agent mode)
|
|
if (params.summary_model_id) {
|
|
postBody.summary_model_id = params.summary_model_id;
|
|
}
|
|
// Include mcp_service_ids if provided (for Agent mode)
|
|
if (params.mcp_service_ids !== undefined && params.mcp_service_ids.length > 0) {
|
|
postBody.mcp_service_ids = params.mcp_service_ids;
|
|
}
|
|
// Include mentioned_items if provided (for displaying @mentions in chat)
|
|
if (params.mentioned_items !== undefined && params.mentioned_items.length > 0) {
|
|
postBody.mentioned_items = params.mentioned_items;
|
|
}
|
|
// Include images if provided (base64 data URIs for multimodal chat)
|
|
if (params.images !== undefined && params.images.length > 0) {
|
|
postBody.images = params.images;
|
|
}
|
|
|
|
await fetchEventSource(url, {
|
|
method: params.method,
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
"Authorization": `Bearer ${token}`,
|
|
"X-Request-ID": `${generateRandomString(12)}`,
|
|
...(tenantIdHeader ? { "X-Tenant-ID": tenantIdHeader } : {}),
|
|
},
|
|
body:
|
|
params.method == "POST"
|
|
? JSON.stringify(postBody)
|
|
: null,
|
|
signal: controller.signal,
|
|
openWhenHidden: true,
|
|
|
|
onopen: async (res) => {
|
|
if (!res.ok) throw new Error(`HTTP ${res.status}`);
|
|
isLoading.value = false;
|
|
},
|
|
|
|
onmessage: (ev) => {
|
|
buffer.push(JSON.parse(ev.data)); // 数据存入缓冲
|
|
// 执行自定义处理
|
|
if (chunkHandler) {
|
|
chunkHandler(JSON.parse(ev.data));
|
|
}
|
|
},
|
|
|
|
onerror: (err) => {
|
|
throw new Error(`${i18n.global.t('error.streamFailed')}: ${err}`);
|
|
},
|
|
|
|
onclose: () => {
|
|
stopStream();
|
|
},
|
|
});
|
|
} catch (err) {
|
|
error.value = err instanceof Error ? err.message : String(err)
|
|
stopStream()
|
|
}
|
|
}
|
|
|
|
let chunkHandler: ((data: any) => void) | null = null
|
|
// 注册块处理器
|
|
const onChunk = (handler: () => void) => {
|
|
chunkHandler = handler
|
|
}
|
|
|
|
|
|
// 停止流
|
|
const stopStream = () => {
|
|
controller.abort();
|
|
controller = new AbortController(); // 重置控制器(如需重新发起)
|
|
isStreaming.value = false;
|
|
isLoading.value = false;
|
|
}
|
|
|
|
// 组件卸载时自动清理
|
|
onUnmounted(stopStream)
|
|
|
|
return {
|
|
output, // 显示内容
|
|
isStreaming, // 是否在流式传输中
|
|
isLoading, // 初始连接状态
|
|
error,
|
|
onChunk,
|
|
startStream, // 启动流
|
|
stopStream // 手动停止
|
|
}
|
|
} |