Commit Graph

56 Commits

Author SHA1 Message Date
wizardchen 492e92580b feat(observability): integrate Langfuse for LLM token tracking and tracing
Closes #620 #497. Add opt-in Langfuse observability covering all five
model types (chat, embedding, rerank, VLM, ASR) with HTTP-request-scoped
traces and Docker Compose support (both cloud and self-hosted).

Core package internal/tracing/langfuse:
- HTTP client with batched async ingestion (non-blocking in request path)
- Sampling, environment / release tagging, and graceful fallback when
  LANGFUSE_* env vars are absent (wrappers become no-ops)
- Gin middleware opens one trace per traced request and finishes it after
  the handler chain returns, attaching method / path / user / session
- Trace context is stored under a typed key exported from internal/types
  so logger.CloneContext can preserve it across handler / goroutine
  boundaries (otherwise each LLM call auto-created an orphan trace,
  fragmenting one request into many)

Per-model generation wrappers (opt-in via NewChat/NewEmbedder/...):
- chat: captures prompt, streaming output, token usage + TTFT
- embedding: approximates tokens when the provider omits usage
- rerank: previews query/docs, summarizes results to keep payload small
- vlm: records image count and total bytes, never uploads raw pixels
- asr: records file size and audio duration, never uploads audio bytes

Async title generation (GenerateTitleAsync) now forwards the trace key
into the goroutine so title calls appear under the parent chat trace.

Docker Compose:
- LANGFUSE_* env passthrough on the `app` service for cloud deployments
- Optional `langfuse` profile spins up a self-hosted Langfuse stack that
  reuses WeKnora's existing PostgreSQL (separate database via an idempotent
  init container that fixes ICU collation drift) and Redis (separate DB
  number), adding only ClickHouse, MinIO, web and worker containers
- web/worker entrypoints URL-encode DB_PASSWORD / REDIS_PASSWORD at start
  to avoid Prisma P1013 when passwords contain @ / # / etc.

Docs: docs/Langfuse集成.md covers cloud vs self-hosted, per-model usage
strategy, code map, and resource footprint.
2026-04-24 10:29:19 +08:00
wizardchen fd3e2992b1 feat(models): support custom HTTP headers across all remote model calls
Introduce per-model `custom_headers` config (similar to OpenAI Python SDK's
`extra_headers`) so users can inject gateway auth tokens, trace IDs, etc.
into every outbound API request for chat / embedding / rerank / VLLM / ASR
models. Reserved headers like Authorization / Content-Type are always
preserved to avoid breaking auth or signing flows.

Along the way, unify production and "test connection" paths onto a single
`ConfigFromModel(*types.Model, appID, appSecret)` constructor in each
model package. Both `service.modelService.GetXxxModel` and the four
`handler.initialization.Check*Model` / `TestEmbeddingModel` endpoints now
go through the same field mapping, so new parameters only need to be
added in one place.

Backend:
- Add `CustomHeaders map[string]string` to `types.ModelParameters` with
  JSON/YAML `omitempty` tags for forward compatibility.
- New `internal/utils/extraheaders.go` providing `ApplyCustomHeaders`
  (for hand-rolled HTTP paths) and `WrapHTTPClientWithHeaders` /
  `CustomHeadersRoundTripper` (for SDK paths like go-openai). Reserved
  headers (Authorization, api-key, Content-Type, Accept, Host,
  Content-Length, User-Agent) are filtered out.
- Inject headers in every remote model path: chat (SDK + raw HTTP),
  embedding (openai/aliyun/jina/volcengine/nvidia/azure_openai), rerank
  (remote_api/aliyun/jina/nvidia/zhipu — via shared `customHeaderSetter`
  interface), VLM and ASR (via http.Client wrapping).
- Add `ConfigFromModel` to each of chat/embedding/rerank/vlm/asr,
  consolidating field mapping (ExtraConfig, CustomHeaders, InterfaceType
  defaulting, WeKnoraCloud credentials, etc.) and cover it with
  dedicated unit tests per package.
- Refactor `service/model.go`: replace ~100 lines of hand-written Config
  literals with one-line `ConfigFromModel` calls; drop the now-unused
  `stringMapToAnyMap` helper.
- Refactor `handler/initialization.go` test-connection endpoints: merge
  four ad-hoc request structs into one `ModelTestRequest`, extract
  `buildTestModel` and `resolveTenantWeKnoraCloudCreds` helpers, and
  route all four endpoints through `ConfigFromModel` + `NewXxx` so the
  test path is now behaviorally identical to production.

Frontend:
- Add `custom_headers` to the `ModelConfig` API type.
- `ModelEditorDialog.vue`: new Key-Value header editor (add/remove rows),
  auto-converts map <-> array when loading/saving, and passes the
  current header set to the `Test Connection` button so the preview
  reflects exactly what production will send.
- `ModelSettings.vue`: serialize the header array back into a map for
  the backend (drops empty rows).
- i18n: add custom-header labels / descriptions / placeholders to
  zh-CN, en-US, ru-RU, ko-KR.

Tests:
- `internal/utils/extraheaders_test.go` covers reserved-header filtering
  and round-tripper wrapping (including nil-client fallback).
- New `config_from_model_test.go` in chat / embedding / rerank / vlm /
  asr verifies all fields (CustomHeaders, ExtraConfig, InterfaceType
  defaulting, AppID/AppSecret) are propagated end-to-end.
2026-04-23 23:36:40 +08:00
wizardchen 1ec43b328d refactor: Simplify WeKnoraCloud request customization and message conversion
- Removed redundant struct definitions for WeKnoraCloud requests and messages, streamlining the customization process.
- Updated the weKnoraCloudRequestCustomizer function to directly modify the request object, enhancing clarity and reducing complexity.
- Improved the convertToWeKnoraCloudMessagesFromOpenAI function to maintain the original message structure while ensuring compatibility with WeKnoraCloud requirements.
2026-04-23 17:52:43 +08:00
wizardchen 9f916181db refactor: Simplify logging in RemoteAPIChat HTTP requests
- Removed header printing from the chatWithRawHTTP method to streamline logging.
- Updated log message to focus on endpoint and model name, enhancing clarity while reducing verbosity.
2026-04-23 11:22:44 +08:00
wizardchen a81ef5fbb2 fix: improve tenant access token logging and update test cases
- Enhanced the logging of the tenant access token in the Feishu client to handle variable lengths for prefix and suffix, ensuring accurate display even for shorter tokens.
- Updated the test cases in `connector_test.go` to reflect changes in the endpoint path for file downloads, improving test reliability.
- Adjusted example outputs in `example_test.go` for clarity and consistency.
- Modified image resolution tests to correct expected outcomes based on updated criteria for icon images.
- Added environment variable settings in image resolver tests to ensure localhost accessibility during testing.

These changes enhance the robustness of logging and testing mechanisms across the application.
2026-04-22 21:17:30 +08:00
moineye 4ca0c7a644 fix: ReadEvent incompatible sse data format 2026-04-20 22:29:38 +08:00
wizardchen 53e8e17df4 feat(logger): implement LLM debug logging functionality
- Added a new logger for LLM calls, enabling detailed logging of model interactions, including request and response data.
- Introduced configuration options for enabling and specifying the log directory for LLM debug logs.
- Implemented cleanup for old log files to manage disk space effectively.
- Wrapped existing chat implementations to log calls when debug logging is enabled, enhancing traceability for model interactions.
2026-04-16 23:15:02 +08:00
wizardchen 0eff63b308 feat(weknoracloud): implement credential management and status checks
- Introduced a new WeKnoraCloudSettings component for managing APPID and APPSECRET.
- Added functionality to save WeKnoraCloud credentials without automatically creating models.
- Implemented credential status checks across various components to provide user feedback on configuration status.
- Updated API endpoints to handle credential saving and status retrieval.
- Enhanced UI elements to guide users in configuring WeKnoraCloud settings.

This update improves the integration of WeKnoraCloud by allowing users to manage their credentials more effectively and receive real-time feedback on their configuration status.
2026-04-14 17:36:01 +08:00
begoniezhao 2c0c1b8bab feat: integrate ChatBot provider and docreader 2026-04-13 17:47:24 +08:00
liweixin bf514ff68a test: harden remote api chat fixture for SSRF validation 2026-04-09 19:19:25 +08:00
liweixin c6215405a5 fix: override AzureModelMapperFunc to preserve deployment name as-is 2026-04-09 19:19:25 +08:00
liweixin 22ec575727 feat: add Azure OpenAI support for chat models 2026-04-09 19:19:25 +08:00
AndyYang f63c9f6dbe fix: resolve tool name duplication in streaming tool calls 2026-04-05 18:25:45 +08:00
nullkey d68c94a11a fix(stream): use io.EOF instead of errors.New("EOF") in SSEReader
errors.New("EOF") creates a distinct error instance that doesn't match
io.EOF, causing processRawHTTPStream to silently ignore normal stream
termination without sending a done response.

- SSEReader: return io.EOF instead of errors.New("EOF")
- processRawHTTPStream: handle io.EOF as normal completion, send done
  response with usage/toolCalls (aligned with processStream behavior)

Fixes #860
2026-04-02 18:35:53 +08:00
wizardchen 4dd481560d refactor(chat): simplify temperature option handling in chat request builders
- Streamlined the handling of the temperature option in both OllamaChat and RemoteAPIChat by removing unnecessary conditional checks.
- Ensured that the temperature value is directly assigned when options are provided, improving code clarity and reducing complexity.
2026-03-31 12:19:22 +08:00
Manx98 1baabb6c05 feat: support system proxy for remote API 2026-03-30 10:46:19 +08:00
AndyYang 930a953f41 feat: fix enable_thinking for Aliyun Qwen models in streaming mode 2026-03-30 10:42:31 +08:00
Manx98 2a3cc92b99 refactor: use unified NVIDIA API for both chat and VLM 2026-03-30 10:38:50 +08:00
ochan.kwon 380f5d9405 fix(agent): prevent empty response when no Knowledge Base is configured
- guard against empty content completion in analyzeResponse/executeLoop
  with retry (max 2), nudge message, and fallback response
- propagate actual finish_reason through streaming pipeline instead of
  hardcoding "stop" in streamThinkingToEventBus
- add FinishReason field to StreamResponse and streamLLMResult
- add finish marker chunk in processStreamDelta for empty content scenarios
- propagate lastFinishReason through EOF handler in processStream
- strengthen PureAgent system prompt with MCP tool guidelines and
  graceful fallback instructions for unanswerable questions
- add unit tests for empty response bug and finish_reason propagation
2026-03-27 14:56:12 +08:00
wizardchen 72dfb9ce75 feat(prompt): enhance context and intent classification in templates
- Updated context template to include runtime metadata such as current time and week, improving contextual awareness in user queries.
- Enhanced rewrite template with critical instructions for intent classification, ensuring that rewritten questions preserve essential entities and keywords.
- Refined intent classification logic to prioritize user intents more effectively, improving the accuracy of responses based on user queries.
- Added examples to clarify expected input and output formats for intent classification, enhancing usability for developers.
2026-03-26 18:57:12 +08:00
wizardchen fd5278d62d feat(security): enhance SSRF protection in RemoteAPIChat
- Replaced the default DialContext with SSRFSafeDialContext in the raw HTTP client to improve security against DNS rebinding attacks.
- Added SSRF validation for BaseURL and endpoint in NewRemoteAPIChat and chat methods, ensuring safer URL handling.
- Updated security utility functions to provide consistent SSRF checks across the application.
2026-03-26 11:37:07 +08:00
wizardchen de0169d7c0 feat(chat): add ParallelToolCalls option to ChatOptions and update related functionality
- Introduced a new ParallelToolCalls field in ChatOptions to control parallel execution of tool calls.
- Updated the BuildChatCompletionRequest method to handle the new ParallelToolCalls option, ensuring it is correctly propagated in requests.
- Enhanced the streamThinkingToEventBus function to utilize the ParallelToolCalls setting.
- Added comprehensive tests to validate the behavior of ParallelToolCalls in various scenarios, ensuring correct propagation and default handling.
2026-03-25 22:08:29 +08:00
wizardchen 2b56c4fbac feat(agent): enhance streaming diagnostics and event tracking
- Added diagnostics for streaming events in the AgentEngine, including chunk counts and response type distributions.
- Implemented logging for emitted event types during the thinking process to aid in debugging and performance analysis.
- Updated the session handler to provide more informative warnings when fallback answers are emitted due to non-streaming behavior.
- Introduced a dedicated HTTP client for Ollama to improve connection handling and timeout management during streaming calls.
2026-03-25 22:08:29 +08:00
wizardchen e7c21c0733 feat(chat): add Volcengine support and refactor thinking configuration
- Introduced Volcengine as a new provider in the chat provider specifications.
- Refactored the thinking configuration to a more generic format, applicable to both LKEAP and Volcengine.
- Updated request customizers to handle the new thinking configuration structure for both LKEAP and Volcengine providers.
2026-03-25 22:08:29 +08:00
wizardchen 0bb1a581de feat(agent): enhance token management and context handling in AgentEngine
- Added token usage tracking to the AgentEngine, allowing for better estimation of current context token counts.
- Implemented a new method to estimate current tokens based on previous usage and newly appended messages, improving context management.
- Updated context window management to utilize estimated token counts for more efficient message consolidation.
- Enhanced streaming methods to include token usage information, providing better insights into LLM interactions.
- Refactored the token estimator to support BPE tokenization, ensuring accurate token counts for messages.
- Added unit tests to validate new token estimation and context management functionalities.
2026-03-25 22:08:29 +08:00
wizardchen 9f4fb39e10 feat(chat): introduce provider-specific request customizers and specs
- Added a new `ProviderSpec` struct to define provider-specific behaviors for chat completions.
- Implemented request and endpoint customizers for various providers including Qwen3, LKEAP, DeepSeek, and Generic.
- Refactored the `NewRemoteChat` function to utilize the new provider specs for customizing requests based on the provider and model name.
- Removed legacy chat implementations for LKEAP, NVIDIA, DeepSeek, and Qwen, consolidating their logic into the new structure.
2026-03-25 22:08:29 +08:00
wizardchen e936e0b347 feat(agent): implement LLM call timeout and transient error handling
- Introduced a configurable LLM call timeout with a default value, allowing for better control over LLM call durations.
- Added logic to retry transient errors (e.g., timeouts, rate limits) up to a specified maximum number of retries, improving robustness in error handling.
- Implemented parameter casting for tool arguments to ensure correct types are used, addressing common LLM quirks.
- Enhanced tool execution error messages with guidance for retrying with different approaches.
- Added validation for configuration values to prevent runtime errors.
2026-03-25 22:08:29 +08:00
lyingbug e5c46642e9 fix: handle thinking stream edge cases (unclosed tags + missing done)
Two related fixes for thinking mode streaming:

1. chat_completion_stream.go: When the response channel closes
   unexpectedly (context cancelled, upstream error) while thinking
   is in progress, the <think> tag was left unclosed. This caused
   the stored message to have an incomplete tag, making the frontend
   show a perpetual "thinking..." state on history reload.
   Now we emit a closing </think> tag when the channel ends with
   thinkingStarted=true but thinkingEnded=false.

2. remote_api.go: The thinking Done=true event was only sent when
   the first answer content chunk arrived. If the model produced
   only reasoning with no answer (e.g., finish_reason set with
   empty content), the thinking-done signal was never emitted.
   Now we also check isDone && state.hasThinking at the end of
   processStreamDelta to ensure the done event is always sent.
2026-03-25 22:08:29 +08:00
Andy Yang 62e6ae960f fix(chat): support reasoning content in streaming responses for vLLM models
- Parse reasoning field together with standard stream response using local struct
- Unify reasoning content extraction from standard and vLLM response paths
- Adapt processStreamDelta to accept reasoning content as a separate parameter
- Send reasoning content as thinking response in the stream when available
- Ensure compatibility with existing SDK logic by constructing standard choice object
2026-03-24 11:56:55 +08:00
wizardchen 160672ea9c feat: enhance message structure to support multi-content messages
- Introduced MessageContentPart and ImageURL types to allow for multi-content messages that can include both text and images.
- Updated the Message struct to include a MultiContent field for handling multiple message parts.
- Modified the ConvertMessages function to prioritize processing of multi-content messages, improving the handling of user messages with images.

These changes enhance the flexibility and functionality of chat messages, enabling richer content delivery.
2026-03-16 17:33:50 +08:00
wizardchen 6a7eb420a9 refactor: update conversation handling and image description requirements
- Removed outdated instructions regarding the `skip_kb_search` field in the conversation configuration.
- Clarified requirements for `image_description` to ensure it is non-empty when images are present.
- Adjusted the handling of message parts in the chat pipeline to improve image processing.
- Deleted unused migration files related to image handling in the database schema.

These changes enhance the clarity and functionality of the conversation and image processing logic.
2026-03-16 15:15:24 +08:00
wizardchen 5fe1ccd4f9 feat: enhance multimodal support and image handling
- Updated configuration to improve handling of multimodal queries, including clearer guidelines for when to use [NO_SEARCH] in responses.
- Enhanced the user interface to include dedicated sections for multimodal configuration, allowing users to manage image uploads and related settings more effectively.
- Added localization support for new multimodal features in both English and Chinese, improving accessibility for a broader audience.
- Implemented backend changes to support image analysis and extraction of OCR text, enriching the interaction experience for users.

These enhancements significantly improve the application's capability to process and respond to multimodal queries, fostering a more interactive and user-friendly environment.
2026-03-16 02:26:47 +08:00
wizardchen 991bd29a14 feat: implement image upload and multimodal support
- 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.
2026-03-16 02:26:47 +08:00
Manx98 a355ac889e feat: NVIDIA chat model API support custom endpoint 2026-03-13 18:14:08 +08:00
wizardchen a4b255a456 feat: implement final_answer tool and enhance agent duration tracking
- Introduced the final_answer tool to ensure agents submit their complete responses as the last action, improving response accuracy and consistency.
- Updated the agent engine to log detailed information about tool calls and responses, including the total duration of agent execution.
- Enhanced the chat message model to include agent_duration_ms, tracking the total execution time from query start to answer delivery.
- Implemented JSON field extraction for streaming responses, allowing for more efficient handling of tool call outputs.

These changes significantly improve the agent's response handling and ensure that final answers are consistently delivered, enhancing overall user experience.
2026-03-09 11:46:56 +08:00
xiaoen b536e86cd0 fix: handle thinking content in Ollama chat responses
Ollama API returns reasoning model output in Message.Thinking field,
but OllamaChat only reads Message.Content. Add thinking content
handling for both streaming and non-streaming, consistent with
RemoteAPIChat behavior.
2026-02-25 11:11:24 +08:00
MEKXH c2cdc16712 fix(chat): strip thinking content from model output
Handle thinking models that return wrapped content even when
Thinking=false is configured. This is a fallback strategy for models
like MiniMax-M2.1 that do not fully support the Thinking parameter.
The thinking tags and their enclosed content are completely stripped.
2026-02-04 19:35:55 +08:00
wizardchen aa4af5365e feat: add thinking mode support for agents 2026-01-20 18:19:44 +08:00
joeyczheng b1633c836a fix: concurrent map writes due to dig.Container is not thread safe
Signed-off-by: joeyczheng <joeyczheng@tencent.com>
2026-01-15 20:07:11 +08:00
wizardchen 884153aeb8 feat: 增强模型选择和错误处理机制
优化模型ID传递逻辑,支持请求级别的模型覆盖;完善流式响应的错误处理
2025-12-31 15:36:20 +08:00
begoniezhao 907e9a5522 feat: Add DataSchema tool for retrieving schema information from CSV and Excel files 2025-12-29 20:03:51 +08:00
JAESOL SHIN ddf5ae4e65 fix(chat): exclude ChatTemplateKwargs for OpenAI API
ChatTemplateKwargs parameter is only supported by custom backends
like vLLM. OpenAI API does not support this parameter and returns
400 Bad Request error.

This change conditionally includes ChatTemplateKwargs only when
the provider is ProviderGeneric (custom deployment).

Fixes connection test failure for OpenAI models with error:
"Unrecognized request argument supplied: chat_template_kwargs"
2025-12-29 19:08:15 +08:00
wizardchen c9a6c3134a Merge branch 'custom_agent' 2025-12-29 17:01:23 +08:00
nullkey e9a2a7b3e5 feat: 新增对多家平台的模型适配 2025-12-29 12:18:42 +08:00
wizardchen 6bc19ab082 feat: 统一系统提示词并优化智能体选择器界面
- 将系统提示词从分离的网络搜索开/关状态合并为统一提示词,使用 {{web_search_status}} 占位符动态控制行为
- 重构智能体选择器,从简单tooltip升级为内容丰富的popup,显示智能体详细信息、类型和能力
- 新增FAQ优先策略配置,支持FAQ答案优先于普通文档
- 优化知识库选择逻辑,智能体切换时自动同步配置的知识库
- 更新相关接口类型定义和国际化文本
2025-12-28 21:46:42 +08:00
wizardchen d0c5c4f6b0 feat: 新增智能体功能模块,支持自定义智能体创建、配置和选择 2025-12-24 10:34:41 +08:00
wizardchen eb8bfddfd1 refactor: Update function signatures across multiple files to improve readability by adding context parameters and enhancing code structure 2025-11-28 16:17:52 +08:00
wizardchen 135e33eca4 refactor: Clean up code by removing unnecessary blank lines and improving comments for better readability and maintainability 2025-11-28 16:10:37 +08:00
wizardchen 2f45bf7d86 refactor: Improve Elasticsearch query construction and error handling 2025-11-25 22:06:43 +08:00
wizardchen 057cfd9eb0 feat: Enhance FAQ import functionality and UI improvements
- Added support for tracking the status of FAQ import tasks, including progress indicators for ongoing imports.
- Introduced new localization strings for processing tasks and batch operations in multiple languages.
- Updated the FAQ entry manager to display import progress and improved user feedback during the import process.
- Enhanced the KnowledgeBase component to reflect the processing state of knowledge items, improving user experience during document uploads.
- Implemented batch deletion functionality for chunks, streamlining the management of knowledge base content.
2025-11-23 17:32:50 +08:00