feat: Add agent configuration and cleanup scripts for database migrations
This commit is contained in:
@@ -10,6 +10,19 @@ import (
|
||||
"github.com/Tencent/WeKnora/internal/types"
|
||||
)
|
||||
|
||||
// Tool represents a function/tool definition
|
||||
type Tool struct {
|
||||
Type string `json:"type"` // "function"
|
||||
Function FunctionDef `json:"function"`
|
||||
}
|
||||
|
||||
// FunctionDef represents a function definition
|
||||
type FunctionDef struct {
|
||||
Name string `json:"name"`
|
||||
Description string `json:"description"`
|
||||
Parameters map[string]interface{} `json:"parameters"`
|
||||
}
|
||||
|
||||
// ChatOptions 聊天选项
|
||||
type ChatOptions struct {
|
||||
Temperature float64 `json:"temperature"` // 温度参数
|
||||
@@ -20,12 +33,30 @@ type ChatOptions struct {
|
||||
FrequencyPenalty float64 `json:"frequency_penalty"` // 频率惩罚
|
||||
PresencePenalty float64 `json:"presence_penalty"` // 存在惩罚
|
||||
Thinking *bool `json:"thinking"` // 是否启用思考
|
||||
Tools []Tool `json:"tools,omitempty"` // 可用工具列表
|
||||
ToolChoice string `json:"tool_choice,omitempty"` // "auto", "required", "none", or specific tool
|
||||
}
|
||||
|
||||
// Message 表示聊天消息
|
||||
type Message struct {
|
||||
Role string `json:"role"` // 角色:system, user, assistant
|
||||
Content string `json:"content"` // 消息内容
|
||||
Role string `json:"role"` // 角色:system, user, assistant, tool
|
||||
Content string `json:"content"` // 消息内容
|
||||
Name string `json:"name,omitempty"` // Function/tool name (for tool role)
|
||||
ToolCallID string `json:"tool_call_id,omitempty"` // Tool call ID (for tool role)
|
||||
ToolCalls []ToolCall `json:"tool_calls,omitempty"` // Tool calls (for assistant role)
|
||||
}
|
||||
|
||||
// ToolCall represents a tool call in a message
|
||||
type ToolCall struct {
|
||||
ID string `json:"id"`
|
||||
Type string `json:"type"` // "function"
|
||||
Function FunctionCall `json:"function"`
|
||||
}
|
||||
|
||||
// FunctionCall represents a function call
|
||||
type FunctionCall struct {
|
||||
Name string `json:"name"`
|
||||
Arguments string `json:"arguments"` // JSON string
|
||||
}
|
||||
|
||||
// Chat 定义了聊天接口
|
||||
|
||||
@@ -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,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"os"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/Tencent/WeKnora/internal/logger"
|
||||
"github.com/ollama/ollama/api"
|
||||
@@ -243,7 +244,15 @@ func (s *OllamaService) GetModelInfo(ctx context.Context, modelName string) (*ap
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// ListModels lists all available models
|
||||
// OllamaModelInfo represents detailed information about an Ollama model
|
||||
type OllamaModelInfo struct {
|
||||
Name string `json:"name"`
|
||||
Size int64 `json:"size"`
|
||||
Digest string `json:"digest"`
|
||||
ModifiedAt time.Time `json:"modified_at"`
|
||||
}
|
||||
|
||||
// ListModels lists all available models with basic info (names only)
|
||||
func (s *OllamaService) ListModels(ctx context.Context) ([]string, error) {
|
||||
listResp, err := s.client.List(ctx)
|
||||
if err != nil {
|
||||
@@ -258,6 +267,26 @@ func (s *OllamaService) ListModels(ctx context.Context) ([]string, error) {
|
||||
return modelNames, nil
|
||||
}
|
||||
|
||||
// ListModelsDetailed lists all available models with detailed information
|
||||
func (s *OllamaService) ListModelsDetailed(ctx context.Context) ([]OllamaModelInfo, error) {
|
||||
listResp, err := s.client.List(ctx)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to get model list: %w", err)
|
||||
}
|
||||
|
||||
models := make([]OllamaModelInfo, len(listResp.Models))
|
||||
for i, model := range listResp.Models {
|
||||
models[i] = OllamaModelInfo{
|
||||
Name: model.Name,
|
||||
Size: model.Size,
|
||||
Digest: model.Digest,
|
||||
ModifiedAt: model.ModifiedAt,
|
||||
}
|
||||
}
|
||||
|
||||
return models, nil
|
||||
}
|
||||
|
||||
// DeleteModel deletes a model
|
||||
func (s *OllamaService) DeleteModel(ctx context.Context, modelName string) error {
|
||||
req := &api.DeleteRequest{
|
||||
|
||||
Reference in New Issue
Block a user