Skip to content
Closed
Show file tree
Hide file tree
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 7 additions & 1 deletion controller/relay.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
ws *websocket.Conn
)

if relayFormat == types.RelayFormatOpenAIRealtime {
if relayFormat == types.RelayFormatOpenAIRealtime || (relayFormat == types.RelayFormatOpenAIResponses && c.Request.Method == http.MethodGet) {
var err error
ws, err = upgrader.Upgrade(c.Writer, c.Request, nil)
if err != nil {
Expand Down Expand Up @@ -211,6 +211,12 @@ func Relay(c *gin.Context, relayFormat types.RelayFormat) {
switch relayFormat {
case types.RelayFormatOpenAIRealtime:
newAPIError = relay.WssHelper(c, relayInfo)
case types.RelayFormatOpenAIResponses:
if relayInfo.ClientWs != nil {
newAPIError = relay.WssResponsesHelper(c, relayInfo)
} else {
newAPIError = relayHandler(c, relayInfo)
}
case types.RelayFormatClaude:
newAPIError = relay.ClaudeHelper(c, relayInfo)
case types.RelayFormatGemini:
Expand Down
6 changes: 6 additions & 0 deletions middleware/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -311,6 +311,12 @@ func TokenAuth() func(c *gin.Context) {
c.Request.Header.Set("Authorization", "Bearer "+xGoogKey)
}
}
if strings.HasPrefix(c.Request.URL.Path, "/v1/responses") {
apiKey := c.Query("api_key")
if apiKey != "" {
c.Request.Header.Set("Authorization", "Bearer "+apiKey)
}
}
Comment on lines +314 to +319

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

API key in query string leaks via logs.

Accepting api_key as a query-string parameter causes the credential to be written to web server access logs, reverse-proxy logs, browser history, and Referer headers on outbound navigation. WebSocket clients already have a header-based path via Sec-WebSocket-Protocol (see Lines 279–292) — prefer extending that (e.g., accept openai-insecure-api-key.sk-xxx for /v1/responses as well) and either gate the query-string form behind a config flag or document that it is for insecure/testing use only.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@middleware/auth.go` around lines 314 - 319, The middleware currently reads
credentials from the query parameter (`c.Query("api_key")`) for requests to
"/v1/responses", which leaks secrets via logs; change the logic in the
middleware handling (the block using strings.HasPrefix(c.Request.URL.Path,
"/v1/responses")) to stop accepting api_key from the URL by default, instead
accept the API key from a header (reuse the existing Sec-WebSocket-Protocol
handling or a dedicated header like "X-OpenAI-Insecure-Api-Key") and set
Authorization from that header, and if you need to keep query-string support
make it conditional on a new config flag (e.g., AllowInsecureApiKeyInQuery) so
the query form is disabled in production; update any related docs/comments to
indicate the query parameter is insecure/testing-only.

key := c.Request.Header.Get("Authorization")
parts := make([]string, 0)
if strings.HasPrefix(key, "Bearer ") || strings.HasPrefix(key, "bearer ") {
Expand Down
27 changes: 27 additions & 0 deletions middleware/distributor.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import (
"github.com/QuantumNous/new-api/constant"
"github.com/QuantumNous/new-api/dto"
"github.com/QuantumNous/new-api/i18n"
"github.com/QuantumNous/new-api/logger"
"github.com/QuantumNous/new-api/model"
relayconstant "github.com/QuantumNous/new-api/relay/constant"
"github.com/QuantumNous/new-api/service"
Expand Down Expand Up @@ -339,6 +340,32 @@ func getModelRequest(c *gin.Context) (*ModelRequest, bool, error) {
if strings.HasPrefix(c.Request.URL.Path, "/v1/responses/compact") && modelRequest.Model != "" {
modelRequest.Model = ratio_setting.WithCompactModelSuffix(modelRequest.Model)
}
if strings.HasPrefix(c.Request.URL.Path, "/v1/responses") && modelRequest.Model == "" {
// logger.LogInfo(c, "DEBUG: headers: " + fmt.Sprintf("%v", c.Request.Header))
modelRequest.Model = c.Query("model")
if modelRequest.Model == "" {
protocol := c.GetHeader("Sec-WebSocket-Protocol")
if protocol != "" {
parts := strings.Split(protocol, ",")
for _, part := range parts {
part = strings.TrimSpace(part)
if strings.HasPrefix(part, "openai-model.") {
modelRequest.Model = strings.TrimPrefix(part, "openai-model.")
break
}
// Fallback: If it's a common model name pattern but not prefixed
if !strings.HasPrefix(part, "openai-") && !strings.Contains(part, "realtime") && strings.Contains(part, "-") {
modelRequest.Model = part
}
}
}
}
// 終極保底:如果真的什麼都找不到,強制使用這個預設值以避免 400 錯誤
if modelRequest.Model == "" {
modelRequest.Model = "gpt-5.3-codex"
logger.LogInfo(c, "WebSocket responses: model completely missing, fallback to gpt-5.3-codex")
}
}
Comment on lines +343 to +368

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Silent hard-coded model fallback and stray debug artifact.

A few concerns in this /v1/responses block:

  1. Missing break in the heuristic branch (Lines 357–359). The openai-model. branch breaks on first match, but the fallback heuristic keeps iterating and overwrites modelRequest.Model with the last matching part. If a client advertises multiple subprotocols this will silently land on whichever ordered last. Either break after assignment or only take the first viable candidate.
  2. Silent fallback to gpt-5.3-codex (Lines 364–367). Force-setting an arbitrary model hides the fact that the request was malformed, disrupts billing/channel routing, and will 403 for any user whose group lacks that model. Prefer returning a 400 (letting the distributor’s existing empty-model check at Line 79 do its job) so the client learns to send a model. At minimum, gate this behind a config option and loudly log.
  3. Commented-out debug log (Line 344). Please drop it rather than leaving it as a dead comment.
🔧 Suggested change
 	if strings.HasPrefix(c.Request.URL.Path, "/v1/responses") && modelRequest.Model == "" {
-		// logger.LogInfo(c, "DEBUG: headers: " + fmt.Sprintf("%v", c.Request.Header))
 		modelRequest.Model = c.Query("model")
 		if modelRequest.Model == "" {
 			protocol := c.GetHeader("Sec-WebSocket-Protocol")
 			if protocol != "" {
 				parts := strings.Split(protocol, ",")
 				for _, part := range parts {
 					part = strings.TrimSpace(part)
 					if strings.HasPrefix(part, "openai-model.") {
 						modelRequest.Model = strings.TrimPrefix(part, "openai-model.")
 						break
 					}
-					// Fallback: If it's a common model name pattern but not prefixed
 					if !strings.HasPrefix(part, "openai-") && !strings.Contains(part, "realtime") && strings.Contains(part, "-") {
 						modelRequest.Model = part
+						break
 					}
 				}
 			}
 		}
-		// 終極保底:如果真的什麼都找不到,強制使用這個預設值以避免 400 錯誤
-		if modelRequest.Model == "" {
-			modelRequest.Model = "gpt-5.3-codex"
-			logger.LogInfo(c, "WebSocket responses: model completely missing, fallback to gpt-5.3-codex")
-		}
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@middleware/distributor.go` around lines 343 - 368, Remove the commented-out
debug line and stop silently forcing a hard-coded model; in the /v1/responses
branch that inspects Sec-WebSocket-Protocol, change the fallback heuristic loop
(the loop that sets modelRequest.Model when part contains "-" and lacks
"openai-"/"realtime") so it only assigns the first viable candidate and
immediately break after assignment (do not let later parts overwrite it). Remove
the unconditional fallback that sets modelRequest.Model = "gpt-5.3-codex";
instead either abort the request with a 400 (e.g., via c.AbortWithStatusJSON) so
the existing empty-model validation handles it, or gate a default-model fallback
behind a config flag and make the action emit a loud
logger.LogError/logger.LogInfo with the chosen default.

return &modelRequest, shouldSelectChannel, nil
}

Expand Down
53 changes: 51 additions & 2 deletions relay/channel/claude/adaptor.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package claude

import (
"encoding/json"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Use common.Unmarshal instead of encoding/json, and drop image/file inputs are silently ignored.

Two items on this conversion:

  1. Guideline violation — direct encoding/json use. The new encoding/json import (Line 4) and json.Unmarshal call (Line 132) bypass the repo-mandated wrappers. Please swap to common.Unmarshal (or common.UnmarshalJsonStr over the raw bytes) so JSON handling stays centralized.

  2. Silent drop of non-text inputs. The loop at Lines 144–148 only handles input_text, so any input_image / input_file parts in a Responses request are discarded without error. Claude's Messages API does support images, and the sibling Gemini adaptor (relay/channel/gemini/adaptor.go Lines 279–287) already maps input_image → image_url. Consider either mirroring Gemini's handling or returning an explicit "unsupported input type" error so clients aren't confused by a silently truncated prompt.

🔧 Suggested fix for the JSON wrapper usage
-import (
-	"encoding/json"
+import (
 	"errors"
 	"fmt"
 	"io"
 	"net/http"
 	"net/url"

 	"github.com/QuantumNous/new-api/dto"
+	"github.com/QuantumNous/new-api/common"
...
-		if err := json.Unmarshal(request.Instructions, &instrStr); err == nil && instrStr != "" {
+		if err := common.Unmarshal(request.Instructions, &instrStr); err == nil && instrStr != "" {

As per coding guidelines: "All JSON marshal/unmarshal operations MUST use wrapper functions in common/json.go (common.Marshal, common.Unmarshal, common.UnmarshalJsonStr, common.DecodeJson, common.GetJsonType). Do NOT directly import or call encoding/json in business code."

Also applies to: 112-162

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@relay/channel/claude/adaptor.go` at line 4, Replace direct use of
encoding/json and json.Unmarshal in relay/channel/claude/adaptor.go with the
repo wrappers (use common.Unmarshal or common.UnmarshalJsonStr as appropriate)
to centralize JSON handling (replace the import and the json.Unmarshal call
around the code that parses Responses at the json.Unmarshal site); additionally
update the request-parts loop that only handles input_text (the loop handling
input_text at Lines ~144–148) to either map input_image/input_file to the same
image_url field as the Gemini adaptor does (see relay/channel/gemini/adaptor.go
mapping of input_image → image_url) or return a clear "unsupported input type"
error so non-text parts are not silently dropped. Ensure you reference the
parsing function/variable names used in this file when making the changes so the
correct unmarshalling and part-mapping logic is updated.

"errors"
"fmt"
"io"
Expand All @@ -14,6 +15,7 @@ import (
"github.com/QuantumNous/new-api/types"

"github.com/gin-gonic/gin"
"github.com/samber/lo"
)

type Adaptor struct {
Expand Down Expand Up @@ -108,8 +110,55 @@ func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.Rela
}

func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
// TODO implement me
return nil, errors.New("not implemented")
// Bridge Responses API to standard OpenAI Chat format, then pass through Claude converter.
oaiReq := &dto.GeneralOpenAIRequest{
Model: request.Model,
Stream: lo.ToPtr(false),
}

if request.MaxOutputTokens != nil {
oaiReq.MaxTokens = request.MaxOutputTokens
}
if request.Temperature != nil {
oaiReq.Temperature = request.Temperature
}
if request.TopP != nil {
oaiReq.TopP = request.TopP
}

// Instructions -> System Message
if len(request.Instructions) > 0 {
var instrStr string
if err := json.Unmarshal(request.Instructions, &instrStr); err == nil && instrStr != "" {
oaiReq.Messages = append(oaiReq.Messages, dto.Message{
Role: "system",
Content: instrStr,
})
}
}

// Input -> User Messages
if len(request.Input) > 0 {
inputs := request.ParseInput()
var contentParts []dto.MediaContent
for _, inp := range inputs {
if inp.Type == "input_text" {
contentParts = append(contentParts, dto.MediaContent{Type: "text", Text: inp.Text})
}
}
if len(contentParts) == 1 {
oaiReq.Messages = append(oaiReq.Messages, dto.Message{
Role: "user",
Content: contentParts[0].Text,
})
} else if len(contentParts) > 1 {
msg := dto.Message{Role: "user"}
msg.SetMediaContent(contentParts)
oaiReq.Messages = append(oaiReq.Messages, msg)
}
}

return a.ConvertOpenAIRequest(c, info, oaiReq)
}

func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
Expand Down
68 changes: 66 additions & 2 deletions relay/channel/gemini/adaptor.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package gemini

import (
"encoding/json"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Use common.Unmarshal instead of encoding/json.

The encoding/json import (Line 4) and json.Unmarshal on Line 266 bypass the repo-mandated JSON wrappers. Please switch to common.Unmarshal and drop the encoding/json import if it becomes unused.

-import (
-	"encoding/json"
...
-		if err := json.Unmarshal(request.Instructions, &instrStr); err == nil && instrStr != "" {
+		if err := common.Unmarshal(request.Instructions, &instrStr); err == nil && instrStr != "" {

As per coding guidelines: "All JSON marshal/unmarshal operations MUST use wrapper functions in common/json.go (common.Marshal, common.Unmarshal, common.UnmarshalJsonStr, common.DecodeJson, common.GetJsonType). Do NOT directly import or call encoding/json in business code."

Also applies to: 264-272

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@relay/channel/gemini/adaptor.go` at line 4, The file imports encoding/json
and calls json.Unmarshal (around the code handling Gemini responses near the
json.Unmarshal call at Line ~266); replace that usage with the repo wrapper
common.Unmarshal and remove the encoding/json import if it becomes unused:
locate the json.Unmarshal invocation in adaptor.go (the Gemini adaptor parsing
path), change it to call common.Unmarshal with the same target variable, handle
the returned error the same way, and drop the encoding/json import from the
import block so all JSON operations use common.Unmarshal per the repo guideline.

"errors"
"fmt"
"io"
Expand Down Expand Up @@ -161,6 +162,11 @@ func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
}

action := "generateContent"
if info.RelayMode == constant.RelayModeResponses {
// Force non-streaming for Gemini via New API for stability with Responses API.
info.IsStream = false
}

if info.IsStream {
action = "streamGenerateContent?alt=sse"
if info.RelayMode == constant.RelayModeGemini {
Expand Down Expand Up @@ -238,15 +244,73 @@ func (a *Adaptor) ConvertEmbeddingRequest(c *gin.Context, info *relaycommon.Rela
}

func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
// TODO implement me
return nil, errors.New("not implemented")
// Bridge Responses API to standard OpenAI Chat format
oaiReq := &dto.GeneralOpenAIRequest{
Model: request.Model,
Stream: lo.ToPtr(false),
}

if request.MaxOutputTokens != nil {
oaiReq.MaxTokens = request.MaxOutputTokens
}
if request.Temperature != nil {
oaiReq.Temperature = request.Temperature
}
if request.TopP != nil {
oaiReq.TopP = request.TopP
}

// Convert instructions into a system message
if len(request.Instructions) > 0 {
var instrStr string
if err := json.Unmarshal(request.Instructions, &instrStr); err == nil && instrStr != "" {
oaiReq.Messages = append(oaiReq.Messages, dto.Message{
Role: "system",
Content: instrStr,
})
}
}

// Convert input into user messages
if len(request.Input) > 0 {
inputs := request.ParseInput()
var contentParts []dto.MediaContent
for _, inp := range inputs {
switch inp.Type {
case "input_text":
contentParts = append(contentParts, dto.MediaContent{Type: "text", Text: inp.Text})
case "input_image":
contentParts = append(contentParts, dto.MediaContent{
Type: "image_url",
ImageUrl: &dto.MessageImageUrl{Url: inp.ImageUrl},
})
}
}
if len(contentParts) == 1 && contentParts[0].Type == "text" {
oaiReq.Messages = append(oaiReq.Messages, dto.Message{
Role: "user",
Content: contentParts[0].Text,
})
} else if len(contentParts) > 0 {
msg := dto.Message{Role: "user"}
msg.SetMediaContent(contentParts)
oaiReq.Messages = append(oaiReq.Messages, msg)
}
}

return a.ConvertOpenAIRequest(c, info, oaiReq)
}

func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, requestBody io.Reader) (any, error) {
return channel.DoApiRequest(a, c, info, requestBody)
}

func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
// Force non-streaming for Responses API stability
if info.RelayMode == constant.RelayModeResponses {
info.IsStream = false
}

if info.RelayMode == constant.RelayModeGemini {
if strings.Contains(info.RequestURLPath, ":embedContent") ||
strings.Contains(info.RequestURLPath, ":batchEmbedContents") {
Expand Down
65 changes: 55 additions & 10 deletions relay/channel/zhipu/adaptor.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package zhipu

import (
"encoding/json"

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🛠️ Refactor suggestion | 🟠 Major

Use common.Unmarshal instead of encoding/json.

The encoding/json import (Line 4) and json.Unmarshal on Line 103 violate the repo JSON-wrapper guideline. Replace with common.Unmarshal.

-		if err := json.Unmarshal(request.Instructions, &instrStr); err == nil && instrStr != "" {
+		if err := common.Unmarshal(request.Instructions, &instrStr); err == nil && instrStr != "" {

As per coding guidelines: "All JSON marshal/unmarshal operations MUST use wrapper functions in common/json.go (common.Marshal, common.Unmarshal, common.UnmarshalJsonStr, common.DecodeJson, common.GetJsonType). Do NOT directly import or call encoding/json in business code."

Also applies to: 101-109

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@relay/channel/zhipu/adaptor.go` at line 4, Replace direct use of
encoding/json with the repo JSON wrapper: remove the "encoding/json" import and
replace calls to json.Unmarshal (and any other direct json.* calls in
adaptor.go, e.g., the json.Unmarshal usage around line 103) with
common.Unmarshal; update the import to include the common package and pass the
same byte slice or string and target struct to common.Unmarshal so the file uses
common.Unmarshal (and other common.* wrappers if needed) instead of
encoding/json.

"errors"
"fmt"
"io"
Expand Down Expand Up @@ -43,10 +44,9 @@ func (a *Adaptor) Init(info *relaycommon.RelayInfo) {
}

func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
// Force non-streaming for GLM via New API for stability with Responses API.
info.IsStream = false
method := "invoke"
if info.IsStream {
method = "sse-invoke"
}
return fmt.Sprintf("%s/api/paas/v3/model-api/%s/%s", info.ChannelBaseUrl, info.UpstreamModelName, method), nil
}
Comment on lines 46 to 51

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Critical regression: streaming unconditionally disabled for all Zhipu v3 requests, not just Responses mode.

GetRequestURL (Lines 46–51) and DoResponse (Lines 135–140) both set info.IsStream = false unconditionally. The previous implementation selected between sse-invoke (streaming) and invoke (non-streaming) based on info.IsStream, and DoResponse dispatched to zhipuStreamHandler vs zhipuHandler accordingly. As written, any user calling /v1/chat/completions with stream: true on a Zhipu channel will now silently get a non-streaming response — a breaking behavior change unrelated to the Responses API feature.

The sibling Gemini adaptor (relay/channel/gemini/adaptor.go Lines 165–168 and 310–312) correctly gates this behind info.RelayMode == constant.RelayModeResponses. Please do the same here:

 func (a *Adaptor) GetRequestURL(info *relaycommon.RelayInfo) (string, error) {
-	// Force non-streaming for GLM via New API for stability with Responses API.
-	info.IsStream = false
-	method := "invoke"
+	// Force non-streaming for GLM via New API for stability with Responses API.
+	if info.RelayMode == constant.RelayModeResponses {
+		info.IsStream = false
+	}
+	method := "invoke"
+	if info.IsStream {
+		method = "sse-invoke"
+	}
 	return fmt.Sprintf("%s/api/paas/v3/model-api/%s/%s", info.ChannelBaseUrl, info.UpstreamModelName, method), nil
 }
 func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
-	// Force non-streaming handler
-	info.IsStream = false
-	usage, err = zhipuHandler(c, info, resp)
+	if info.RelayMode == constant.RelayModeResponses {
+		info.IsStream = false
+	}
+	if info.IsStream {
+		usage, err = zhipuStreamHandler(c, info, resp)
+	} else {
+		usage, err = zhipuHandler(c, info, resp)
+	}
 	return
 }

You'll need to add the relay/constant import. Also applies symmetrically to relay/channel/zhipu_4v/adaptor.go (per the PR summary) — please audit that file for the same pattern.

Also applies to: 135-140

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@relay/channel/zhipu/adaptor.go` around lines 46 - 51, GetRequestURL and
DoResponse are unconditionally forcing info.IsStream = false which breaks
streaming for Zhipu channels; change both places to only set info.IsStream =
false when info.RelayMode == constant.RelayModeResponses (mirror Gemini adaptor
logic), import relay/constant, and restore the conditional dispatch in
DoResponse to call zhipuStreamHandler when info.IsStream is true and
zhipuHandler when false; apply the same fix/audit to
relay/channel/zhipu_4v/adaptor.go to ensure streaming remains enabled for
non-Responses modes.


Expand Down Expand Up @@ -81,16 +81,61 @@ func (a *Adaptor) DoRequest(c *gin.Context, info *relaycommon.RelayInfo, request
}

func (a *Adaptor) ConvertOpenAIResponsesRequest(c *gin.Context, info *relaycommon.RelayInfo, request dto.OpenAIResponsesRequest) (any, error) {
// TODO implement me
return nil, errors.New("not implemented")
// Bridge Responses API to standard OpenAI Chat format
oaiReq := &dto.GeneralOpenAIRequest{
Model: request.Model,
Stream: lo.ToPtr(false),
}

if request.MaxOutputTokens != nil {
oaiReq.MaxTokens = request.MaxOutputTokens
}
if request.Temperature != nil {
oaiReq.Temperature = request.Temperature
}
if request.TopP != nil {
oaiReq.TopP = request.TopP
}

// Instructions -> System Message
if len(request.Instructions) > 0 {
var instrStr string
if err := json.Unmarshal(request.Instructions, &instrStr); err == nil && instrStr != "" {
oaiReq.Messages = append(oaiReq.Messages, dto.Message{
Role: "system",
Content: instrStr,
})
}
}

// Input -> User Messages
if len(request.Input) > 0 {
inputs := request.ParseInput()
var contentParts []dto.MediaContent
for _, inp := range inputs {
if inp.Type == "input_text" {
contentParts = append(contentParts, dto.MediaContent{Type: "text", Text: inp.Text})
}
}
if len(contentParts) == 1 {
oaiReq.Messages = append(oaiReq.Messages, dto.Message{
Role: "user",
Content: contentParts[0].Text,
})
} else if len(contentParts) > 1 {
msg := dto.Message{Role: "user"}
msg.SetMediaContent(contentParts)
oaiReq.Messages = append(oaiReq.Messages, msg)
}
}

return a.ConvertOpenAIRequest(c, info, oaiReq)
}

func (a *Adaptor) DoResponse(c *gin.Context, resp *http.Response, info *relaycommon.RelayInfo) (usage any, err *types.NewAPIError) {
if info.IsStream {
usage, err = zhipuStreamHandler(c, info, resp)
} else {
usage, err = zhipuHandler(c, info, resp)
}
// Force non-streaming handler
info.IsStream = false
usage, err = zhipuHandler(c, info, resp)
return
}

Expand Down
Loading