feat: Add agent configuration and cleanup scripts for database migrations

This commit is contained in:
wizardchen
2025-11-05 23:18:44 +08:00
parent ae9d0778e9
commit 4fa3adbf3b
126 changed files with 22506 additions and 629 deletions
+198 -17
View File
@@ -8,6 +8,7 @@ import (
"net/http"
"strings"
"github.com/Tencent/WeKnora/internal/logger"
"github.com/Tencent/WeKnora/internal/types"
"github.com/sashabaranov/go-openai"
)
@@ -45,12 +46,40 @@ func NewRemoteAPIChat(chatConfig *ChatConfig) (*RemoteAPIChat, error) {
// convertMessages 转换消息格式为OpenAI格式
func (c *RemoteAPIChat) convertMessages(messages []Message) []openai.ChatCompletionMessage {
openaiMessages := make([]openai.ChatCompletionMessage, len(messages))
for i, msg := range messages {
openaiMessages[i] = openai.ChatCompletionMessage{
Role: msg.Role,
Content: msg.Content,
openaiMessages := make([]openai.ChatCompletionMessage, 0, len(messages))
for _, msg := range messages {
openaiMsg := openai.ChatCompletionMessage{
Role: msg.Role,
}
// 处理内容:对于 assistant 角色,内容可能为空(当有 tool_calls 时)
if msg.Content != "" {
openaiMsg.Content = msg.Content
}
// 处理 tool calls(assistant 角色)
if len(msg.ToolCalls) > 0 {
openaiMsg.ToolCalls = make([]openai.ToolCall, 0, len(msg.ToolCalls))
for _, tc := range msg.ToolCalls {
toolType := openai.ToolType(tc.Type)
openaiMsg.ToolCalls = append(openaiMsg.ToolCalls, openai.ToolCall{
ID: tc.ID,
Type: toolType,
Function: openai.FunctionCall{
Name: tc.Function.Name,
Arguments: tc.Function.Arguments,
},
})
}
}
// 处理 tool 角色消息(工具返回结果)
if msg.Role == "tool" {
openaiMsg.ToolCallID = msg.ToolCallID
openaiMsg.Name = msg.Name
}
openaiMessages = append(openaiMessages, openaiMsg)
}
return openaiMessages
}
@@ -60,6 +89,11 @@ func (c *RemoteAPIChat) isAliyunQwen3Model() bool {
return strings.HasPrefix(c.modelName, "qwen3-") && c.baseURL == "https://dashscope.aliyuncs.com/compatible-mode/v1"
}
// isDeepSeekModel 检查是否为 DeepSeek 模型
func (c *RemoteAPIChat) isDeepSeekModel() bool {
return strings.Contains(strings.ToLower(c.modelName), "deepseek")
}
// buildQwenChatCompletionRequest 构建 qwen 模型的聊天请求参数
func (c *RemoteAPIChat) buildQwenChatCompletionRequest(messages []Message,
opts *ChatOptions, isStream bool,
@@ -110,12 +144,68 @@ func (c *RemoteAPIChat) buildChatCompletionRequest(messages []Message,
if opts.Thinking != nil {
thinking = *opts.Thinking
}
// 处理 Tools(函数定义)
if len(opts.Tools) > 0 {
req.Tools = make([]openai.Tool, 0, len(opts.Tools))
for _, tool := range opts.Tools {
toolType := openai.ToolType(tool.Type)
openaiTool := openai.Tool{
Type: toolType,
Function: &openai.FunctionDefinition{
Name: tool.Function.Name,
Description: tool.Function.Description,
},
}
// 转换 Parameters (map[string]interface{} -> JSON Schema)
if tool.Function.Parameters != nil {
// Parameters 已经是 JSON Schema 格式的 map,直接使用
openaiTool.Function.Parameters = tool.Function.Parameters
}
req.Tools = append(req.Tools, openaiTool)
}
}
// 处理 ToolChoice
// ToolChoice 可以是字符串或 ToolChoice 对象
// 对于 "auto", "none", "required" 直接使用字符串
// 对于特定工具名称,使用 ToolChoice 对象
// 注意:某些模型(如 DeepSeek)不支持 tool_choice,需要跳过设置
if opts.ToolChoice != "" {
// DeepSeek 模型不支持 tool_choice,跳过设置(默认行为会自动使用工具)
if c.isDeepSeekModel() {
// 对于 DeepSeek,不设置 tool_choice,让 API 使用默认行为
// 如果有 tools,DeepSeek 会自动使用
logger.Infof(context.Background(), "deepseek model, skip tool_choice")
} else {
switch opts.ToolChoice {
case "none", "required", "auto":
// 直接使用字符串
req.ToolChoice = opts.ToolChoice
default:
// 特定工具名称,使用 ToolChoice 对象
req.ToolChoice = openai.ToolChoice{
Type: "function",
Function: openai.ToolFunction{
Name: opts.ToolChoice,
},
}
}
}
}
}
req.ChatTemplateKwargs = map[string]interface{}{
"enable_thinking": thinking,
}
// print req
jsonData, err := json.Marshal(req)
if err != nil {
logger.Error(context.Background(), "marshal request: %w", err)
}
logger.Infof(context.Background(), "llm request: %s", string(jsonData))
return req
}
@@ -139,9 +229,10 @@ func (c *RemoteAPIChat) Chat(ctx context.Context, messages []Message, opts *Chat
return nil, fmt.Errorf("no response from OpenAI")
}
// 转换响应格式
return &types.ChatResponse{
Content: resp.Choices[0].Message.Content,
choice := resp.Choices[0]
response := &types.ChatResponse{
Content: choice.Message.Content,
FinishReason: string(choice.FinishReason),
Usage: struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
@@ -151,7 +242,24 @@ func (c *RemoteAPIChat) Chat(ctx context.Context, messages []Message, opts *Chat
CompletionTokens: resp.Usage.CompletionTokens,
TotalTokens: resp.Usage.TotalTokens,
},
}, nil
}
// 转换 Tool Calls
if len(choice.Message.ToolCalls) > 0 {
response.ToolCalls = make([]types.LLMToolCall, 0, len(choice.Message.ToolCalls))
for _, tc := range choice.Message.ToolCalls {
response.ToolCalls = append(response.ToolCalls, types.LLMToolCall{
ID: tc.ID,
Type: string(tc.Type),
Function: types.FunctionCall{
Name: tc.Function.Name,
Arguments: tc.Function.Arguments,
},
})
}
}
return response, nil
}
// chatWithQwen 使用自定义请求处理 qwen 模型
@@ -201,9 +309,10 @@ func (c *RemoteAPIChat) chatWithQwen(ctx context.Context, messages []Message, op
return nil, fmt.Errorf("no response from API")
}
// 转换响应格式
return &types.ChatResponse{
Content: chatResp.Choices[0].Message.Content,
choice := chatResp.Choices[0]
response := &types.ChatResponse{
Content: choice.Message.Content,
FinishReason: string(choice.FinishReason),
Usage: struct {
PromptTokens int `json:"prompt_tokens"`
CompletionTokens int `json:"completion_tokens"`
@@ -213,7 +322,24 @@ func (c *RemoteAPIChat) chatWithQwen(ctx context.Context, messages []Message, op
CompletionTokens: chatResp.Usage.CompletionTokens,
TotalTokens: chatResp.Usage.TotalTokens,
},
}, nil
}
// 转换 Tool Calls
if len(choice.Message.ToolCalls) > 0 {
response.ToolCalls = make([]types.LLMToolCall, 0, len(choice.Message.ToolCalls))
for _, tc := range choice.Message.ToolCalls {
response.ToolCalls = append(response.ToolCalls, types.LLMToolCall{
ID: tc.ID,
Type: string(tc.Type),
Function: types.FunctionCall{
Name: tc.Function.Name,
Arguments: tc.Function.Arguments,
},
})
}
}
return response, nil
}
// ChatStream 进行流式聊天
@@ -238,20 +364,75 @@ func (c *RemoteAPIChat) ChatStream(ctx context.Context,
defer close(streamChan)
defer stream.Close()
var collectedToolCalls []types.LLMToolCall
for {
response, err := stream.Recv()
if err != nil {
// 发送最后一个响应,包含收集到的 tool calls
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Content: "",
Done: true,
ToolCalls: collectedToolCalls,
}
return
}
if len(response.Choices) > 0 {
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Content: response.Choices[0].Delta.Content,
Done: false,
delta := response.Choices[0].Delta
isDone := string(response.Choices[0].FinishReason) != ""
// 收集 tool calls(流式响应中 tool calls 可能分多次返回)
if len(delta.ToolCalls) > 0 {
for _, tc := range delta.ToolCalls {
// 检查是否已经存在该 tool call(通过 index)
var toolCallIndex int
if tc.Index != nil {
toolCallIndex = *tc.Index
}
if toolCallIndex >= len(collectedToolCalls) {
// 新建 tool call
collectedToolCalls = append(collectedToolCalls, types.LLMToolCall{
ID: tc.ID,
Type: string(tc.Type),
Function: types.FunctionCall{
Name: tc.Function.Name,
Arguments: tc.Function.Arguments,
},
})
} else {
// 追加参数到已有的 tool call
collectedToolCalls[toolCallIndex].Function.Arguments += tc.Function.Arguments
// 更新 ID 和名称(如果提供了)
if tc.ID != "" {
collectedToolCalls[toolCallIndex].ID = tc.ID
}
if tc.Function.Name != "" {
collectedToolCalls[toolCallIndex].Function.Name = tc.Function.Name
}
}
}
}
// 发送内容块
if delta.Content != "" {
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Content: delta.Content,
Done: isDone,
ToolCalls: collectedToolCalls,
}
}
// 如果是最后一次响应,确保发送包含所有 tool calls 的响应
if isDone && len(collectedToolCalls) > 0 {
streamChan <- types.StreamResponse{
ResponseType: types.ResponseTypeAnswer,
Content: "",
Done: true,
ToolCalls: collectedToolCalls,
}
}
}
}