2023-04-23 10:24:11 +00:00
|
|
|
package controller
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"one-api/common"
|
2023-07-15 11:06:51 +00:00
|
|
|
"strconv"
|
2023-04-25 12:27:53 +00:00
|
|
|
"strings"
|
2023-07-15 04:03:23 +00:00
|
|
|
|
|
|
|
"github.com/gin-gonic/gin"
|
2023-04-23 10:24:11 +00:00
|
|
|
)
|
|
|
|
|
2023-04-28 08:58:55 +00:00
|
|
|
type Message struct {
|
2023-05-19 03:07:17 +00:00
|
|
|
Role string `json:"role"`
|
2023-11-19 10:38:54 +00:00
|
|
|
Content any `json:"content"`
|
2023-05-19 03:07:17 +00:00
|
|
|
Name *string `json:"name,omitempty"`
|
2023-04-28 08:58:55 +00:00
|
|
|
}
|
|
|
|
|
2023-11-19 10:38:54 +00:00
|
|
|
type ImageURL struct {
|
|
|
|
Url string `json:"url,omitempty"`
|
|
|
|
Detail string `json:"detail,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type TextContent struct {
|
|
|
|
Type string `json:"type,omitempty"`
|
|
|
|
Text string `json:"text,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type ImageContent struct {
|
|
|
|
Type string `json:"type,omitempty"`
|
|
|
|
ImageURL *ImageURL `json:"image_url,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m Message) StringContent() string {
|
|
|
|
content, ok := m.Content.(string)
|
|
|
|
if ok {
|
|
|
|
return content
|
|
|
|
}
|
|
|
|
contentList, ok := m.Content.([]any)
|
|
|
|
if ok {
|
|
|
|
var contentStr string
|
|
|
|
for _, contentItem := range contentList {
|
|
|
|
contentMap, ok := contentItem.(map[string]any)
|
|
|
|
if !ok {
|
|
|
|
continue
|
|
|
|
}
|
|
|
|
if contentMap["type"] == "text" {
|
|
|
|
if subStr, ok := contentMap["text"].(string); ok {
|
|
|
|
contentStr += subStr
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return contentStr
|
|
|
|
}
|
|
|
|
return ""
|
|
|
|
}
|
|
|
|
|
2023-06-08 06:54:02 +00:00
|
|
|
const (
|
|
|
|
RelayModeUnknown = iota
|
|
|
|
RelayModeChatCompletions
|
|
|
|
RelayModeCompletions
|
|
|
|
RelayModeEmbeddings
|
2023-06-25 03:46:23 +00:00
|
|
|
RelayModeModerations
|
2023-06-19 02:28:55 +00:00
|
|
|
RelayModeImagesGenerations
|
2023-06-25 03:46:23 +00:00
|
|
|
RelayModeEdits
|
2023-11-17 13:18:51 +00:00
|
|
|
RelayModeAudioSpeech
|
|
|
|
RelayModeAudioTranscription
|
|
|
|
RelayModeAudioTranslation
|
2023-06-08 06:54:02 +00:00
|
|
|
)
|
|
|
|
|
2023-05-21 06:26:59 +00:00
|
|
|
// https://platform.openai.com/docs/api-reference/chat
|
|
|
|
|
2023-11-19 09:50:30 +00:00
|
|
|
type ResponseFormat struct {
|
|
|
|
Type string `json:"type,omitempty"`
|
|
|
|
}
|
|
|
|
|
2023-05-21 06:26:59 +00:00
|
|
|
type GeneralOpenAIRequest struct {
|
2023-11-19 09:50:30 +00:00
|
|
|
Model string `json:"model,omitempty"`
|
|
|
|
Messages []Message `json:"messages,omitempty"`
|
|
|
|
Prompt any `json:"prompt,omitempty"`
|
|
|
|
Stream bool `json:"stream,omitempty"`
|
|
|
|
MaxTokens int `json:"max_tokens,omitempty"`
|
|
|
|
Temperature float64 `json:"temperature,omitempty"`
|
|
|
|
TopP float64 `json:"top_p,omitempty"`
|
|
|
|
N int `json:"n,omitempty"`
|
|
|
|
Input any `json:"input,omitempty"`
|
|
|
|
Instruction string `json:"instruction,omitempty"`
|
|
|
|
Size string `json:"size,omitempty"`
|
|
|
|
Functions any `json:"functions,omitempty"`
|
|
|
|
FrequencyPenalty float64 `json:"frequency_penalty,omitempty"`
|
|
|
|
PresencePenalty float64 `json:"presence_penalty,omitempty"`
|
|
|
|
ResponseFormat *ResponseFormat `json:"response_format,omitempty"`
|
|
|
|
Seed float64 `json:"seed,omitempty"`
|
|
|
|
Tools any `json:"tools,omitempty"`
|
|
|
|
ToolChoice any `json:"tool_choice,omitempty"`
|
|
|
|
User string `json:"user,omitempty"`
|
2023-05-21 06:26:59 +00:00
|
|
|
}
|
|
|
|
|
2023-09-03 14:12:35 +00:00
|
|
|
func (r GeneralOpenAIRequest) ParseInput() []string {
|
|
|
|
if r.Input == nil {
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
var input []string
|
|
|
|
switch r.Input.(type) {
|
|
|
|
case string:
|
|
|
|
input = []string{r.Input.(string)}
|
|
|
|
case []any:
|
|
|
|
input = make([]string, 0, len(r.Input.([]any)))
|
|
|
|
for _, item := range r.Input.([]any) {
|
|
|
|
if str, ok := item.(string); ok {
|
|
|
|
input = append(input, str)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|
|
|
|
return input
|
|
|
|
}
|
|
|
|
|
2023-05-15 02:48:52 +00:00
|
|
|
type ChatRequest struct {
|
2023-05-16 08:22:25 +00:00
|
|
|
Model string `json:"model"`
|
|
|
|
Messages []Message `json:"messages"`
|
|
|
|
MaxTokens int `json:"max_tokens"`
|
2023-05-15 02:48:52 +00:00
|
|
|
}
|
|
|
|
|
2023-04-28 08:58:55 +00:00
|
|
|
type TextRequest struct {
|
2023-05-16 08:18:35 +00:00
|
|
|
Model string `json:"model"`
|
|
|
|
Messages []Message `json:"messages"`
|
|
|
|
Prompt string `json:"prompt"`
|
|
|
|
MaxTokens int `json:"max_tokens"`
|
2023-04-28 08:58:55 +00:00
|
|
|
//Stream bool `json:"stream"`
|
|
|
|
}
|
|
|
|
|
2023-11-17 12:03:16 +00:00
|
|
|
// ImageRequest docs: https://platform.openai.com/docs/api-reference/images/create
|
2023-07-15 04:30:06 +00:00
|
|
|
type ImageRequest struct {
|
2023-11-17 12:03:16 +00:00
|
|
|
Model string `json:"model"`
|
|
|
|
Prompt string `json:"prompt" binding:"required"`
|
2023-12-03 09:43:30 +00:00
|
|
|
N int `json:"n,omitempty"`
|
|
|
|
Size string `json:"size,omitempty"`
|
|
|
|
Quality string `json:"quality,omitempty"`
|
|
|
|
ResponseFormat string `json:"response_format,omitempty"`
|
|
|
|
Style string `json:"style,omitempty"`
|
|
|
|
User string `json:"user,omitempty"`
|
2023-07-15 04:30:06 +00:00
|
|
|
}
|
|
|
|
|
2023-12-10 10:39:14 +00:00
|
|
|
type WhisperJSONResponse struct {
|
2023-08-27 07:28:23 +00:00
|
|
|
Text string `json:"text,omitempty"`
|
|
|
|
}
|
|
|
|
|
2023-12-10 10:39:14 +00:00
|
|
|
type WhisperVerboseJSONResponse struct {
|
|
|
|
Task string `json:"task,omitempty"`
|
|
|
|
Language string `json:"language,omitempty"`
|
|
|
|
Duration float64 `json:"duration,omitempty"`
|
|
|
|
Text string `json:"text,omitempty"`
|
|
|
|
Segments []Segment `json:"segments,omitempty"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type Segment struct {
|
|
|
|
Id int `json:"id"`
|
|
|
|
Seek int `json:"seek"`
|
|
|
|
Start float64 `json:"start"`
|
|
|
|
End float64 `json:"end"`
|
|
|
|
Text string `json:"text"`
|
|
|
|
Tokens []int `json:"tokens"`
|
|
|
|
Temperature float64 `json:"temperature"`
|
|
|
|
AvgLogprob float64 `json:"avg_logprob"`
|
|
|
|
CompressionRatio float64 `json:"compression_ratio"`
|
|
|
|
NoSpeechProb float64 `json:"no_speech_prob"`
|
|
|
|
}
|
|
|
|
|
2023-11-17 13:18:51 +00:00
|
|
|
type TextToSpeechRequest struct {
|
|
|
|
Model string `json:"model" binding:"required"`
|
|
|
|
Input string `json:"input" binding:"required"`
|
|
|
|
Voice string `json:"voice" binding:"required"`
|
|
|
|
Speed float64 `json:"speed"`
|
|
|
|
ResponseFormat string `json:"response_format"`
|
|
|
|
}
|
|
|
|
|
2023-04-28 08:58:55 +00:00
|
|
|
type Usage struct {
|
|
|
|
PromptTokens int `json:"prompt_tokens"`
|
|
|
|
CompletionTokens int `json:"completion_tokens"`
|
|
|
|
TotalTokens int `json:"total_tokens"`
|
|
|
|
}
|
|
|
|
|
2023-05-15 02:48:52 +00:00
|
|
|
type OpenAIError struct {
|
|
|
|
Message string `json:"message"`
|
|
|
|
Type string `json:"type"`
|
|
|
|
Param string `json:"param"`
|
2023-06-11 01:49:57 +00:00
|
|
|
Code any `json:"code"`
|
2023-05-15 02:48:52 +00:00
|
|
|
}
|
|
|
|
|
2023-05-18 03:11:15 +00:00
|
|
|
type OpenAIErrorWithStatusCode struct {
|
|
|
|
OpenAIError
|
|
|
|
StatusCode int `json:"status_code"`
|
|
|
|
}
|
|
|
|
|
2023-04-28 08:58:55 +00:00
|
|
|
type TextResponse struct {
|
2023-08-06 09:40:31 +00:00
|
|
|
Choices []OpenAITextResponseChoice `json:"choices"`
|
|
|
|
Usage `json:"usage"`
|
|
|
|
Error OpenAIError `json:"error"`
|
2023-04-28 08:58:55 +00:00
|
|
|
}
|
|
|
|
|
2023-07-22 08:18:03 +00:00
|
|
|
type OpenAITextResponseChoice struct {
|
|
|
|
Index int `json:"index"`
|
|
|
|
Message `json:"message"`
|
|
|
|
FinishReason string `json:"finish_reason"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type OpenAITextResponse struct {
|
|
|
|
Id string `json:"id"`
|
|
|
|
Object string `json:"object"`
|
|
|
|
Created int64 `json:"created"`
|
|
|
|
Choices []OpenAITextResponseChoice `json:"choices"`
|
|
|
|
Usage `json:"usage"`
|
|
|
|
}
|
|
|
|
|
2023-07-29 04:15:07 +00:00
|
|
|
type OpenAIEmbeddingResponseItem struct {
|
|
|
|
Object string `json:"object"`
|
|
|
|
Index int `json:"index"`
|
|
|
|
Embedding []float64 `json:"embedding"`
|
|
|
|
}
|
|
|
|
|
|
|
|
type OpenAIEmbeddingResponse struct {
|
|
|
|
Object string `json:"object"`
|
|
|
|
Data []OpenAIEmbeddingResponseItem `json:"data"`
|
|
|
|
Model string `json:"model"`
|
|
|
|
Usage `json:"usage"`
|
|
|
|
}
|
|
|
|
|
2023-07-15 04:30:06 +00:00
|
|
|
type ImageResponse struct {
|
|
|
|
Created int `json:"created"`
|
|
|
|
Data []struct {
|
|
|
|
Url string `json:"url"`
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-07-22 08:18:03 +00:00
|
|
|
type ChatCompletionsStreamResponseChoice struct {
|
|
|
|
Delta struct {
|
|
|
|
Content string `json:"content"`
|
|
|
|
} `json:"delta"`
|
2023-08-12 03:04:53 +00:00
|
|
|
FinishReason *string `json:"finish_reason"`
|
2023-07-22 08:18:03 +00:00
|
|
|
}
|
|
|
|
|
2023-06-08 06:54:02 +00:00
|
|
|
type ChatCompletionsStreamResponse struct {
|
2023-07-22 08:18:03 +00:00
|
|
|
Id string `json:"id"`
|
|
|
|
Object string `json:"object"`
|
|
|
|
Created int64 `json:"created"`
|
|
|
|
Model string `json:"model"`
|
|
|
|
Choices []ChatCompletionsStreamResponseChoice `json:"choices"`
|
2023-04-28 08:58:55 +00:00
|
|
|
}
|
|
|
|
|
2023-06-08 06:54:02 +00:00
|
|
|
type CompletionsStreamResponse struct {
|
|
|
|
Choices []struct {
|
|
|
|
Text string `json:"text"`
|
|
|
|
FinishReason string `json:"finish_reason"`
|
|
|
|
} `json:"choices"`
|
|
|
|
}
|
|
|
|
|
2023-04-23 10:24:11 +00:00
|
|
|
func Relay(c *gin.Context) {
|
2023-06-08 06:54:02 +00:00
|
|
|
relayMode := RelayModeUnknown
|
|
|
|
if strings.HasPrefix(c.Request.URL.Path, "/v1/chat/completions") {
|
|
|
|
relayMode = RelayModeChatCompletions
|
|
|
|
} else if strings.HasPrefix(c.Request.URL.Path, "/v1/completions") {
|
|
|
|
relayMode = RelayModeCompletions
|
|
|
|
} else if strings.HasPrefix(c.Request.URL.Path, "/v1/embeddings") {
|
|
|
|
relayMode = RelayModeEmbeddings
|
2023-07-15 04:03:23 +00:00
|
|
|
} else if strings.HasSuffix(c.Request.URL.Path, "embeddings") {
|
|
|
|
relayMode = RelayModeEmbeddings
|
2023-06-11 01:37:36 +00:00
|
|
|
} else if strings.HasPrefix(c.Request.URL.Path, "/v1/moderations") {
|
2023-06-25 03:46:23 +00:00
|
|
|
relayMode = RelayModeModerations
|
2023-06-19 02:28:55 +00:00
|
|
|
} else if strings.HasPrefix(c.Request.URL.Path, "/v1/images/generations") {
|
|
|
|
relayMode = RelayModeImagesGenerations
|
2023-06-25 03:46:23 +00:00
|
|
|
} else if strings.HasPrefix(c.Request.URL.Path, "/v1/edits") {
|
|
|
|
relayMode = RelayModeEdits
|
2023-11-17 13:18:51 +00:00
|
|
|
} else if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/speech") {
|
|
|
|
relayMode = RelayModeAudioSpeech
|
2023-11-19 08:11:39 +00:00
|
|
|
} else if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/transcriptions") {
|
2023-11-17 13:18:51 +00:00
|
|
|
relayMode = RelayModeAudioTranscription
|
2023-11-19 08:11:39 +00:00
|
|
|
} else if strings.HasPrefix(c.Request.URL.Path, "/v1/audio/translations") {
|
2023-11-17 13:18:51 +00:00
|
|
|
relayMode = RelayModeAudioTranslation
|
2023-06-19 02:28:55 +00:00
|
|
|
}
|
|
|
|
var err *OpenAIErrorWithStatusCode
|
|
|
|
switch relayMode {
|
|
|
|
case RelayModeImagesGenerations:
|
|
|
|
err = relayImageHelper(c, relayMode)
|
2023-11-17 13:18:51 +00:00
|
|
|
case RelayModeAudioSpeech:
|
|
|
|
fallthrough
|
|
|
|
case RelayModeAudioTranslation:
|
|
|
|
fallthrough
|
|
|
|
case RelayModeAudioTranscription:
|
2023-08-27 07:28:23 +00:00
|
|
|
err = relayAudioHelper(c, relayMode)
|
2023-06-19 02:28:55 +00:00
|
|
|
default:
|
2023-06-19 07:00:22 +00:00
|
|
|
err = relayTextHelper(c, relayMode)
|
2023-06-08 06:54:02 +00:00
|
|
|
}
|
2023-04-28 09:11:57 +00:00
|
|
|
if err != nil {
|
2023-09-17 07:39:46 +00:00
|
|
|
requestId := c.GetString(common.RequestIdKey)
|
2023-07-15 11:06:51 +00:00
|
|
|
retryTimesStr := c.Query("retry")
|
|
|
|
retryTimes, _ := strconv.Atoi(retryTimesStr)
|
|
|
|
if retryTimesStr == "" {
|
|
|
|
retryTimes = common.RetryTimes
|
|
|
|
}
|
|
|
|
if retryTimes > 0 {
|
|
|
|
c.Redirect(http.StatusTemporaryRedirect, fmt.Sprintf("%s?retry=%d", c.Request.URL.Path, retryTimes-1))
|
|
|
|
} else {
|
|
|
|
if err.StatusCode == http.StatusTooManyRequests {
|
2023-08-12 02:20:54 +00:00
|
|
|
err.OpenAIError.Message = "当前分组上游负载已饱和,请稍后再试"
|
2023-07-15 11:06:51 +00:00
|
|
|
}
|
2023-09-17 07:39:46 +00:00
|
|
|
err.OpenAIError.Message = common.MessageWithRequestId(err.OpenAIError.Message, requestId)
|
2023-07-15 11:06:51 +00:00
|
|
|
c.JSON(err.StatusCode, gin.H{
|
|
|
|
"error": err.OpenAIError,
|
|
|
|
})
|
2023-05-18 07:27:15 +00:00
|
|
|
}
|
2023-05-17 12:20:48 +00:00
|
|
|
channelId := c.GetInt("channel_id")
|
2023-09-17 07:39:46 +00:00
|
|
|
common.LogError(c.Request.Context(), fmt.Sprintf("relay error (channel #%d): %s", channelId, err.Message))
|
2023-05-21 12:58:00 +00:00
|
|
|
// https://platform.openai.com/docs/guides/error-codes/api-errors
|
2023-08-26 04:05:18 +00:00
|
|
|
if shouldDisableChannel(&err.OpenAIError, err.StatusCode) {
|
2023-05-15 09:34:09 +00:00
|
|
|
channelId := c.GetInt("channel_id")
|
|
|
|
channelName := c.GetString("channel_name")
|
2023-05-18 03:11:15 +00:00
|
|
|
disableChannel(channelId, channelName, err.Message)
|
2023-05-15 09:34:09 +00:00
|
|
|
}
|
2023-04-28 09:11:57 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2023-04-28 08:58:55 +00:00
|
|
|
func RelayNotImplemented(c *gin.Context) {
|
2023-05-18 03:11:15 +00:00
|
|
|
err := OpenAIError{
|
|
|
|
Message: "API not implemented",
|
|
|
|
Type: "one_api_error",
|
|
|
|
Param: "",
|
|
|
|
Code: "api_not_implemented",
|
|
|
|
}
|
2023-06-23 14:59:44 +00:00
|
|
|
c.JSON(http.StatusNotImplemented, gin.H{
|
2023-05-18 03:11:15 +00:00
|
|
|
"error": err,
|
2023-04-28 08:58:55 +00:00
|
|
|
})
|
|
|
|
}
|
2023-06-17 01:46:07 +00:00
|
|
|
|
|
|
|
func RelayNotFound(c *gin.Context) {
|
|
|
|
err := OpenAIError{
|
2023-08-11 11:53:01 +00:00
|
|
|
Message: fmt.Sprintf("Invalid URL (%s %s)", c.Request.Method, c.Request.URL.Path),
|
|
|
|
Type: "invalid_request_error",
|
2023-06-17 01:46:07 +00:00
|
|
|
Param: "",
|
2023-08-11 11:53:01 +00:00
|
|
|
Code: "",
|
2023-06-17 01:46:07 +00:00
|
|
|
}
|
2023-06-23 14:59:44 +00:00
|
|
|
c.JSON(http.StatusNotFound, gin.H{
|
2023-06-17 01:46:07 +00:00
|
|
|
"error": err,
|
|
|
|
})
|
|
|
|
}
|