Skip to content

Commit

Permalink
feat: add gpt-4-vision-preview transhipment format support
Browse files Browse the repository at this point in the history
  • Loading branch information
zmh-program committed Dec 28, 2023
1 parent a1f4845 commit 61c9177
Show file tree
Hide file tree
Showing 8 changed files with 333 additions and 256 deletions.
2 changes: 2 additions & 0 deletions app/src/admin/channel.ts
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,7 @@ export const ChannelInfos: Record<string, ChannelInfo> = {
"gpt-4-32k",
"gpt-4-32k-0314",
"gpt-4-32k-0613",
"dalle",
"dall-e-2",
"dall-e-3",
],
Expand Down Expand Up @@ -87,6 +88,7 @@ export const ChannelInfos: Record<string, ChannelInfo> = {
"gpt-4-32k",
"gpt-4-32k-0314",
"gpt-4-32k-0613",
"dalle",
"dall-e-2",
"dall-e-3",
],
Expand Down
4 changes: 2 additions & 2 deletions app/src/components/admin/ChargeWidget.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -407,10 +407,10 @@ function ChargeTable({ data, dispatch, onRefresh }: ChargeTableProps) {
<pre>{charge.models.join("\n")}</pre>
</TableCell>
<TableCell>
{charge.input === 0 ? 0 : charge.input.toFixed(2)}
{charge.input === 0 ? 0 : charge.input.toFixed(3)}
</TableCell>
<TableCell>
{charge.output === 0 ? 0 : charge.output.toFixed(2)}
{charge.output === 0 ? 0 : charge.output.toFixed(3)}
</TableCell>
<TableCell>{t(String(charge.anonymous))}</TableCell>
<TableCell>
Expand Down
2 changes: 1 addition & 1 deletion app/src/conf.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,7 @@ export const supportModels: Model[] = [
name: "DALLE 3",
free: false,
auth: true,
tag: ["free", "official", "image-generation"],
tag: ["official", "image-generation"],
},

{
Expand Down
3 changes: 2 additions & 1 deletion globals/variables.go
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ const (
GPT432k = "gpt-4-32k"
GPT432k0314 = "gpt-4-32k-0314"
GPT432k0613 = "gpt-4-32k-0613"
Dalle = "dalle"
Dalle2 = "dall-e-2"
Dalle3 = "dall-e-3"
Claude1 = "claude-1"
Expand Down Expand Up @@ -113,7 +114,7 @@ func IsGPT4NativeModel(model string) bool {
}

func IsDalleModel(model string) bool {
return model == Dalle2 || model == Dalle3
return model == Dalle || model == Dalle2 || model == Dalle3
}

func IsClaude100KModel(model string) bool {
Expand Down
196 changes: 196 additions & 0 deletions manager/chat_completions.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,196 @@
package manager

import (
"chat/adapter"
"chat/addition/web"
"chat/admin"
"chat/auth"
"chat/channel"
"chat/globals"
"chat/utils"
"fmt"
"github.com/gin-gonic/gin"
"io"
"net/http"
"strings"
"time"
)

func TranshipmentAPI(c *gin.Context) {
username := utils.GetUserFromContext(c)
if username == "" {
abortWithErrorResponse(c, fmt.Errorf("access denied for invalid api key"), "authentication_error")
return
}

if utils.GetAgentFromContext(c) != "api" {
abortWithErrorResponse(c, fmt.Errorf("access denied for invalid agent"), "authentication_error")
return
}

var form TranshipmentForm
if err := c.ShouldBindJSON(&form); err != nil {
abortWithErrorResponse(c, fmt.Errorf("invalid request body: %s", err.Error()), "invalid_request_error")
return
}

db := utils.GetDBFromContext(c)
user := &auth.User{
Username: username,
}
id := utils.Md5Encrypt(username + form.Model + time.Now().String())
created := time.Now().Unix()

messages := transform(form.Messages)
if strings.HasPrefix(form.Model, "web-") {
suffix := strings.TrimPrefix(form.Model, "web-")

form.Model = suffix
messages = web.UsingWebNativeSegment(true, messages)
}

if strings.HasSuffix(form.Model, "-official") {
form.Model = strings.TrimSuffix(form.Model, "-official")
form.Official = true
}

check := auth.CanEnableModel(db, user, form.Model)
if !check {
sendErrorResponse(c, fmt.Errorf("quota exceeded"), "quota_exceeded_error")
return
}

if form.Stream {
sendStreamTranshipmentResponse(c, form, messages, id, created, user, false)
} else {
sendTranshipmentResponse(c, form, messages, id, created, user, false)
}
}

func GetChatProps(form TranshipmentForm, messages []globals.Message, buffer *utils.Buffer, plan bool) *adapter.ChatProps {
return &adapter.ChatProps{
Model: form.Model,
Message: messages,
Plan: plan,
Token: utils.Multi(form.MaxTokens == 0, 2500, form.MaxTokens),
PresencePenalty: form.PresencePenalty,
FrequencyPenalty: form.FrequencyPenalty,
RepetitionPenalty: form.RepetitionPenalty,
Temperature: form.Temperature,
TopP: form.TopP,
TopK: form.TopK,
Tools: form.Tools,
ToolChoice: form.ToolChoice,
Buffer: *buffer,
}
}

func sendTranshipmentResponse(c *gin.Context, form TranshipmentForm, messages []globals.Message, id string, created int64, user *auth.User, plan bool) {
db := utils.GetDBFromContext(c)
cache := utils.GetCacheFromContext(c)

buffer := utils.NewBuffer(form.Model, messages, channel.ChargeInstance.GetCharge(form.Model))
err := channel.NewChatRequest(auth.GetGroup(db, user), GetChatProps(form, messages, buffer, plan), func(data string) error {
buffer.Write(data)
return nil
})

admin.AnalysisRequest(form.Model, buffer, err)
if err != nil {
auth.RevertSubscriptionUsage(db, cache, user, form.Model)
globals.Warn(fmt.Sprintf("error from chat request api: %s (instance: %s, client: %s)", err, form.Model, c.ClientIP()))

sendErrorResponse(c, err)
return
}

CollectQuota(c, user, buffer, plan, err)
c.JSON(http.StatusOK, TranshipmentResponse{
Id: fmt.Sprintf("chatcmpl-%s", id),
Object: "chat.completion",
Created: created,
Model: form.Model,
Choices: []Choice{
{
Index: 0,
Message: globals.Message{Role: globals.Assistant, Content: buffer.ReadWithDefault(defaultMessage)},
FinishReason: "stop",
},
},
Usage: Usage{
PromptTokens: buffer.CountInputToken(),
CompletionTokens: buffer.CountOutputToken(),
TotalTokens: buffer.CountToken(),
},
Quota: utils.Multi[*float32](form.Official, nil, utils.ToPtr(buffer.GetQuota())),
})
}

func getStreamTranshipmentForm(id string, created int64, form TranshipmentForm, data string, buffer *utils.Buffer, end bool, err error) TranshipmentStreamResponse {
return TranshipmentStreamResponse{
Id: fmt.Sprintf("chatcmpl-%s", id),
Object: "chat.completion.chunk",
Created: created,
Model: form.Model,
Choices: []ChoiceDelta{
{
Index: 0,
Delta: globals.Message{
Role: globals.Assistant,
Content: data,
},
FinishReason: utils.Multi[interface{}](end, "stop", nil),
},
},
Usage: Usage{
PromptTokens: utils.MultiF(end, func() int { return buffer.CountInputToken() }, 0),
CompletionTokens: utils.MultiF(end, func() int { return buffer.CountOutputToken() }, 0),
TotalTokens: utils.MultiF(end, func() int { return buffer.CountToken() }, 0),
},
Quota: utils.Multi[*float32](form.Official, nil, utils.ToPtr(buffer.GetQuota())),
Error: err,
}
}

func sendStreamTranshipmentResponse(c *gin.Context, form TranshipmentForm, messages []globals.Message, id string, created int64, user *auth.User, plan bool) {
partial := make(chan TranshipmentStreamResponse)
db := utils.GetDBFromContext(c)
cache := utils.GetCacheFromContext(c)

go func() {
buffer := utils.NewBuffer(form.Model, messages, channel.ChargeInstance.GetCharge(form.Model))
err := channel.NewChatRequest(auth.GetGroup(db, user), GetChatProps(form, messages, buffer, plan), func(data string) error {
partial <- getStreamTranshipmentForm(id, created, form, buffer.Write(data), buffer, false, nil)
return nil
})

admin.AnalysisRequest(form.Model, buffer, err)
if err != nil {
auth.RevertSubscriptionUsage(db, cache, user, form.Model)
globals.Warn(fmt.Sprintf("error from chat request api: %s (instance: %s, client: %s)", err.Error(), form.Model, c.ClientIP()))
partial <- getStreamTranshipmentForm(id, created, form, err.Error(), buffer, true, err)
close(partial)
return
}

partial <- getStreamTranshipmentForm(id, created, form, "", buffer, true, nil)
CollectQuota(c, user, buffer, plan, err)
close(partial)
return
}()

c.Stream(func(w io.Writer) bool {
if resp, ok := <-partial; ok {
if resp.Error != nil {
sendErrorResponse(c, resp.Error)
return false
}

c.Render(-1, utils.NewEvent(resp))
return true
}

c.Render(-1, utils.NewEndEvent())
return false
})
}
1 change: 1 addition & 0 deletions manager/images.go
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
package manager
Loading

0 comments on commit 61c9177

Please sign in to comment.