File size: 11,675 Bytes
1766992 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 | package services
import (
"bytes"
"github.com/libaxuan/cursor2api-go/middleware"
"github.com/libaxuan/cursor2api-go/models"
"github.com/libaxuan/cursor2api-go/utils"
"encoding/json"
"fmt"
"strings"
)
const thinkingHint = "Use <thinking>...</thinking> for hidden reasoning when it helps. Keep your final visible answer outside the thinking tags."
type cursorBuildResult struct {
Payload models.CursorRequest
ParseConfig models.CursorParseConfig
}
type toolChoiceSpec struct {
Mode string
FunctionName string
}
func (s *CursorService) buildCursorRequest(request *models.ChatCompletionRequest) (cursorBuildResult, error) {
capability := models.ResolveModelCapability(request.Model)
toolChoice, err := parseToolChoice(request.ToolChoice)
if err != nil {
return cursorBuildResult{}, middleware.NewRequestValidationError(err.Error(), "invalid_tool_choice")
}
// Kilo Code 兼容:当上层编排器希望“必须用工具”时,即便 tool_choice=auto,
// 也可以通过环境变量强制要求至少一次工具调用,避免 MODEL_NO_TOOLS_USED 一类的上层报错。
if s.config != nil && s.config.KiloToolStrict && len(request.Tools) > 0 && toolChoice.Mode == "auto" {
toolChoice.Mode = "required"
}
if len(request.Tools) == 0 && toolChoice.Mode != "auto" && toolChoice.Mode != "none" {
return cursorBuildResult{}, middleware.NewRequestValidationError("tool_choice requires tools to be provided", "missing_tools")
}
if err := validateTools(request.Tools); err != nil {
return cursorBuildResult{}, middleware.NewRequestValidationError(err.Error(), "invalid_tools")
}
if toolChoice.FunctionName != "" && !toolExists(request.Tools, toolChoice.FunctionName) {
return cursorBuildResult{}, middleware.NewRequestValidationError(
fmt.Sprintf("tool_choice references unknown function %q", toolChoice.FunctionName),
"unknown_tool_choice_function",
)
}
hasToolHistory := messagesContainToolHistory(request.Messages)
toolProtocolEnabled := len(request.Tools) > 0 && toolChoice.Mode != "none"
triggerSignal := ""
if toolProtocolEnabled || hasToolHistory {
triggerSignal = "<<CALL_" + utils.GenerateRandomString(8) + ">>"
}
cursorMessages := buildCursorMessages(
request.Messages,
s.config.SystemPromptInject,
request.Tools,
toolChoice,
capability,
hasToolHistory,
triggerSignal,
)
cursorMessages = s.truncateCursorMessages(cursorMessages)
payload := models.CursorRequest{
Context: []interface{}{},
Model: models.GetCursorModel(request.Model),
ID: utils.GenerateRandomString(16),
Messages: cursorMessages,
Trigger: "submit-message",
}
return cursorBuildResult{
Payload: payload,
ParseConfig: models.CursorParseConfig{
TriggerSignal: triggerSignal,
ThinkingEnabled: capability.ThinkingEnabled,
},
}, nil
}
func parseToolChoice(raw json.RawMessage) (toolChoiceSpec, error) {
if len(bytes.TrimSpace(raw)) == 0 || string(bytes.TrimSpace(raw)) == "null" {
return toolChoiceSpec{Mode: "auto"}, nil
}
var choiceString string
if err := json.Unmarshal(raw, &choiceString); err == nil {
switch choiceString {
case "auto", "none", "required":
return toolChoiceSpec{Mode: choiceString}, nil
default:
return toolChoiceSpec{}, fmt.Errorf("unsupported tool_choice value %q", choiceString)
}
}
var choiceObject models.ToolChoiceObject
if err := json.Unmarshal(raw, &choiceObject); err != nil {
return toolChoiceSpec{}, fmt.Errorf("tool_choice must be a string or function object")
}
if choiceObject.Type != "function" {
return toolChoiceSpec{}, fmt.Errorf("unsupported tool_choice type %q", choiceObject.Type)
}
if choiceObject.Function == nil || strings.TrimSpace(choiceObject.Function.Name) == "" {
return toolChoiceSpec{}, fmt.Errorf("tool_choice.function.name is required")
}
return toolChoiceSpec{
Mode: "function",
FunctionName: strings.TrimSpace(choiceObject.Function.Name),
}, nil
}
func validateTools(tools []models.Tool) error {
seen := make(map[string]struct{}, len(tools))
for _, tool := range tools {
toolType := tool.Type
if toolType == "" {
toolType = "function"
}
if toolType != "function" {
return fmt.Errorf("unsupported tool type %q", tool.Type)
}
name := strings.TrimSpace(tool.Function.Name)
if name == "" {
return fmt.Errorf("tool function name is required")
}
if _, exists := seen[name]; exists {
return fmt.Errorf("duplicate tool function name %q", name)
}
seen[name] = struct{}{}
}
return nil
}
func toolExists(tools []models.Tool, name string) bool {
for _, tool := range tools {
if strings.TrimSpace(tool.Function.Name) == name {
return true
}
}
return false
}
func buildCursorMessages(
messages []models.Message,
systemPromptInject string,
tools []models.Tool,
toolChoice toolChoiceSpec,
capability models.ModelCapability,
hasToolHistory bool,
triggerSignal string,
) []models.CursorMessage {
result := make([]models.CursorMessage, 0, len(messages)+1)
startIdx := 0
systemSegments := make([]string, 0, 3)
if len(messages) > 0 && strings.EqualFold(messages[0].Role, "system") {
if systemText := strings.TrimSpace(messages[0].GetStringContent()); systemText != "" {
systemSegments = append(systemSegments, systemText)
}
startIdx = 1
}
if inject := strings.TrimSpace(systemPromptInject); inject != "" {
systemSegments = append(systemSegments, inject)
}
if protocolText := strings.TrimSpace(buildProtocolPrompt(tools, toolChoice, capability.ThinkingEnabled, hasToolHistory, triggerSignal)); protocolText != "" {
systemSegments = append(systemSegments, protocolText)
}
if len(systemSegments) > 0 {
result = append(result, newCursorTextMessage("system", strings.Join(systemSegments, "\n\n")))
}
for _, msg := range messages[startIdx:] {
converted, ok := convertMessage(msg, capability.ThinkingEnabled, triggerSignal)
if !ok {
continue
}
result = append(result, converted)
}
return result
}
func buildProtocolPrompt(tools []models.Tool, toolChoice toolChoiceSpec, thinkingEnabled bool, hasToolHistory bool, triggerSignal string) string {
var sections []string
if len(tools) > 0 && triggerSignal != "" {
var builder strings.Builder
builder.WriteString("You may call external tools through the bridge below.\n")
builder.WriteString("When you need a tool, output exactly in this format with no markdown fences:\n")
builder.WriteString(triggerSignal)
builder.WriteString("\n<invoke name=\"tool_name\">{\"arg\":\"value\"}</invoke>\n")
builder.WriteString("Available tools:\n")
builder.WriteString(renderFunctionList(tools))
switch toolChoice.Mode {
case "required":
builder.WriteString("\nYou must call at least one tool before your final answer.")
builder.WriteString("\nIMPORTANT: Your next assistant message MUST be a tool call using the exact format above. Do not include any natural language text in that message.")
case "function":
builder.WriteString(fmt.Sprintf("\nYou must call the function %q before your final answer.", toolChoice.FunctionName))
builder.WriteString("\nIMPORTANT: Your next assistant message MUST be a tool call using the exact format above. Do not include any natural language text in that message.")
}
sections = append(sections, builder.String())
} else if hasToolHistory && triggerSignal != "" {
var builder strings.Builder
builder.WriteString("Previous assistant tool calls in this conversation are serialized in the following format:\n")
builder.WriteString(triggerSignal)
builder.WriteString("\n<invoke name=\"tool_name\">{\"arg\":\"value\"}</invoke>\n")
builder.WriteString("Previous tool results are serialized as <tool_result ...>...</tool_result>.\n")
builder.WriteString("Treat those tool transcripts as completed history. Do not emit a new tool call unless a current tool list is provided.")
sections = append(sections, builder.String())
}
if thinkingEnabled {
sections = append(sections, thinkingHint)
}
return strings.Join(sections, "\n\n")
}
func messagesContainToolHistory(messages []models.Message) bool {
for _, msg := range messages {
if len(msg.ToolCalls) > 0 {
return true
}
if strings.EqualFold(strings.TrimSpace(msg.Role), "tool") {
return true
}
}
return false
}
func renderFunctionList(tools []models.Tool) string {
var builder strings.Builder
builder.WriteString("<function_list>\n")
for _, tool := range tools {
schema := "{}"
if len(tool.Function.Parameters) > 0 {
if marshaled, err := json.MarshalIndent(tool.Function.Parameters, "", " "); err == nil {
schema = string(marshaled)
}
}
builder.WriteString(fmt.Sprintf("<function name=\"%s\">\n", tool.Function.Name))
if desc := strings.TrimSpace(tool.Function.Description); desc != "" {
builder.WriteString(desc)
builder.WriteString("\n")
}
builder.WriteString("JSON Schema:\n")
builder.WriteString(schema)
builder.WriteString("\n</function>\n")
}
builder.WriteString("</function_list>")
return builder.String()
}
func convertMessage(msg models.Message, thinkingEnabled bool, triggerSignal string) (models.CursorMessage, bool) {
role := strings.TrimSpace(msg.Role)
if role == "" {
return models.CursorMessage{}, false
}
switch role {
case "tool":
return newCursorTextMessage("user", formatToolResult(msg)), true
case "assistant":
text := strings.TrimSpace(msg.GetStringContent())
segments := make([]string, 0, len(msg.ToolCalls)+1)
if text != "" {
segments = append(segments, text)
}
for _, toolCall := range msg.ToolCalls {
segments = append(segments, formatAssistantToolCall(toolCall, triggerSignal))
}
if len(segments) == 0 {
return models.CursorMessage{}, false
}
return newCursorTextMessage("assistant", strings.Join(segments, "\n\n")), true
case "user":
text := msg.GetStringContent()
if thinkingEnabled {
text = appendThinkingHint(text)
}
if strings.TrimSpace(text) == "" {
return models.CursorMessage{}, false
}
return newCursorTextMessage("user", text), true
default:
text := msg.GetStringContent()
if strings.TrimSpace(text) == "" {
return models.CursorMessage{}, false
}
return newCursorTextMessage(role, text), true
}
}
func appendThinkingHint(content string) string {
content = strings.TrimSpace(content)
if content == "" {
return thinkingHint
}
return content + "\n\n" + thinkingHint
}
func formatAssistantToolCall(toolCall models.ToolCall, triggerSignal string) string {
pieces := make([]string, 0, 2)
if triggerSignal != "" {
pieces = append(pieces, triggerSignal)
}
callType := toolCall.Type
if callType == "" {
callType = "function"
}
name := strings.TrimSpace(toolCall.Function.Name)
if name == "" {
name = "tool"
}
arguments := strings.TrimSpace(toolCall.Function.Arguments)
if arguments == "" {
arguments = "{}"
}
pieces = append(pieces, fmt.Sprintf("<invoke name=\"%s\">%s</invoke>", name, arguments))
return strings.Join(pieces, "\n")
}
func formatToolResult(msg models.Message) string {
content := msg.GetStringContent()
id := strings.TrimSpace(msg.ToolCallID)
name := strings.TrimSpace(msg.Name)
var builder strings.Builder
builder.WriteString("<tool_result")
if id != "" {
builder.WriteString(fmt.Sprintf(" id=\"%s\"", id))
}
if name != "" {
builder.WriteString(fmt.Sprintf(" name=\"%s\"", name))
}
builder.WriteString(">")
builder.WriteString(content)
builder.WriteString("</tool_result>")
return builder.String()
}
func newCursorTextMessage(role, text string) models.CursorMessage {
return models.CursorMessage{
Role: role,
Parts: []models.CursorPart{
{
Type: "text",
Text: text,
},
},
}
}
|