* 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
343 lines
10 KiB
Go
343 lines
10 KiB
Go
package ollama
|
|
|
|
import (
|
|
"encoding/json"
|
|
"fmt"
|
|
"io"
|
|
"net/http"
|
|
"strings"
|
|
"time"
|
|
|
|
"github.com/QuantumNous/new-api/common"
|
|
"github.com/QuantumNous/new-api/constant"
|
|
"github.com/QuantumNous/new-api/logger"
|
|
relaycommon "github.com/QuantumNous/new-api/relay/common"
|
|
"github.com/QuantumNous/new-api/relay/helper"
|
|
"github.com/QuantumNous/new-api/relaykit/dto"
|
|
"github.com/QuantumNous/new-api/relaykit/types"
|
|
"github.com/QuantumNous/new-api/service"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
type ollamaChatStreamChunk struct {
|
|
Model string `json:"model"`
|
|
CreatedAt string `json:"created_at"`
|
|
// chat
|
|
Message *struct {
|
|
Role string `json:"role"`
|
|
Content string `json:"content"`
|
|
Thinking json.RawMessage `json:"thinking"`
|
|
ToolCalls []OllamaToolCall `json:"tool_calls"`
|
|
} `json:"message"`
|
|
// generate
|
|
Response string `json:"response"`
|
|
Done bool `json:"done"`
|
|
DoneReason string `json:"done_reason"`
|
|
TotalDuration int64 `json:"total_duration"`
|
|
LoadDuration int64 `json:"load_duration"`
|
|
PromptEvalCount int `json:"prompt_eval_count"`
|
|
EvalCount int `json:"eval_count"`
|
|
PromptEvalDuration int64 `json:"prompt_eval_duration"`
|
|
EvalDuration int64 `json:"eval_duration"`
|
|
}
|
|
|
|
func ollamaToolCallsToOpenAI(toolCalls []OllamaToolCall, startIndex int, includeIndex bool) ([]dto.ToolCallResponse, int) {
|
|
if len(toolCalls) == 0 {
|
|
return nil, startIndex
|
|
}
|
|
result := make([]dto.ToolCallResponse, 0, len(toolCalls))
|
|
for _, tc := range toolCalls {
|
|
var argBytes []byte
|
|
var err error
|
|
if tc.Function.Arguments == nil {
|
|
argBytes = []byte("{}")
|
|
} else {
|
|
argBytes, err = common.Marshal(tc.Function.Arguments)
|
|
if err != nil || len(argBytes) == 0 {
|
|
argBytes = []byte("{}")
|
|
}
|
|
}
|
|
tr := dto.ToolCallResponse{
|
|
ID: fmt.Sprintf("call_%d", startIndex),
|
|
Type: "function",
|
|
Function: dto.FunctionResponse{
|
|
Name: tc.Function.Name,
|
|
Arguments: string(argBytes),
|
|
},
|
|
}
|
|
if includeIndex {
|
|
tr.SetIndex(startIndex)
|
|
}
|
|
startIndex++
|
|
result = append(result, tr)
|
|
}
|
|
return result, startIndex
|
|
}
|
|
|
|
func toUnix(ts string) int64 {
|
|
if ts == "" {
|
|
return time.Now().Unix()
|
|
}
|
|
// try time.RFC3339 or with nanoseconds
|
|
t, err := time.Parse(time.RFC3339Nano, ts)
|
|
if err != nil {
|
|
t2, err2 := time.Parse(time.RFC3339, ts)
|
|
if err2 == nil {
|
|
return t2.Unix()
|
|
}
|
|
return time.Now().Unix()
|
|
}
|
|
return t.Unix()
|
|
}
|
|
|
|
func ollamaStreamHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
|
|
if resp == nil || resp.Body == nil {
|
|
return nil, types.NewOpenAIError(fmt.Errorf("empty response"), types.ErrorCodeBadResponse, http.StatusBadRequest)
|
|
}
|
|
defer service.CloseResponseBodyGracefully(resp)
|
|
|
|
helper.SetEventStreamHeaders(c)
|
|
scanner := helper.NewStreamScanner(resp.Body)
|
|
usage := &dto.Usage{}
|
|
var model = info.UpstreamModelName
|
|
var responseId = common.GetUUID()
|
|
var created = time.Now().Unix()
|
|
var toolCallIndex int
|
|
start := helper.GenerateStartEmptyResponse(responseId, created, model, nil)
|
|
if data, err := common.Marshal(start); err == nil {
|
|
_ = helper.StringData(c, string(data))
|
|
}
|
|
|
|
for scanner.Scan() {
|
|
line := scanner.Text()
|
|
line = strings.TrimSpace(line)
|
|
if line == "" {
|
|
continue
|
|
}
|
|
var chunk ollamaChatStreamChunk
|
|
if err := common.Unmarshal([]byte(line), &chunk); err != nil {
|
|
logger.LogError(c, "ollama stream json decode error: "+err.Error()+" line="+line)
|
|
return usage, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
|
|
}
|
|
if chunk.Model != "" {
|
|
model = chunk.Model
|
|
}
|
|
created = toUnix(chunk.CreatedAt)
|
|
|
|
if !chunk.Done {
|
|
// delta content
|
|
var content string
|
|
if chunk.Message != nil {
|
|
content = chunk.Message.Content
|
|
} else {
|
|
content = chunk.Response
|
|
}
|
|
delta := dto.ChatCompletionsStreamResponse{
|
|
Id: responseId,
|
|
Object: "chat.completion.chunk",
|
|
Created: created,
|
|
Model: model,
|
|
Choices: []dto.ChatCompletionsStreamResponseChoice{{
|
|
Index: 0,
|
|
Delta: dto.ChatCompletionsStreamResponseChoiceDelta{Role: "assistant"},
|
|
}},
|
|
}
|
|
if content != "" {
|
|
delta.Choices[0].Delta.SetContentString(content)
|
|
}
|
|
if chunk.Message != nil && len(chunk.Message.Thinking) > 0 {
|
|
raw := strings.TrimSpace(string(chunk.Message.Thinking))
|
|
if raw != "" && raw != "null" {
|
|
// Unmarshal the JSON string to get the actual content without quotes
|
|
var thinkingContent string
|
|
if err := common.Unmarshal(chunk.Message.Thinking, &thinkingContent); err == nil {
|
|
delta.Choices[0].Delta.SetReasoningContent(thinkingContent)
|
|
} else {
|
|
// Fallback to raw string if it's not a JSON string
|
|
delta.Choices[0].Delta.SetReasoningContent(raw)
|
|
}
|
|
}
|
|
}
|
|
// tool calls
|
|
if chunk.Message != nil && len(chunk.Message.ToolCalls) > 0 {
|
|
delta.Choices[0].Delta.ToolCalls, toolCallIndex = ollamaToolCallsToOpenAI(chunk.Message.ToolCalls, toolCallIndex, true)
|
|
}
|
|
if data, err := common.Marshal(delta); err == nil {
|
|
_ = helper.StringData(c, string(data))
|
|
}
|
|
continue
|
|
}
|
|
// done frame
|
|
// finalize once and break loop
|
|
usage.PromptTokens = chunk.PromptEvalCount
|
|
usage.CompletionTokens = chunk.EvalCount
|
|
usage.TotalTokens = usage.PromptTokens + usage.CompletionTokens
|
|
finishReason := chunk.DoneReason
|
|
if finishReason == "" {
|
|
finishReason = "stop"
|
|
}
|
|
if toolCallIndex > 0 {
|
|
finishReason = constant.FinishReasonToolCalls
|
|
}
|
|
// emit stop delta
|
|
if stop := helper.GenerateStopResponse(responseId, created, model, finishReason); stop != nil {
|
|
if data, err := common.Marshal(stop); err == nil {
|
|
_ = helper.StringData(c, string(data))
|
|
}
|
|
}
|
|
// emit usage frame
|
|
if final := helper.GenerateFinalUsageResponse(responseId, created, model, *usage); final != nil {
|
|
if data, err := common.Marshal(final); err == nil {
|
|
_ = helper.StringData(c, string(data))
|
|
}
|
|
}
|
|
// send [DONE]
|
|
helper.Done(c)
|
|
break
|
|
}
|
|
if err := scanner.Err(); err != nil && err != io.EOF {
|
|
logger.LogError(c, "ollama stream scan error: "+err.Error())
|
|
}
|
|
return usage, nil
|
|
}
|
|
|
|
// non-stream handler for chat/generate
|
|
func ollamaChatHandler(c *gin.Context, info *relaycommon.RelayInfo, resp *http.Response) (*dto.Usage, *types.NewAPIError) {
|
|
body, err := io.ReadAll(resp.Body)
|
|
if err != nil {
|
|
return nil, types.NewOpenAIError(err, types.ErrorCodeReadResponseBodyFailed, http.StatusInternalServerError)
|
|
}
|
|
service.CloseResponseBodyGracefully(resp)
|
|
raw := string(body)
|
|
if common.DebugEnabled {
|
|
println("ollama non-stream raw resp:", raw)
|
|
}
|
|
|
|
lines := strings.Split(raw, "\n")
|
|
var (
|
|
aggContent strings.Builder
|
|
reasoningBuilder strings.Builder
|
|
lastChunk ollamaChatStreamChunk
|
|
parsedAny bool
|
|
toolCallIndex int
|
|
toolCalls []dto.ToolCallResponse
|
|
)
|
|
for _, ln := range lines {
|
|
ln = strings.TrimSpace(ln)
|
|
if ln == "" {
|
|
continue
|
|
}
|
|
var ck ollamaChatStreamChunk
|
|
if err := common.Unmarshal([]byte(ln), &ck); err != nil {
|
|
if len(lines) == 1 {
|
|
return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
|
|
}
|
|
continue
|
|
}
|
|
parsedAny = true
|
|
lastChunk = ck
|
|
if ck.Message != nil && len(ck.Message.Thinking) > 0 {
|
|
raw := strings.TrimSpace(string(ck.Message.Thinking))
|
|
if raw != "" && raw != "null" {
|
|
// Unmarshal the JSON string to get the actual content without quotes
|
|
var thinkingContent string
|
|
if err := common.Unmarshal(ck.Message.Thinking, &thinkingContent); err == nil {
|
|
reasoningBuilder.WriteString(thinkingContent)
|
|
} else {
|
|
// Fallback to raw string if it's not a JSON string
|
|
reasoningBuilder.WriteString(raw)
|
|
}
|
|
}
|
|
}
|
|
if ck.Message != nil && ck.Message.Content != "" {
|
|
aggContent.WriteString(ck.Message.Content)
|
|
} else if ck.Response != "" {
|
|
aggContent.WriteString(ck.Response)
|
|
}
|
|
if ck.Message != nil && len(ck.Message.ToolCalls) > 0 {
|
|
var converted []dto.ToolCallResponse
|
|
converted, toolCallIndex = ollamaToolCallsToOpenAI(ck.Message.ToolCalls, toolCallIndex, false)
|
|
toolCalls = append(toolCalls, converted...)
|
|
}
|
|
}
|
|
|
|
if !parsedAny {
|
|
var single ollamaChatStreamChunk
|
|
if err := common.Unmarshal(body, &single); err != nil {
|
|
return nil, types.NewOpenAIError(err, types.ErrorCodeBadResponseBody, http.StatusInternalServerError)
|
|
}
|
|
lastChunk = single
|
|
if single.Message != nil {
|
|
if len(single.Message.Thinking) > 0 {
|
|
raw := strings.TrimSpace(string(single.Message.Thinking))
|
|
if raw != "" && raw != "null" {
|
|
// Unmarshal the JSON string to get the actual content without quotes
|
|
var thinkingContent string
|
|
if err := common.Unmarshal(single.Message.Thinking, &thinkingContent); err == nil {
|
|
reasoningBuilder.WriteString(thinkingContent)
|
|
} else {
|
|
// Fallback to raw string if it's not a JSON string
|
|
reasoningBuilder.WriteString(raw)
|
|
}
|
|
}
|
|
}
|
|
aggContent.WriteString(single.Message.Content)
|
|
if len(single.Message.ToolCalls) > 0 {
|
|
var converted []dto.ToolCallResponse
|
|
converted, toolCallIndex = ollamaToolCallsToOpenAI(single.Message.ToolCalls, toolCallIndex, false)
|
|
toolCalls = append(toolCalls, converted...)
|
|
}
|
|
} else {
|
|
aggContent.WriteString(single.Response)
|
|
}
|
|
}
|
|
|
|
model := lastChunk.Model
|
|
if model == "" {
|
|
model = info.UpstreamModelName
|
|
}
|
|
created := toUnix(lastChunk.CreatedAt)
|
|
usage := &dto.Usage{PromptTokens: lastChunk.PromptEvalCount, CompletionTokens: lastChunk.EvalCount, TotalTokens: lastChunk.PromptEvalCount + lastChunk.EvalCount}
|
|
content := aggContent.String()
|
|
finishReason := lastChunk.DoneReason
|
|
if finishReason == "" {
|
|
finishReason = "stop"
|
|
}
|
|
if len(toolCalls) > 0 {
|
|
finishReason = constant.FinishReasonToolCalls
|
|
}
|
|
|
|
msg := dto.Message{Role: "assistant", Content: contentPtr(content)}
|
|
if len(toolCalls) > 0 {
|
|
if rawToolCalls, err := common.Marshal(toolCalls); err == nil {
|
|
msg.ToolCalls = rawToolCalls
|
|
}
|
|
}
|
|
if rc := reasoningBuilder.String(); rc != "" {
|
|
msg.ReasoningContent = &rc
|
|
}
|
|
full := dto.OpenAITextResponse{
|
|
Id: common.GetUUID(),
|
|
Model: model,
|
|
Object: "chat.completion",
|
|
Created: created,
|
|
Choices: []dto.OpenAITextResponseChoice{{
|
|
Index: 0,
|
|
Message: msg,
|
|
FinishReason: finishReason,
|
|
}},
|
|
Usage: *usage,
|
|
}
|
|
out, _ := common.Marshal(full)
|
|
service.IOCopyBytesGracefully(c, resp, out)
|
|
return usage, nil
|
|
}
|
|
|
|
func contentPtr(s string) *string {
|
|
if s == "" {
|
|
return nil
|
|
}
|
|
return &s
|
|
}
|