mirror of
https://github.com/QuantumNous/new-api.git
synced 2026-09-13 07:40:56 +00:00
* test(relayconvert): add golden snapshot matrix and relaykit boundary guard Phase 0 of the relaykit extraction plan: pin byte-level output of every registered (from,to) request/response/stream conversion route, and forbid kit-bound packages from growing host-only imports. * wip(relayconvert): drop gin.Context from converter signatures; add convmeta draft Phase 1 in progress: relayconvert now takes context.Context; host media resolver adapts gin.Context back at the service boundary. * refactor(relayconvert): decouple converters from RelayInfo, gin, and settings Phase 1 of the relaykit extraction plan: - converters now depend on convmeta.Meta (implemented by RelayInfo) instead of *relaycommon.RelayInfo; ClaudeConvertInfo and the format guesser move to convmeta with aliases left behind - host settings reach converters via a convmeta.Options snapshot built in RelayInfo.ConvOptions; no more model_setting/reasoning global reads inside the conversion layer - effort-suffix helpers move to service/relayconvert/reasoning (old package forwards); chat-to-responses upgrade policy moves to service (host routing logic, not conversion) - golden conversion matrix unchanged * test(relayconvert): tighten boundary — kit packages now free of gin/setting imports * refactor(dto): drop gin and logger dependencies Phase 2 (part 1): dto.Request.IsStream now takes *http.Request instead of *gin.Context (Gemini's impl reads query/path off the std request); dto's three logger calls become common.SysError. Boundary test allowlist is now empty — kit-bound packages import no gin/setting/logger/model. * refactor(kit): extract dependency-free kitutil; dto/types/relayconvert stop importing common Phase 2 of the relaykit extraction plan: - new service/relayconvert/kitutil holds the pure helpers the kit needs (JSON wrappers, pointer/string/uuid/timestamp utils, MaskSensitiveInfo, pluggable LogInfo/LogError hooks, Debug flag) - dto, types, and all relayconvert packages now use kitutil; their only remaining internal deps are dto/types/constant - common keeps every original symbol (MaskSensitiveInfo delegates to kitutil) so host code is untouched; main.go routes kit logging into common.SysLog/SysError and mirrors DebugEnabled - golden conversion matrix unchanged * refactor(kit): move EndpointType/FinishReason to types; OpenRouter dialect via Options Kit packages (dto/types/relayconvert/reasonmap) no longer import constant: - EndpointType and finish-reason values live in types; constant re-exports - the OpenRouter special-case in claude->openai request conversion reads Options.OpenRouterDialect, set by the host from the channel type; InitChannelMeta invalidates the cached snapshot on channel switch * refactor: extract relaykit submodule (dto/types/relayconvert/reasonmap) Phase 3 of the relaykit extraction plan: - new go module github.com/QuantumNous/new-api/relaykit containing dto (minus task family), types, relayconvert (with convmeta/kitutil/reasoning), and reasonmap; host consumes it via require + replace, go.work for dev - task-family dto (task/suno/midjourney/video) stays in the host dto package; dual-consumer host files alias it as taskdto - relaykit builds and tests standalone (GOWORK=off): no host imports, no gin, no DB, no settings - golden conversion matrix unchanged * build(docker): copy relaykit/go.mod before go mod download The local-replace submodule's go.mod must exist inside the build context for the main module graph to resolve. * fix: address relaykit extraction regressions * fix: address relaykit review regressions * docs: document Meta nil receiver contract * fix(relaykit): fail OpenAI→Claude conversion without max_tokens; reject negative default_max_tokens The Claude Messages API requires max_tokens (omitting it is a 400 "Field required"), but with a nil Options.Claude.DefaultMaxTokens hook the converters silently emitted a request the upstream is guaranteed to reject. Both OpenAI Chat and Responses → Claude conversions now return sharedclaude.ErrMissingMaxTokens when no path (client value, default hook, thinking-adapter floor) supplied one. Unreachable in the host, which always configures the hook. Host side, claude.default_max_tokens now rejects negative values at the option API before persisting — they would wrap into huge unsigned values during conversion. Zero stays allowed: the current API treats max_tokens: 0 as cache pre-warming. * fix: make Gemini safety settings read path race-free
299 lines
9.2 KiB
Go
299 lines
9.2 KiB
Go
package geminichat
|
|
|
|
import (
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/QuantumNous/new-api/relaykit/dto"
|
|
kitutil "github.com/QuantumNous/new-api/relaykit/relayconvert/kitutil"
|
|
"github.com/QuantumNous/new-api/relaykit/types"
|
|
)
|
|
|
|
func UsageFromGeminiMetadata(metadata *dto.GeminiUsageMetadata, fallbackPromptTokens int) *dto.Usage {
|
|
if metadata == nil {
|
|
if fallbackPromptTokens <= 0 {
|
|
return nil
|
|
}
|
|
usage := &dto.Usage{PromptTokens: fallbackPromptTokens}
|
|
usage.PromptTokensDetails.TextTokens = fallbackPromptTokens
|
|
return usage
|
|
}
|
|
|
|
promptTokens := metadata.PromptTokenCount + metadata.ToolUsePromptTokenCount
|
|
if promptTokens <= 0 && fallbackPromptTokens > 0 {
|
|
promptTokens = fallbackPromptTokens
|
|
}
|
|
|
|
usage := &dto.Usage{
|
|
PromptTokens: promptTokens,
|
|
CompletionTokens: metadata.CandidatesTokenCount + metadata.ThoughtsTokenCount,
|
|
TotalTokens: metadata.TotalTokenCount,
|
|
BillingUsage: dto.CloneBillingUsage(metadata.BillingUsage),
|
|
}
|
|
if usage.BillingUsage == nil {
|
|
usage.BillingUsage = dto.NewGeminiChatBillingUsage(metadata)
|
|
}
|
|
usage.CompletionTokenDetails.ReasoningTokens = metadata.ThoughtsTokenCount
|
|
usage.PromptTokensDetails.CachedTokens = metadata.CachedContentTokenCount
|
|
|
|
for _, detail := range metadata.PromptTokensDetails {
|
|
if detail.Modality == "AUDIO" {
|
|
usage.PromptTokensDetails.AudioTokens += detail.TokenCount
|
|
} else if detail.Modality == "IMAGE" {
|
|
usage.PromptTokensDetails.ImageTokens += detail.TokenCount
|
|
} else if detail.Modality == "TEXT" {
|
|
usage.PromptTokensDetails.TextTokens += detail.TokenCount
|
|
}
|
|
}
|
|
for _, detail := range metadata.ToolUsePromptTokensDetails {
|
|
if detail.Modality == "AUDIO" {
|
|
usage.PromptTokensDetails.AudioTokens += detail.TokenCount
|
|
} else if detail.Modality == "IMAGE" {
|
|
usage.PromptTokensDetails.ImageTokens += detail.TokenCount
|
|
} else if detail.Modality == "TEXT" {
|
|
usage.PromptTokensDetails.TextTokens += detail.TokenCount
|
|
}
|
|
}
|
|
for _, detail := range metadata.CandidatesTokensDetails {
|
|
switch detail.Modality {
|
|
case "IMAGE":
|
|
usage.CompletionTokenDetails.ImageTokens += detail.TokenCount
|
|
case "AUDIO":
|
|
usage.CompletionTokenDetails.AudioTokens += detail.TokenCount
|
|
case "TEXT":
|
|
usage.CompletionTokenDetails.TextTokens += detail.TokenCount
|
|
}
|
|
}
|
|
|
|
if usage.TotalTokens > 0 && usage.CompletionTokens <= 0 {
|
|
usage.CompletionTokens = usage.TotalTokens - usage.PromptTokens
|
|
}
|
|
|
|
if usage.PromptTokens > 0 && usage.PromptTokensDetails.TextTokens == 0 && usage.PromptTokensDetails.AudioTokens == 0 {
|
|
usage.PromptTokensDetails.TextTokens = usage.PromptTokens
|
|
}
|
|
|
|
return usage
|
|
}
|
|
|
|
func ResponseGeminiChat2OpenAI(id string, created int64, response *dto.GeminiChatResponse) *dto.OpenAITextResponse {
|
|
fullTextResponse := dto.OpenAITextResponse{
|
|
Id: id,
|
|
Object: "chat.completion",
|
|
Created: created,
|
|
Choices: make([]dto.OpenAITextResponseChoice, 0, len(response.Candidates)),
|
|
}
|
|
isToolCall := false
|
|
for _, candidate := range response.Candidates {
|
|
choice := dto.OpenAITextResponseChoice{
|
|
Index: int(candidate.Index),
|
|
Message: dto.Message{
|
|
Role: "assistant",
|
|
Content: "",
|
|
},
|
|
FinishReason: types.FinishReasonStop,
|
|
}
|
|
if len(candidate.Content.Parts) > 0 {
|
|
var content strings.Builder
|
|
var inlineGrow int
|
|
for _, part := range candidate.Content.Parts {
|
|
if part.InlineData != nil {
|
|
inlineGrow += len(part.InlineData.MimeType) + len(part.InlineData.Data) + 32
|
|
}
|
|
}
|
|
if inlineGrow > 0 {
|
|
content.Grow(inlineGrow)
|
|
}
|
|
appended := 0
|
|
writeSep := func() {
|
|
if appended > 0 {
|
|
content.WriteByte('\n')
|
|
}
|
|
appended++
|
|
}
|
|
var toolCalls []dto.ToolCallResponse
|
|
for _, part := range candidate.Content.Parts {
|
|
if part.InlineData != nil {
|
|
if strings.HasPrefix(part.InlineData.MimeType, "image") {
|
|
writeSep()
|
|
content.WriteString("
|
|
content.WriteString(part.InlineData.MimeType)
|
|
content.WriteString(";base64,")
|
|
content.WriteString(part.InlineData.Data)
|
|
content.WriteByte(')')
|
|
} else {
|
|
writeSep()
|
|
content.WriteString("[media](data:")
|
|
content.WriteString(part.InlineData.MimeType)
|
|
content.WriteString(";base64,")
|
|
content.WriteString(part.InlineData.Data)
|
|
content.WriteByte(')')
|
|
}
|
|
} else if part.FunctionCall != nil {
|
|
choice.FinishReason = types.FinishReasonToolCalls
|
|
if call := geminiResponseToolCall(&part); call != nil {
|
|
toolCalls = append(toolCalls, *call)
|
|
}
|
|
} else if part.Thought {
|
|
choice.Message.ReasoningContent = &part.Text
|
|
} else {
|
|
if part.ExecutableCode != nil {
|
|
writeSep()
|
|
content.WriteString("```")
|
|
content.WriteString(part.ExecutableCode.Language)
|
|
content.WriteByte('\n')
|
|
content.WriteString(part.ExecutableCode.Code)
|
|
content.WriteString("\n```")
|
|
} else if part.CodeExecutionResult != nil {
|
|
writeSep()
|
|
content.WriteString("```output\n")
|
|
content.WriteString(part.CodeExecutionResult.Output)
|
|
content.WriteString("\n```")
|
|
} else if part.Text != "\n" {
|
|
writeSep()
|
|
content.WriteString(part.Text)
|
|
}
|
|
}
|
|
}
|
|
if len(toolCalls) > 0 {
|
|
choice.Message.SetToolCalls(toolCalls)
|
|
isToolCall = true
|
|
}
|
|
choice.Message.SetStringContent(content.String())
|
|
}
|
|
if candidate.FinishReason != nil {
|
|
switch *candidate.FinishReason {
|
|
case "STOP":
|
|
choice.FinishReason = types.FinishReasonStop
|
|
case "MAX_TOKENS":
|
|
choice.FinishReason = types.FinishReasonLength
|
|
case "SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "OTHER":
|
|
choice.FinishReason = types.FinishReasonContentFilter
|
|
default:
|
|
choice.FinishReason = types.FinishReasonContentFilter
|
|
}
|
|
}
|
|
if isToolCall {
|
|
choice.FinishReason = types.FinishReasonToolCalls
|
|
}
|
|
|
|
fullTextResponse.Choices = append(fullTextResponse.Choices, choice)
|
|
}
|
|
return &fullTextResponse
|
|
}
|
|
|
|
func StreamResponseGeminiChat2OpenAI(geminiResponse *dto.GeminiChatResponse) (*dto.ChatCompletionsStreamResponse, bool) {
|
|
choices := make([]dto.ChatCompletionsStreamResponseChoice, 0, len(geminiResponse.Candidates))
|
|
isStop := false
|
|
for _, candidate := range geminiResponse.Candidates {
|
|
if candidate.FinishReason != nil && *candidate.FinishReason == "STOP" {
|
|
isStop = true
|
|
candidate.FinishReason = nil
|
|
}
|
|
choice := dto.ChatCompletionsStreamResponseChoice{
|
|
Index: int(candidate.Index),
|
|
Delta: dto.ChatCompletionsStreamResponseChoiceDelta{},
|
|
}
|
|
var content strings.Builder
|
|
var inlineGrow int
|
|
for _, part := range candidate.Content.Parts {
|
|
if part.InlineData != nil {
|
|
inlineGrow += len(part.InlineData.MimeType) + len(part.InlineData.Data) + 32
|
|
}
|
|
}
|
|
if inlineGrow > 0 {
|
|
content.Grow(inlineGrow)
|
|
}
|
|
appended := 0
|
|
writeSep := func() {
|
|
if appended > 0 {
|
|
content.WriteByte('\n')
|
|
}
|
|
appended++
|
|
}
|
|
isTools := false
|
|
isThought := false
|
|
if candidate.FinishReason != nil {
|
|
switch *candidate.FinishReason {
|
|
case "STOP":
|
|
choice.FinishReason = &types.FinishReasonStop
|
|
case "MAX_TOKENS":
|
|
choice.FinishReason = &types.FinishReasonLength
|
|
case "SAFETY", "RECITATION", "BLOCKLIST", "PROHIBITED_CONTENT", "SPII", "OTHER":
|
|
choice.FinishReason = &types.FinishReasonContentFilter
|
|
default:
|
|
choice.FinishReason = &types.FinishReasonContentFilter
|
|
}
|
|
}
|
|
for _, part := range candidate.Content.Parts {
|
|
if part.InlineData != nil {
|
|
if strings.HasPrefix(part.InlineData.MimeType, "image") {
|
|
writeSep()
|
|
content.WriteString("
|
|
content.WriteString(part.InlineData.MimeType)
|
|
content.WriteString(";base64,")
|
|
content.WriteString(part.InlineData.Data)
|
|
content.WriteByte(')')
|
|
}
|
|
} else if part.FunctionCall != nil {
|
|
isTools = true
|
|
if call := geminiResponseToolCall(&part); call != nil {
|
|
call.SetIndex(len(choice.Delta.ToolCalls))
|
|
choice.Delta.ToolCalls = append(choice.Delta.ToolCalls, *call)
|
|
}
|
|
} else if part.Thought {
|
|
isThought = true
|
|
writeSep()
|
|
content.WriteString(part.Text)
|
|
} else {
|
|
if part.ExecutableCode != nil {
|
|
writeSep()
|
|
content.WriteString("```")
|
|
content.WriteString(part.ExecutableCode.Language)
|
|
content.WriteByte('\n')
|
|
content.WriteString(part.ExecutableCode.Code)
|
|
content.WriteString("\n```\n")
|
|
} else if part.CodeExecutionResult != nil {
|
|
writeSep()
|
|
content.WriteString("```output\n")
|
|
content.WriteString(part.CodeExecutionResult.Output)
|
|
content.WriteString("\n```\n")
|
|
} else if part.Text != "\n" {
|
|
writeSep()
|
|
content.WriteString(part.Text)
|
|
}
|
|
}
|
|
}
|
|
if isThought {
|
|
choice.Delta.SetReasoningContent(content.String())
|
|
} else {
|
|
choice.Delta.SetContentString(content.String())
|
|
}
|
|
if isTools {
|
|
choice.FinishReason = &types.FinishReasonToolCalls
|
|
}
|
|
choices = append(choices, choice)
|
|
}
|
|
|
|
response := dto.ChatCompletionsStreamResponse{
|
|
Object: "chat.completion.chunk",
|
|
Choices: choices,
|
|
}
|
|
return &response, isStop
|
|
}
|
|
|
|
func geminiResponseToolCall(item *dto.GeminiPart) *dto.ToolCallResponse {
|
|
argsBytes, err := kitutil.Marshal(item.FunctionCall.Arguments)
|
|
if err != nil {
|
|
return nil
|
|
}
|
|
return &dto.ToolCallResponse{
|
|
ID: fmt.Sprintf("call_%s", kitutil.GetUUID()),
|
|
Type: "function",
|
|
Function: dto.FunctionResponse{
|
|
Arguments: string(argsBytes),
|
|
Name: item.FunctionCall.FunctionName,
|
|
},
|
|
}
|
|
}
|