Compare commits

..

1 Commits

Author SHA1 Message Date
dependabot[bot]
c1a73bbdca chore(deps): bump golang.org/x/crypto from 0.31.0 to 0.45.0
Bumps [golang.org/x/crypto](https://github.com/golang/crypto) from 0.31.0 to 0.45.0.
- [Commits](https://github.com/golang/crypto/compare/v0.31.0...v0.45.0)

---
updated-dependencies:
- dependency-name: golang.org/x/crypto
  dependency-version: 0.45.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2025-11-20 01:15:39 +00:00
29 changed files with 205 additions and 761 deletions

View File

@@ -1,23 +0,0 @@
package file
import (
"bytes"
"encoding/base64"
"net/http"
)
func GetFileFromUrl(url string) (mimeType string, data string, err error) {
resp, err := http.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
buffer := bytes.NewBuffer(nil)
_, err = buffer.ReadFrom(resp.Body)
if err != nil {
return
}
mimeType = resp.Header.Get("Content-Type")
data = base64.StdEncoding.EncodeToString(buffer.Bytes())
return
}

12
go.mod
View File

@@ -1,6 +1,6 @@
module github.com/songquanpeng/one-api
go 1.20
go 1.24.0
require (
cloud.google.com/go/iam v1.1.10
@@ -24,9 +24,9 @@ require (
github.com/pkoukk/tiktoken-go v0.1.7
github.com/smartystreets/goconvey v1.8.1
github.com/stretchr/testify v1.9.0
golang.org/x/crypto v0.31.0
golang.org/x/crypto v0.45.0
golang.org/x/image v0.18.0
golang.org/x/sync v0.10.0
golang.org/x/sync v0.18.0
google.golang.org/api v0.187.0
gorm.io/driver/mysql v1.5.6
gorm.io/driver/postgres v1.5.7
@@ -97,10 +97,10 @@ require (
go.opentelemetry.io/otel/metric v1.24.0 // indirect
go.opentelemetry.io/otel/trace v1.24.0 // indirect
golang.org/x/arch v0.8.0 // indirect
golang.org/x/net v0.26.0 // indirect
golang.org/x/net v0.47.0 // indirect
golang.org/x/oauth2 v0.21.0 // indirect
golang.org/x/sys v0.28.0 // indirect
golang.org/x/text v0.21.0 // indirect
golang.org/x/sys v0.38.0 // indirect
golang.org/x/text v0.31.0 // indirect
golang.org/x/time v0.5.0 // indirect
google.golang.org/genproto/googleapis/api v0.0.0-20240617180043-68d350f18fd4 // indirect
google.golang.org/genproto/googleapis/rpc v0.0.0-20240624140628-dc46fd24d27d // indirect

31
go.sum
View File

@@ -73,6 +73,7 @@ github.com/go-logr/logr v1.4.1/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ4
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-playground/assert/v2 v2.2.0 h1:JvknZsQTYeFEAhQwI4qEt9cyV5ONwRHC+lYKSsYSR8s=
github.com/go-playground/assert/v2 v2.2.0/go.mod h1:VDjEfimB/XKnb+ZQfWdccd7VUvScMdVu0Titje2rxJ4=
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
@@ -111,8 +112,10 @@ github.com/google/go-cmp v0.4.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/
github.com/google/go-cmp v0.5.0/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.5.3/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE=
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/gofuzz v1.2.0 h1:xRy4A+RhZaiKjJ1bPfwQ8sedCA+YS2YcCHW6ec7JMi0=
github.com/google/gofuzz v1.2.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
github.com/google/s2a-go v0.1.7 h1:60BLSyTrOV4/haCDW4zb1guZItoSq8foHCXrAnjBo/o=
github.com/google/s2a-go v0.1.7/go.mod h1:50CgR4k1jNlWBu4UfS4AcfhVe1r6pdZPygJ3R8F0Qdw=
github.com/google/uuid v1.1.2/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
@@ -157,6 +160,7 @@ github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuV
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
github.com/kr/pretty v0.3.0 h1:WgNl7dwNpEZ6jJ9k1snq4pZsg7DOEN8hP9Xw0Tsjwk0=
github.com/kr/pretty v0.3.0/go.mod h1:640gp4NfQd8pI5XOwp5fnNeVWj67G7CFk/SaSQn7NBk=
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
@@ -171,8 +175,11 @@ github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJ
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
github.com/nxadm/tail v1.4.8 h1:nPr65rt6Y5JFSKQO7qToXr7pePgD6Gwiw05lkbyAQTE=
github.com/nxadm/tail v1.4.8/go.mod h1:+ncqLTQzXmGhMZNUePPaPqPvBxHAIsmXswZKocGu+AU=
github.com/onsi/ginkgo v1.16.5 h1:8xi0RTUf59SOSfEtZMvwTvXYMzG4gV23XVHOZiXNtnE=
github.com/onsi/ginkgo v1.16.5/go.mod h1:+E8gABHa3K6zRBolWtd+ROzc/U5bkGt0FwiG042wbpU=
github.com/onsi/gomega v1.18.1 h1:M1GfJqGRrBrrGGsbxzV5dqM2U2ApXefZCQpkukxYRLE=
github.com/onsi/gomega v1.18.1/go.mod h1:0q+aL8jAiMXy9hbwj2mr5GziHiwhAIQpFmmtT5hitRs=
github.com/patrickmn/go-cache v2.1.0+incompatible h1:HRMgzkcYKYpi3C8ajMPV8OFXaaRUnok+kx1WdO15EQc=
github.com/patrickmn/go-cache v2.1.0+incompatible/go.mod h1:3Qf8kWWT7OJRJbdiICTKqZju1ZixQ/KpMGzzAfe6+WQ=
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
@@ -185,6 +192,7 @@ github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZb
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
github.com/prometheus/client_model v0.0.0-20190812154241-14fe0d1b01d4/go.mod h1:xMI15A0UPsDsEKsMN9yxemIoYk6Tm2C1GtYGdfGttqA=
github.com/rogpeppe/go-internal v1.8.0 h1:FCbCCtXNOY3UtUuHUYaghJg4y7Fd14rXifAYUAtL9R8=
github.com/rogpeppe/go-internal v1.8.0/go.mod h1:WmiCO8CzOY8rg0OYDC4/i/2WRWAB6poM+XZ2dLUbcbE=
github.com/smarty/assertions v1.15.0 h1:cR//PqUBUiQRakZWqBiFFQ9wb8emQGDb0HeGdqGByCY=
github.com/smarty/assertions v1.15.0/go.mod h1:yABtdzeQs6l1brC900WlRNwj6ZR55d7B+E8C6HtKdec=
github.com/smartystreets/goconvey v1.8.1 h1:qGjIddxOk4grTu9JPOU31tVfq3cNdBlNa5sSznIX1xY=
@@ -222,8 +230,8 @@ golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/crypto v0.0.0-20200622213623-75b288015ac9/go.mod h1:LzIPMQfyMNhhGPhUkYOs5KpL4U8rLKemX1yGLhDgUto=
golang.org/x/crypto v0.31.0 h1:ihbySMvVjLAeSH1IbfcRTkD/iNscyz8rGzjF/E5hV6U=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
golang.org/x/crypto v0.45.0 h1:jMBrvKuj23MTlT0bQEOBcAE0mjg8mK9RXFhRH6nyF3Q=
golang.org/x/crypto v0.45.0/go.mod h1:XTGrrkGJve7CYK7J8PEww4aY7gM3qMCElcJQ8n8JdX4=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/image v0.18.0 h1:jGzIakQa/ZXI1I0Fxvaa9W7yP25TqT6cHIHn+6CqvSQ=
golang.org/x/image v0.18.0/go.mod h1:4yyo5vMFQjVjUcVk4jEQcU9MGy/rulF5WvUILseCM2E=
@@ -236,28 +244,28 @@ golang.org/x/net v0.0.0-20190213061140-3a22650c66bd/go.mod h1:mL1N/T3taQHkDXs73r
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
golang.org/x/net v0.0.0-20201110031124-69a78807bb2b/go.mod h1:sp8m0HH+o8qH0wwXwYZr8TS3Oi6o0r6Gce1SSxlDquU=
golang.org/x/net v0.26.0 h1:soB7SVo0PWrY4vPW/+ay0jKDNScG2X9wFeYlXIvJsOQ=
golang.org/x/net v0.26.0/go.mod h1:5YKkiSynbBIh3p6iOc/vibscux0x38BZDkn8sCUPxHE=
golang.org/x/net v0.47.0 h1:Mx+4dIFzqraBXUugkia1OOvlD6LemFo1ALMHjrXDOhY=
golang.org/x/net v0.47.0/go.mod h1:/jNxtkgq5yWUGYkaZGqo27cfGZ1c5Nen03aYrrKpVRU=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.21.0 h1:tsimM75w1tF/uws5rbeHzIWxEqElMehnc+iW793zsZs=
golang.org/x/oauth2 v0.21.0/go.mod h1:XYTD2NtWslqkgxebSiOHnXEap4TF09sJSc7H1sXbhtI=
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.0.0-20190423024810-112230192c58/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.18.0 h1:kr88TuHDroi+UVf+0hZnirlk8o8T+4MrK6mr60WkH/I=
golang.org/x/sync v0.18.0/go.mod h1:9KTHXmSnoGruLpwFjVSX0lNNA75CykiMECbovNTZqGI=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190412213103-97732733099d/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.0.0-20200930185726-fdedc70b468f/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.38.0 h1:3yZWxaJjBmCWXqhN1qh02AkOnCQ1poK6oF+a7xWL6Gc=
golang.org/x/sys v0.38.0/go.mod h1:OgkHotnGiDImocRcuBABYBEXf8A9a87e/uXjp9XT3ks=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.3/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
golang.org/x/text v0.31.0 h1:aC8ghyu4JhP8VojJ2lEHBnochRno1sgL6nEi9WGFGMM=
golang.org/x/text v0.31.0/go.mod h1:tKRAlv61yKIjGGHX/4tP1LTbc13YSec1pxVEWXzfoeM=
golang.org/x/time v0.5.0 h1:o7cqy6amK/52YcAKIPlM3a+Fpj35zvRj2TP+e1xFSfk=
golang.org/x/time v0.5.0/go.mod h1:3BpzKBy/shNhVucY/MWOyx10tF3SFh9QdLuxbVysPQM=
golang.org/x/tools v0.0.0-20180917221912-90fa682c2a6e/go.mod h1:n7NCudcB/nEzxVGmLbDWY5pfWTLqBcC2KZ6jyYvM4mQ=
@@ -297,8 +305,11 @@ google.golang.org/protobuf v1.34.2 h1:6xV6lTsCfpGD21XK49h7MhtcApnLqkfYgPcdHftf6h
google.golang.org/protobuf v1.34.2/go.mod h1:qYOHts0dSfpeUzUFpOMr/WGzszTmLH+DiWniOlNbLDw=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7 h1:uRGJdciOHaEIrze2W8Q3AKkepLTh2hOroT7a+7czfdQ=
gopkg.in/tomb.v1 v1.0.0-20141024135613-dd632973f1e7/go.mod h1:dt/ZhP58zS4L8KSrWDmTeBkI65Dw0HsyUHuEVlX15mw=
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
gopkg.in/yaml.v2 v2.4.0/go.mod h1:RDklbk79AGWmwhnvt/jBztapEOGDOx6ZbXqjP6csGnQ=
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=

View File

@@ -135,32 +135,30 @@ func InitDB() {
}
func migrateDB() error {
if env.Bool("StartSqlMigration", false) {
var err error
if err = DB.AutoMigrate(&Channel{}); err != nil {
return err
}
if err = DB.AutoMigrate(&Token{}); err != nil {
return err
}
if err = DB.AutoMigrate(&User{}); err != nil {
return err
}
if err = DB.AutoMigrate(&Option{}); err != nil {
return err
}
if err = DB.AutoMigrate(&Redemption{}); err != nil {
return err
}
if err = DB.AutoMigrate(&Ability{}); err != nil {
return err
}
if err = DB.AutoMigrate(&Log{}); err != nil {
return err
}
if err = DB.AutoMigrate(&Channel{}); err != nil {
return err
}
var err error
if err = DB.AutoMigrate(&Channel{}); err != nil {
return err
}
if err = DB.AutoMigrate(&Token{}); err != nil {
return err
}
if err = DB.AutoMigrate(&User{}); err != nil {
return err
}
if err = DB.AutoMigrate(&Option{}); err != nil {
return err
}
if err = DB.AutoMigrate(&Redemption{}); err != nil {
return err
}
if err = DB.AutoMigrate(&Ability{}); err != nil {
return err
}
if err = DB.AutoMigrate(&Log{}); err != nil {
return err
}
if err = DB.AutoMigrate(&Channel{}); err != nil {
return err
}
return nil
}

View File

@@ -64,9 +64,6 @@ func GetAdaptor(apiType int) adaptor.Adaptor {
return &proxy.Adaptor{}
case apitype.Replicate:
return &replicate.Adaptor{}
case apitype.CozeV3:
return &coze.AdaptorV3{}
}
return nil
}

View File

@@ -36,12 +36,6 @@ func ConvertRequest(request model.GeneralOpenAIRequest) *ChatRequest {
enableSearch = true
aliModel = strings.TrimSuffix(aliModel, EnableSearchModelSuffix)
}
enableThinking := false
if request.ReasoningEffort != nil {
enableThinking = true
}
request.TopP = helper.Float64PtrMax(request.TopP, 0.9999)
return &ChatRequest{
Model: aliModel,
@@ -58,7 +52,6 @@ func ConvertRequest(request model.GeneralOpenAIRequest) *ChatRequest {
TopK: request.TopK,
ResultFormat: "message",
Tools: request.Tools,
EnableThinking: enableThinking,
},
}
}

View File

@@ -25,7 +25,6 @@ type Parameters struct {
Temperature *float64 `json:"temperature,omitempty"`
ResultFormat string `json:"result_format,omitempty"`
Tools []model.Tool `json:"tools,omitempty"`
EnableThinking bool `json:"enable_thinking,omitempty"`
}
type ChatRequest struct {

View File

@@ -17,5 +17,4 @@ var ModelList = []string{
"deepseek-r1",
"deepseek-v3",
"deepseek-v3.1",
}

View File

@@ -1,75 +0,0 @@
package coze
import (
"errors"
"fmt"
"github.com/gin-gonic/gin"
"github.com/songquanpeng/one-api/relay/adaptor"
"github.com/songquanpeng/one-api/relay/adaptor/openai"
"github.com/songquanpeng/one-api/relay/meta"
"github.com/songquanpeng/one-api/relay/model"
"io"
"net/http"
)
type AdaptorV3 struct {
meta *meta.Meta
}
func (a *AdaptorV3) Init(meta *meta.Meta) {
a.meta = meta
}
func (a *AdaptorV3) GetRequestURL(meta *meta.Meta) (string, error) {
return fmt.Sprintf("%s/v3/chat", meta.BaseURL), nil
}
func (a *AdaptorV3) SetupRequestHeader(c *gin.Context, req *http.Request, meta *meta.Meta) error {
adaptor.SetupCommonRequestHeader(c, req, meta)
req.Header.Set("Authorization", "Bearer "+meta.APIKey)
return nil
}
func (a *AdaptorV3) ConvertRequest(c *gin.Context, relayMode int, request *model.GeneralOpenAIRequest) (any, error) {
if request == nil {
return nil, errors.New("request is nil")
}
request.User = a.meta.Config.UserID
return V3ConvertRequest(*request), nil
}
func (a *AdaptorV3) ConvertImageRequest(request *model.ImageRequest) (any, error) {
if request == nil {
return nil, errors.New("request is nil")
}
return request, nil
}
func (a *AdaptorV3) DoRequest(c *gin.Context, meta *meta.Meta, requestBody io.Reader) (*http.Response, error) {
return adaptor.DoRequestHelper(a, c, meta, requestBody)
}
func (a *AdaptorV3) DoResponse(c *gin.Context, resp *http.Response, meta *meta.Meta) (usage *model.Usage, err *model.ErrorWithStatusCode) {
var responseText *string
if meta.IsStream {
err, responseText = V3StreamHandler(c, resp)
} else {
err, responseText = V3Handler(c, resp, meta.PromptTokens, meta.ActualModelName)
}
if responseText != nil {
usage = openai.ResponseText2Usage(*responseText, meta.ActualModelName, meta.PromptTokens)
} else {
usage = &model.Usage{}
}
usage.PromptTokens = meta.PromptTokens
usage.TotalTokens = usage.PromptTokens + usage.CompletionTokens
return
}
func (a *AdaptorV3) GetModelList() []string {
return ModelList
}
func (a *AdaptorV3) GetChannelName() string {
return "CozeV3"
}

View File

@@ -1,9 +1,6 @@
package coze
import (
"github.com/songquanpeng/one-api/relay/adaptor/coze/constant/event"
"strings"
)
import "github.com/songquanpeng/one-api/relay/adaptor/coze/constant/event"
func event2StopReason(e *string) string {
if e == nil || *e == event.Message {
@@ -11,16 +8,3 @@ func event2StopReason(e *string) string {
}
return "stop"
}
func splitOnDoubleNewline(data []byte, atEOF bool) (advance int, token []byte, err error) {
if atEOF && len(data) == 0 {
return 0, nil, nil
}
if i := strings.Index(string(data), "\n\n"); i >= 0 {
return i + 1, data[0:i], nil
}
if atEOF {
return len(data), data, nil
}
return 0, nil, nil
}

View File

@@ -4,18 +4,19 @@ import (
"bufio"
"encoding/json"
"fmt"
"github.com/songquanpeng/one-api/common/render"
"io"
"net/http"
"strings"
"github.com/gin-gonic/gin"
"github.com/songquanpeng/one-api/common"
"github.com/songquanpeng/one-api/common/conv"
"github.com/songquanpeng/one-api/common/helper"
"github.com/songquanpeng/one-api/common/logger"
"github.com/songquanpeng/one-api/common/render"
"github.com/songquanpeng/one-api/relay/adaptor/coze/constant/messagetype"
"github.com/songquanpeng/one-api/relay/adaptor/openai"
"github.com/songquanpeng/one-api/relay/model"
"io"
"net/http"
"strings"
)
// https://www.coze.com/open
@@ -56,32 +57,6 @@ func ConvertRequest(textRequest model.GeneralOpenAIRequest) *Request {
return &cozeRequest
}
func V3ConvertRequest(textRequest model.GeneralOpenAIRequest) *V3Request {
cozeRequest := V3Request{
UserId: textRequest.User,
Stream: textRequest.Stream,
BotId: strings.TrimPrefix(textRequest.Model, "bot-"),
}
if cozeRequest.UserId == "" {
cozeRequest.UserId = "any"
}
for i, message := range textRequest.Messages {
if i == len(textRequest.Messages)-1 {
cozeRequest.AdditionalMessages = append(cozeRequest.AdditionalMessages, Message{
Role: "user",
Content: message.CozeV3StringContent(),
})
continue
}
cozeMessage := Message{
Role: message.Role,
Content: message.CozeV3StringContent(),
}
cozeRequest.AdditionalMessages = append(cozeRequest.AdditionalMessages, cozeMessage)
}
return &cozeRequest
}
func StreamResponseCoze2OpenAI(cozeResponse *StreamResponse) (*openai.ChatCompletionsStreamResponse, *Response) {
var response *Response
var stopReason string
@@ -105,28 +80,6 @@ func StreamResponseCoze2OpenAI(cozeResponse *StreamResponse) (*openai.ChatComple
return &openaiResponse, response
}
func V3StreamResponseCoze2OpenAI(cozeResponse *V3StreamResponse) (*openai.ChatCompletionsStreamResponse, *Response) {
var response *Response
var choice openai.ChatCompletionsStreamResponseChoice
choice.Delta.Role = cozeResponse.Role
choice.Delta.Content = cozeResponse.Content
var openaiResponse openai.ChatCompletionsStreamResponse
openaiResponse.Object = "chat.completion.chunk"
openaiResponse.Choices = []openai.ChatCompletionsStreamResponseChoice{choice}
openaiResponse.Id = cozeResponse.ConversationId
if cozeResponse.Usage.TokenCount > 0 {
openaiResponse.Usage = &model.Usage{
PromptTokens: cozeResponse.Usage.InputCount,
CompletionTokens: cozeResponse.Usage.OutputCount,
TotalTokens: cozeResponse.Usage.TokenCount,
}
}
return &openaiResponse, response
}
func ResponseCoze2OpenAI(cozeResponse *Response) *openai.TextResponse {
var responseText string
for _, message := range cozeResponse.Messages {
@@ -154,26 +107,6 @@ func ResponseCoze2OpenAI(cozeResponse *Response) *openai.TextResponse {
return &fullTextResponse
}
func V3ResponseCoze2OpenAI(cozeResponse *V3Response) *openai.TextResponse {
choice := openai.TextResponseChoice{
Index: 0,
Message: model.Message{
Role: "assistant",
Content: cozeResponse.Data.Content,
Name: nil,
},
FinishReason: "stop",
}
fullTextResponse := openai.TextResponse{
Id: fmt.Sprintf("chatcmpl-%s", cozeResponse.Data.ConversationId),
Model: "coze-bot",
Object: "chat.completion",
Created: helper.GetTimestamp(),
Choices: []openai.TextResponseChoice{choice},
}
return &fullTextResponse
}
func StreamHandler(c *gin.Context, resp *http.Response) (*model.ErrorWithStatusCode, *string) {
var responseText string
createdTime := helper.GetTimestamp()
@@ -229,63 +162,6 @@ func StreamHandler(c *gin.Context, resp *http.Response) (*model.ErrorWithStatusC
return nil, &responseText
}
func V3StreamHandler(c *gin.Context, resp *http.Response) (*model.ErrorWithStatusCode, *string) {
var responseText string
createdTime := helper.GetTimestamp()
scanner := bufio.NewScanner(resp.Body)
scanner.Split(splitOnDoubleNewline)
common.SetEventStreamHeaders(c)
var modelName string
for scanner.Scan() {
part := scanner.Text()
part = strings.TrimPrefix(part, "\n")
parts := strings.Split(part, "\n")
if len(parts) != 2 {
continue
}
if !strings.HasPrefix(parts[0], "event:") || !strings.HasPrefix(parts[1], "data:") {
continue
}
event, data := strings.TrimSpace(parts[0][6:]), strings.TrimSpace(parts[1][5:])
if event == "conversation.message.delta" || event == "conversation.chat.completed" {
data = strings.TrimSuffix(data, "\r")
var cozeResponse V3StreamResponse
err := json.Unmarshal([]byte(data), &cozeResponse)
if err != nil {
logger.SysError("error unmarshalling stream response: " + err.Error())
continue
}
response, _ := V3StreamResponseCoze2OpenAI(&cozeResponse)
if response == nil {
continue
}
for _, choice := range response.Choices {
responseText += conv.AsString(choice.Delta.Content)
}
response.Model = modelName
response.Created = createdTime
err = render.ObjectData(c, response)
if err != nil {
logger.SysError(err.Error())
}
}
}
if err := scanner.Err(); err != nil {
logger.SysError("error reading stream: " + err.Error())
}
render.Done(c)
err := resp.Body.Close()
if err != nil {
return openai.ErrorWrapper(err, "close_response_body_failed", http.StatusInternalServerError), nil
}
return nil, &responseText
}
func Handler(c *gin.Context, resp *http.Response, promptTokens int, modelName string) (*model.ErrorWithStatusCode, *string) {
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
@@ -324,42 +200,3 @@ func Handler(c *gin.Context, resp *http.Response, promptTokens int, modelName st
}
return nil, &responseText
}
func V3Handler(c *gin.Context, resp *http.Response, promptTokens int, modelName string) (*model.ErrorWithStatusCode, *string) {
responseBody, err := io.ReadAll(resp.Body)
if err != nil {
return openai.ErrorWrapper(err, "read_response_body_failed", http.StatusInternalServerError), nil
}
err = resp.Body.Close()
if err != nil {
return openai.ErrorWrapper(err, "close_response_body_failed", http.StatusInternalServerError), nil
}
var cozeResponse V3Response
err = json.Unmarshal(responseBody, &cozeResponse)
if err != nil {
return openai.ErrorWrapper(err, "unmarshal_response_body_failed", http.StatusInternalServerError), nil
}
if cozeResponse.Code != 0 {
return &model.ErrorWithStatusCode{
Error: model.Error{
Message: cozeResponse.Msg,
Code: cozeResponse.Code,
},
StatusCode: resp.StatusCode,
}, nil
}
fullTextResponse := V3ResponseCoze2OpenAI(&cozeResponse)
fullTextResponse.Model = modelName
jsonResponse, err := json.Marshal(fullTextResponse)
if err != nil {
return openai.ErrorWrapper(err, "marshal_response_body_failed", http.StatusInternalServerError), nil
}
c.Writer.Header().Set("Content-Type", "application/json")
c.Writer.WriteHeader(resp.StatusCode)
_, err = c.Writer.Write(jsonResponse)
var responseText string
if len(fullTextResponse.Choices) > 0 {
responseText = fullTextResponse.Choices[0].Message.StringContent()
}
return nil, &responseText
}

View File

@@ -2,9 +2,9 @@ package coze
type Message struct {
Role string `json:"role"`
Type string `json:"type,omitempty"`
Type string `json:"type"`
Content string `json:"content"`
ContentType string `json:"content_type,omitempty"`
ContentType string `json:"content_type"`
}
type ErrorInformation struct {
@@ -36,52 +36,3 @@ type StreamResponse struct {
ConversationId string `json:"conversation_id,omitempty"`
ErrorInformation *ErrorInformation `json:"error_information,omitempty"`
}
type V3StreamResponse struct {
Id string `json:"id"`
ConversationId string `json:"conversation_id"`
BotId string `json:"bot_id"`
Role string `json:"role"`
Type string `json:"type"`
Content string `json:"content"`
ContentType string `json:"content_type"`
ChatId string `json:"chat_id"`
CreatedAt int `json:"created_at"`
CompletedAt int `json:"completed_at"`
LastError struct {
Code int `json:"code"`
Msg string `json:"msg"`
} `json:"last_error"`
Status string `json:"status"`
Usage struct {
TokenCount int `json:"token_count"`
OutputCount int `json:"output_count"`
InputCount int `json:"input_count"`
} `json:"usage"`
SectionId string `json:"section_id"`
}
type V3Response struct {
Data struct {
Id string `json:"id"`
ConversationId string `json:"conversation_id"`
BotId string `json:"bot_id"`
Content string `json:"content"`
ContentType string `json:"content_type"`
CreatedAt int `json:"created_at"`
LastError struct {
Code int `json:"code"`
Msg string `json:"msg"`
} `json:"last_error"`
Status string `json:"status"`
} `json:"data"`
Code int `json:"code"`
Msg string `json:"msg"`
}
type V3Request struct {
BotId string `json:"bot_id"`
UserId string `json:"user_id"`
AdditionalMessages []Message `json:"additional_messages"`
Stream bool `json:"stream"`
}

View File

@@ -25,7 +25,7 @@ func (a *Adaptor) Init(meta *meta.Meta) {
func (a *Adaptor) GetRequestURL(meta *meta.Meta) (string, error) {
defaultVersion := config.GeminiVersion
if strings.Contains(meta.ActualModelName, "gemini-2") ||
if strings.Contains(meta.ActualModelName, "gemini-2.0") ||
strings.Contains(meta.ActualModelName, "gemini-1.5") {
defaultVersion = "v1beta"
}

View File

@@ -12,7 +12,6 @@ import (
"github.com/songquanpeng/one-api/common"
"github.com/songquanpeng/one-api/common/config"
"github.com/songquanpeng/one-api/common/file"
"github.com/songquanpeng/one-api/common/helper"
"github.com/songquanpeng/one-api/common/image"
"github.com/songquanpeng/one-api/common/logger"
@@ -67,23 +66,6 @@ func ConvertRequest(textRequest model.GeneralOpenAIRequest) *ChatRequest {
MaxOutputTokens: textRequest.MaxTokens,
},
}
if textRequest.ReasoningEffort != nil {
var thinkBudget int
switch *textRequest.ReasoningEffort {
case "low":
thinkBudget = 1000
case "medium":
thinkBudget = 8000
case "high":
thinkBudget = 24000
}
geminiRequest.GenerationConfig.ThinkingConfig = &ThinkingConfig{
ThinkingBudget: thinkBudget,
IncludeThoughts: true,
}
}
if textRequest.ResponseFormat != nil {
if mimeType, ok := mimeTypeMap[textRequest.ResponseFormat.Type]; ok {
geminiRequest.GenerationConfig.ResponseMimeType = mimeType
@@ -94,13 +76,22 @@ func ConvertRequest(textRequest model.GeneralOpenAIRequest) *ChatRequest {
}
}
if textRequest.Tools != nil {
geminiRequest.Tools = textRequest.Tools
functions := make([]model.Function, 0, len(textRequest.Tools))
for _, tool := range textRequest.Tools {
functions = append(functions, tool.Function)
}
geminiRequest.Tools = []ChatTools{
{
FunctionDeclarations: functions,
},
}
} else if textRequest.Functions != nil {
geminiRequest.Tools = []ChatTools{
{
FunctionDeclarations: textRequest.Functions,
},
}
}
if textRequest.Functions != nil {
geminiRequest.Tools = textRequest.Functions
}
shouldAddDummyModelMessage := false
for _, message := range textRequest.Messages {
content := ChatContent{
@@ -119,14 +110,6 @@ func ConvertRequest(textRequest model.GeneralOpenAIRequest) *ChatRequest {
parts = append(parts, Part{
Text: part.Text,
})
} else if part.Type == model.ContentTypeInputFile {
mimeType, data, _ := file.GetFileFromUrl(part.File.FileData)
parts = append(parts, Part{
InlineData: &InlineData{
MimeType: mimeType,
Data: data,
},
})
} else if part.Type == model.ContentTypeImageURL {
imageNum += 1
if imageNum > VisionMaxImageNum {
@@ -216,21 +199,6 @@ func (g *ChatResponse) GetResponseText() string {
return ""
}
func (g *ChatResponse) GetResponseTextAndThought() (content string, thought string) {
if g == nil {
return
}
if len(g.Candidates) > 0 && len(g.Candidates[0].Content.Parts) > 0 {
contentPart := g.Candidates[0].Content.Parts[0]
if contentPart.Thought {
thought = contentPart.Text
return
}
content = contentPart.Text
}
return
}
type ChatCandidate struct {
Content ChatContent `json:"content"`
FinishReason string `json:"finishReason"`
@@ -295,11 +263,7 @@ func responseGeminiChat2OpenAI(response *ChatResponse) *openai.TextResponse {
if i > 0 {
builder.WriteString("\n")
}
if part.Thought {
builder.WriteString(fmt.Sprintf("<think>%s</think>\n", part.Text))
} else {
builder.WriteString(part.Text)
}
builder.WriteString(part.Text)
}
choice.Message.Content = builder.String()
}
@@ -314,7 +278,7 @@ func responseGeminiChat2OpenAI(response *ChatResponse) *openai.TextResponse {
func streamResponseGeminiChat2OpenAI(geminiResponse *ChatResponse) *openai.ChatCompletionsStreamResponse {
var choice openai.ChatCompletionsStreamResponseChoice
choice.Delta.Content, choice.Delta.ReasoningContent = geminiResponse.GetResponseTextAndThought()
choice.Delta.Content = geminiResponse.GetResponseText()
//choice.FinishReason = &constant.StopFinishReason
var response openai.ChatCompletionsStreamResponse
response.Id = fmt.Sprintf("chatcmpl-%s", random.GetUUID())

View File

@@ -4,7 +4,7 @@ type ChatRequest struct {
Contents []ChatContent `json:"contents"`
SafetySettings []ChatSafetySettings `json:"safety_settings,omitempty"`
GenerationConfig ChatGenerationConfig `json:"generation_config,omitempty"`
Tools interface{} `json:"tools,omitempty"`
Tools []ChatTools `json:"tools,omitempty"`
SystemInstruction *ChatContent `json:"system_instruction,omitempty"`
}
@@ -40,11 +40,6 @@ type InlineData struct {
Data string `json:"data"`
}
type FileData struct {
MimeType string `json:"mime_type"`
FileUri string `json:"file_uri"`
}
type FunctionCall struct {
FunctionName string `json:"name"`
Arguments any `json:"args"`
@@ -54,8 +49,6 @@ type Part struct {
Text string `json:"text,omitempty"`
InlineData *InlineData `json:"inlineData,omitempty"`
FunctionCall *FunctionCall `json:"functionCall,omitempty"`
Thought bool `json:"thought,omitempty"`
FileData *FileData `json:"fileData,omitempty"`
}
type ChatContent struct {
@@ -73,18 +66,12 @@ type ChatTools struct {
}
type ChatGenerationConfig struct {
ResponseMimeType string `json:"responseMimeType,omitempty"`
ResponseSchema any `json:"responseSchema,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"topP,omitempty"`
TopK float64 `json:"topK,omitempty"`
MaxOutputTokens int `json:"maxOutputTokens,omitempty"`
CandidateCount int `json:"candidateCount,omitempty"`
StopSequences []string `json:"stopSequences,omitempty"`
ThinkingConfig *ThinkingConfig `json:"thinkingConfig,omitempty"`
}
type ThinkingConfig struct {
ThinkingBudget int `json:"thinkingBudget"`
IncludeThoughts bool `json:"includeThoughts"`
ResponseMimeType string `json:"responseMimeType,omitempty"`
ResponseSchema any `json:"responseSchema,omitempty"`
Temperature *float64 `json:"temperature,omitempty"`
TopP *float64 `json:"topP,omitempty"`
TopK float64 `json:"topK,omitempty"`
MaxOutputTokens int `json:"maxOutputTokens,omitempty"`
CandidateCount int `json:"candidateCount,omitempty"`
StopSequences []string `json:"stopSequences,omitempty"`
}

View File

@@ -45,6 +45,7 @@ func (a *Adaptor) GetRequestURL(meta *meta.Meta) (string, error) {
requestURL = fmt.Sprintf("%s?api-version=%s", requestURL, meta.Config.APIVersion)
task := strings.TrimPrefix(requestURL, "/v1/")
model_ := meta.ActualModelName
model_ = strings.Replace(model_, ".", "", -1)
//https://github.com/songquanpeng/one-api/issues/1191
// {your endpoint}/openai/deployments/{your azure_model}/chat/completions?api-version={api_version}
requestURL = fmt.Sprintf("/openai/deployments/%s/%s", model_, task)

View File

@@ -4,7 +4,7 @@ var ModelList = []string{
"gpt-3.5-turbo", "gpt-3.5-turbo-0301", "gpt-3.5-turbo-0613", "gpt-3.5-turbo-1106", "gpt-3.5-turbo-0125",
"gpt-3.5-turbo-16k", "gpt-3.5-turbo-16k-0613",
"gpt-3.5-turbo-instruct",
"gpt-4", "gpt-4.1", "gpt-4-0314", "gpt-4-0613", "gpt-4-1106-preview", "gpt-4-0125-preview",
"gpt-4", "gpt-4-0314", "gpt-4-0613", "gpt-4-1106-preview", "gpt-4-0125-preview",
"gpt-4-32k", "gpt-4-32k-0314", "gpt-4-32k-0613",
"gpt-4-turbo-preview", "gpt-4-turbo", "gpt-4-turbo-2024-04-09",
"gpt-4o", "gpt-4o-2024-05-13",

View File

@@ -20,6 +20,6 @@ const (
VertexAI
Proxy
Replicate
CozeV3
Dummy // this one is only for count, do not add any channel after this
)

View File

@@ -27,7 +27,6 @@ var modelRatioLock sync.RWMutex
var ModelRatio = map[string]float64{
// https://openai.com/pricing
"gpt-4": 15,
"gpt-4.1": 15,
"gpt-4-0314": 15,
"gpt-4-0613": 15,
"gpt-4-32k": 30,
@@ -72,8 +71,6 @@ var ModelRatio = map[string]float64{
"text-davinci-edit-001": 10,
"code-davinci-edit-001": 10,
"whisper-1": 15, // $0.006 / minute -> $0.006 / 150 words -> $0.006 / 200 tokens -> $0.03 / 1k tokens
"gpt-4o-mini-transcribe": 15, // $0.006 / minute -> $0.006 / 150 words -> $0.006 / 200 tokens -> $0.03 / 1k tokens
"gpt-4o-transcribe": 15, // $0.006 / minute -> $0.006 / 150 words -> $0.006 / 200 tokens -> $0.03 / 1k tokens
"tts-1": 7.5, // $0.015 / 1K characters
"tts-1-1106": 7.5,
"tts-1-hd": 15, // $0.030 / 1K characters
@@ -629,9 +626,7 @@ var CompletionRatio = map[string]float64{
"llama3-8b-8192(33)": 0.0006 / 0.0003,
"llama3-70b-8192(33)": 0.0035 / 0.00265,
// whisper
"whisper-1": 0, // only count input tokens
"gpt-4o-mini-transcribe": 0,
"gpt-4o-transcribe": 0,
"whisper-1": 0, // only count input tokens
// deepseek
"deepseek-chat": 0.28 / 0.14,
"deepseek-reasoner": 2.19 / 0.55,

View File

@@ -53,6 +53,5 @@ const (
AliBailian
OpenAICompatible
GeminiOpenAICompatible
CozeV3
Dummy
)

View File

@@ -23,16 +23,12 @@ func ToAPIType(channelType int) int {
apiType = apitype.Tencent
case Gemini:
apiType = apitype.Gemini
case GeminiOpenAICompatible:
apiType = apitype.Gemini
case Ollama:
apiType = apitype.Ollama
case AwsClaude:
apiType = apitype.AwsClaude
case Coze:
apiType = apitype.Coze
case CozeV3:
apiType = apitype.CozeV3
case Cohere:
apiType = apitype.Cohere
case Cloudflare:

View File

@@ -54,7 +54,6 @@ var ChannelBaseURLs = []string{
"", // 50
"https://generativelanguage.googleapis.com/v1beta/openai/", // 51
"https://api.coze.cn", // 52
}
func init() {

View File

@@ -8,7 +8,6 @@ import (
"errors"
"fmt"
"io"
"mime/multipart"
"net/http"
"strings"
@@ -31,7 +30,8 @@ import (
func RelayAudioHelper(c *gin.Context, relayMode int) *relaymodel.ErrorWithStatusCode {
ctx := c.Request.Context()
meta := meta.GetByContext(c)
audioModel := "gpt-4o-transcribe"
audioModel := "whisper-1"
tokenId := c.GetInt(ctxkey.TokenId)
channelType := c.GetInt(ctxkey.Channel)
channelId := c.GetInt(ctxkey.ChannelId)
@@ -124,13 +124,12 @@ func RelayAudioHelper(c *gin.Context, relayMode int) *relaymodel.ErrorWithStatus
fullRequestURL := openai.GetFullRequestURL(baseURL, requestURL, channelType)
if channelType == channeltype.Azure {
apiVersion := meta.Config.APIVersion
deploymentName := c.GetString(ctxkey.ChannelName)
if relayMode == relaymode.AudioTranscription {
// https://learn.microsoft.com/en-us/azure/ai-services/openai/whisper-quickstart?tabs=command-line#rest-api
fullRequestURL = fmt.Sprintf("%s/openai/deployments/%s/audio/transcriptions?api-version=%s", baseURL, deploymentName, apiVersion)
fullRequestURL = fmt.Sprintf("%s/openai/deployments/%s/audio/transcriptions?api-version=%s", baseURL, audioModel, apiVersion)
} else if relayMode == relaymode.AudioSpeech {
// https://learn.microsoft.com/en-us/azure/ai-services/openai/text-to-speech-quickstart?tabs=command-line#rest-api
fullRequestURL = fmt.Sprintf("%s/openai/deployments/%s/audio/speech?api-version=%s", baseURL, deploymentName, apiVersion)
fullRequestURL = fmt.Sprintf("%s/openai/deployments/%s/audio/speech?api-version=%s", baseURL, audioModel, apiVersion)
}
}
@@ -139,73 +138,8 @@ func RelayAudioHelper(c *gin.Context, relayMode int) *relaymodel.ErrorWithStatus
if err != nil {
return openai.ErrorWrapper(err, "new_request_body_failed", http.StatusInternalServerError)
}
// 处理表单数据
contentType := c.Request.Header.Get("Content-Type")
responseFormat := "json"
var contentTypeWithBoundary string
if strings.Contains(contentType, "multipart/form-data") {
originalBody := requestBody.Bytes()
c.Request.Body = io.NopCloser(bytes.NewBuffer(originalBody))
err = c.Request.ParseMultipartForm(32 << 20) // 32MB 最大内存
if err != nil {
return openai.ErrorWrapper(err, "parse_multipart_form_failed", http.StatusInternalServerError)
}
// 获取响应格式
if format := c.Request.FormValue("response_format"); format != "" {
responseFormat = format
}
requestBody = &bytes.Buffer{}
writer := multipart.NewWriter(requestBody)
// 复制表单字段
for key, values := range c.Request.MultipartForm.Value {
for _, value := range values {
err = writer.WriteField(key, value)
if err != nil {
return openai.ErrorWrapper(err, "write_field_failed", http.StatusInternalServerError)
}
}
}
// 复制文件
for key, fileHeaders := range c.Request.MultipartForm.File {
for _, fileHeader := range fileHeaders {
file, err := fileHeader.Open()
if err != nil {
return openai.ErrorWrapper(err, "open_file_failed", http.StatusInternalServerError)
}
part, err := writer.CreateFormFile(key, fileHeader.Filename)
if err != nil {
file.Close()
return openai.ErrorWrapper(err, "create_form_file_failed", http.StatusInternalServerError)
}
_, err = io.Copy(part, file)
file.Close()
if err != nil {
return openai.ErrorWrapper(err, "copy_file_failed", http.StatusInternalServerError)
}
}
}
// 完成multipart写入
err = writer.Close()
if err != nil {
return openai.ErrorWrapper(err, "close_writer_failed", http.StatusInternalServerError)
}
// 更新Content-Type
contentTypeWithBoundary = writer.FormDataContentType()
c.Request.Header.Set("Content-Type", contentTypeWithBoundary)
} else {
// 对于非表单请求,直接重置请求体
c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody.Bytes()))
}
c.Request.Body = io.NopCloser(bytes.NewBuffer(requestBody.Bytes()))
responseFormat := c.DefaultPostForm("response_format", "json")
req, err := http.NewRequest(c.Request.Method, fullRequestURL, requestBody)
if err != nil {
@@ -217,26 +151,11 @@ func RelayAudioHelper(c *gin.Context, relayMode int) *relaymodel.ErrorWithStatus
apiKey := c.Request.Header.Get("Authorization")
apiKey = strings.TrimPrefix(apiKey, "Bearer ")
req.Header.Set("api-key", apiKey)
// 确保请求体大小与Content-Length一致
req.ContentLength = int64(requestBody.Len())
req.ContentLength = c.Request.ContentLength
} else {
req.Header.Set("Authorization", c.Request.Header.Get("Authorization"))
// 确保请求体大小与Content-Length一致
req.ContentLength = int64(requestBody.Len())
}
// 确保Content-Type正确传递
if strings.Contains(contentType, "multipart/form-data") && c.Request.MultipartForm != nil {
// 对于multipart请求使用我们重建时生成的Content-Type
// 注意此处必须使用writer生成的boundary
if contentTypeWithBoundary != "" {
req.Header.Set("Content-Type", contentTypeWithBoundary)
} else {
req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
}
} else {
req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
}
req.Header.Set("Content-Type", c.Request.Header.Get("Content-Type"))
req.Header.Set("Accept", c.Request.Header.Get("Accept"))
resp, err := client.HTTPClient.Do(req)

View File

@@ -4,5 +4,4 @@ const (
ContentTypeText = "text"
ContentTypeImageURL = "image_url"
ContentTypeInputAudio = "input_audio"
ContentTypeInputFile = "file"
)

View File

@@ -1,7 +1,5 @@
package model
import "encoding/json"
type Message struct {
Role string `json:"role,omitempty"`
Content any `json:"content,omitempty"`
@@ -40,53 +38,6 @@ func (m Message) StringContent() string {
return ""
}
func (m Message) CozeV3StringContent() string {
content, ok := m.Content.(string)
if ok {
return content
}
contentList, ok := m.Content.([]any)
if ok {
contents := make([]map[string]any, 0)
var contentStr string
for _, contentItem := range contentList {
contentMap, ok := contentItem.(map[string]any)
if !ok {
continue
}
switch contentMap["type"] {
case "text":
if subStr, ok := contentMap["text"].(string); ok {
contents = append(contents, map[string]any{
"type": "text",
"text": subStr,
})
}
case "image_url":
if subStr, ok := contentMap["image_url"].(string); ok {
contents = append(contents, map[string]any{
"type": "image",
"file_url": subStr,
})
}
case "file":
if subStr, ok := contentMap["image_url"].(string); ok {
contents = append(contents, map[string]any{
"type": "file",
"file_url": subStr,
})
}
}
}
if len(contents) > 0 {
b, _ := json.Marshal(contents)
return string(b)
}
return contentStr
}
return ""
}
func (m Message) ParseContent() []MessageContent {
var contentList []MessageContent
content, ok := m.Content.(string)
@@ -121,15 +72,6 @@ func (m Message) ParseContent() []MessageContent {
},
})
}
case ContentTypeInputFile:
if subObj, ok := contentMap["file"].(map[string]any); ok {
contentList = append(contentList, MessageContent{
Type: ContentTypeInputFile,
File: &File{
FileData: subObj["file_data"].(string),
},
})
}
}
}
return contentList
@@ -146,10 +88,4 @@ type MessageContent struct {
Type string `json:"type,omitempty"`
Text string `json:"text"`
ImageURL *ImageURL `json:"image_url,omitempty"`
File *File `json:"file,omitempty"`
}
type File struct {
FileData string `json:"file_data,omitempty"`
FileName string `json:"filename,omitempty"`
}

View File

@@ -22,7 +22,6 @@ export const CHANNEL_OPTIONS = [
{ key: 31, text: '零一万物', value: 31, color: 'green' },
{ key: 32, text: '阶跃星辰', value: 32, color: 'blue' },
{ key: 34, text: 'Coze', value: 34, color: 'blue' },
{ key: 52, text: 'CozeV3', value: 52, color: 'blue' },
{ key: 35, text: 'Cohere', value: 35, color: 'blue' },
{ key: 36, text: 'DeepSeek', value: 36, color: 'black' },
{ key: 37, text: 'Cloudflare', value: 37, color: 'orange' },

View File

@@ -137,12 +137,6 @@ export const CHANNEL_OPTIONS = {
value: 34,
color: 'primary'
},
52: {
key: 52,
text: 'CozeV3',
value: 52,
color: 'primary'
},
35: {
key: 35,
text: 'Cohere',
@@ -191,7 +185,7 @@ export const CHANNEL_OPTIONS = {
value: 45,
color: 'primary'
},
46: {
45: {
key: 46,
text: 'Replicate',
value: 46,

View File

@@ -206,20 +206,6 @@ const typeConfig = {
},
modelGroup: 'Coze'
},
52: {
inputLabel: {
config: {
user_id: 'User ID'
}
},
prompt: {
models: '对于 CozeV3 而言,模型名称即 Bot ID你可以添加一个前缀 `bot-`,例如:`bot-123456`',
config: {
user_id: '生成该密钥的用户 ID'
}
},
modelGroup: 'CozeV3'
},
42: {
inputLabel: {
key: '',

View File

@@ -1,109 +1,108 @@
export const CHANNEL_OPTIONS = [
{key: 1, text: 'OpenAI', value: 1, color: 'green'},
{
key: 50,
text: 'OpenAI 兼容',
value: 50,
color: 'olive',
description: 'OpenAI 兼容渠道,支持设置 Base URL',
},
{key: 14, text: 'Anthropic', value: 14, color: 'black'},
{key: 33, text: 'AWS', value: 33, color: 'black'},
{key: 3, text: 'Azure', value: 3, color: 'olive'},
{key: 11, text: 'PaLM2', value: 11, color: 'orange'},
{key: 24, text: 'Gemini', value: 24, color: 'orange'},
{
key: 51,
text: 'Gemini (OpenAI)',
value: 51,
color: 'orange',
description: 'Gemini OpenAI 兼容格式',
},
{key: 28, text: 'Mistral AI', value: 28, color: 'orange'},
{key: 41, text: 'Novita', value: 41, color: 'purple'},
{
key: 40,
text: '字节火山引擎',
value: 40,
color: 'blue',
description: '原字节跳动豆包',
},
{
key: 15,
text: '百度文心千帆',
value: 15,
color: 'blue',
tip: '请前往<a href="https://console.bce.baidu.com/qianfan/ais/console/applicationConsole/application/v1" target="_blank">此处</a>获取 AKAPI Key以及 SKSecret Key注意V2 版本接口请使用 <strong>百度文心千帆 V2 </strong>渠道类型',
},
{
key: 47,
text: '百度文心千帆 V2',
value: 47,
color: 'blue',
tip: '请前往<a href="https://console.bce.baidu.com/iam/#/iam/apikey/list" target="_blank">此处</a>获取 API Key注意本渠道仅支持<a target="_blank" href="https://cloud.baidu.com/doc/WENXINWORKSHOP/s/em4tsqo3v">推理服务 V2</a>相关模型',
},
{
key: 17,
text: '阿里通义千问',
value: 17,
color: 'orange',
tip: '如需使用阿里云百炼,请使用<strong>阿里云百炼</strong>渠道',
},
{key: 49, text: '阿里云百炼', value: 49, color: 'orange'},
{
key: 18,
text: '讯飞星火认知',
value: 18,
color: 'blue',
tip: '本渠道基于讯飞 WebSocket 版本 API如需 HTTP 版本,请使用<strong>讯飞星火认知 V2</strong>渠道',
},
{
key: 48,
text: '讯飞星火认知 V2',
value: 48,
color: 'blue',
tip: 'HTTP 版本的讯飞接口,前往<a href="https://console.xfyun.cn/services/cbm" target="_blank">此处</a>获取 HTTP 服务接口认证密钥',
},
{key: 16, text: '智谱 ChatGLM', value: 16, color: 'violet'},
{key: 19, text: '360 智脑', value: 19, color: 'blue'},
{key: 25, text: 'Moonshot AI', value: 25, color: 'black'},
{key: 23, text: '腾讯混元', value: 23, color: 'teal'},
{key: 26, text: '百川大模型', value: 26, color: 'orange'},
{key: 27, text: 'MiniMax', value: 27, color: 'red'},
{key: 29, text: 'Groq', value: 29, color: 'orange'},
{key: 30, text: 'Ollama', value: 30, color: 'black'},
{key: 31, text: '零一万物', value: 31, color: 'green'},
{key: 32, text: '阶跃星辰', value: 32, color: 'blue'},
{key: 34, text: 'Coze', value: 34, color: 'blue'},
{key: 52, text: 'CozeV3', value: 52, color: 'blue'},
{key: 35, text: 'Cohere', value: 35, color: 'blue'},
{key: 36, text: 'DeepSeek', value: 36, color: 'black'},
{key: 37, text: 'Cloudflare', value: 37, color: 'orange'},
{key: 38, text: 'DeepL', value: 38, color: 'black'},
{key: 39, text: 'together.ai', value: 39, color: 'blue'},
{key: 42, text: 'VertexAI', value: 42, color: 'blue'},
{key: 43, text: 'Proxy', value: 43, color: 'blue'},
{key: 44, text: 'SiliconFlow', value: 44, color: 'blue'},
{key: 45, text: 'xAI', value: 45, color: 'blue'},
{key: 46, text: 'Replicate', value: 46, color: 'blue'},
{
key: 8,
text: '自定义渠道',
value: 8,
color: 'pink',
tip: '不推荐使用,请使用 <strong>OpenAI 兼容</strong>渠道类型。注意,这里所需要填入的代理地址仅会在实际请求时替换域名部分,如果你想填入 OpenAI SDK 中所要求的 Base URL请使用 OpenAI 兼容渠道类型',
description: '不推荐使用,请使用 OpenAI 兼容渠道类型',
},
{key: 22, text: '知识库:FastGPT', value: 22, color: 'blue'},
{key: 21, text: '知识库AI Proxy', value: 21, color: 'purple'},
{key: 20, text: 'OpenRouter', value: 20, color: 'black'},
{key: 2, text: '代理:API2D', value: 2, color: 'blue'},
{key: 5, text: '代理OpenAI-SB', value: 5, color: 'brown'},
{key: 7, text: '代理:OhMyGPT', value: 7, color: 'purple'},
{key: 10, text: '代理:AI Proxy', value: 10, color: 'purple'},
{key: 4, text: '代理:CloseAI', value: 4, color: 'teal'},
{key: 6, text: '代理:OpenAI Max', value: 6, color: 'violet'},
{key: 9, text: '代理AI.LS', value: 9, color: 'yellow'},
{key: 12, text: '代理API2GPT', value: 12, color: 'blue'},
{key: 13, text: '代理AIGC2D', value: 13, color: 'purple'},
{ key: 1, text: 'OpenAI', value: 1, color: 'green' },
{
key: 50,
text: 'OpenAI 兼容',
value: 50,
color: 'olive',
description: 'OpenAI 兼容渠道,支持设置 Base URL',
},
{key: 14, text: 'Anthropic', value: 14, color: 'black'},
{ key: 33, text: 'AWS', value: 33, color: 'black' },
{key: 3, text: 'Azure', value: 3, color: 'olive'},
{key: 11, text: 'PaLM2', value: 11, color: 'orange'},
{key: 24, text: 'Gemini', value: 24, color: 'orange'},
{
key: 51,
text: 'Gemini (OpenAI)',
value: 51,
color: 'orange',
description: 'Gemini OpenAI 兼容格式',
},
{ key: 28, text: 'Mistral AI', value: 28, color: 'orange' },
{ key: 41, text: 'Novita', value: 41, color: 'purple' },
{
key: 40,
text: '字节火山引擎',
value: 40,
color: 'blue',
description: '原字节跳动豆包',
},
{
key: 15,
text: '百度文心千帆',
value: 15,
color: 'blue',
tip: '请前往<a href="https://console.bce.baidu.com/qianfan/ais/console/applicationConsole/application/v1" target="_blank">此处</a>获取 AKAPI Key以及 SKSecret Key注意V2 版本接口请使用 <strong>百度文心千帆 V2 </strong>渠道类型',
},
{
key: 47,
text: '百度文心千帆 V2',
value: 47,
color: 'blue',
tip: '请前往<a href="https://console.bce.baidu.com/iam/#/iam/apikey/list" target="_blank">此处</a>获取 API Key注意本渠道仅支持<a target="_blank" href="https://cloud.baidu.com/doc/WENXINWORKSHOP/s/em4tsqo3v">推理服务 V2</a>相关模型',
},
{
key: 17,
text: '阿里通义千问',
value: 17,
color: 'orange',
tip: '如需使用阿里云百炼,请使用<strong>阿里云百炼</strong>渠道',
},
{ key: 49, text: '阿里云百炼', value: 49, color: 'orange' },
{
key: 18,
text: '讯飞星火认知',
value: 18,
color: 'blue',
tip: '本渠道基于讯飞 WebSocket 版本 API如需 HTTP 版本,请使用<strong>讯飞星火认知 V2</strong>渠道',
},
{
key: 48,
text: '讯飞星火认知 V2',
value: 48,
color: 'blue',
tip: 'HTTP 版本的讯飞接口,前往<a href="https://console.xfyun.cn/services/cbm" target="_blank">此处</a>获取 HTTP 服务接口认证密钥',
},
{ key: 16, text: '智谱 ChatGLM', value: 16, color: 'violet' },
{ key: 19, text: '360 智脑', value: 19, color: 'blue' },
{ key: 25, text: 'Moonshot AI', value: 25, color: 'black' },
{ key: 23, text: '腾讯混元', value: 23, color: 'teal' },
{ key: 26, text: '百川大模型', value: 26, color: 'orange' },
{ key: 27, text: 'MiniMax', value: 27, color: 'red' },
{ key: 29, text: 'Groq', value: 29, color: 'orange' },
{ key: 30, text: 'Ollama', value: 30, color: 'black' },
{ key: 31, text: '零一万物', value: 31, color: 'green' },
{ key: 32, text: '阶跃星辰', value: 32, color: 'blue' },
{ key: 34, text: 'Coze', value: 34, color: 'blue' },
{ key: 35, text: 'Cohere', value: 35, color: 'blue' },
{ key: 36, text: 'DeepSeek', value: 36, color: 'black' },
{ key: 37, text: 'Cloudflare', value: 37, color: 'orange' },
{ key: 38, text: 'DeepL', value: 38, color: 'black' },
{ key: 39, text: 'together.ai', value: 39, color: 'blue' },
{ key: 42, text: 'VertexAI', value: 42, color: 'blue' },
{ key: 43, text: 'Proxy', value: 43, color: 'blue' },
{ key: 44, text: 'SiliconFlow', value: 44, color: 'blue' },
{ key: 45, text: 'xAI', value: 45, color: 'blue' },
{ key: 46, text: 'Replicate', value: 46, color: 'blue' },
{
key: 8,
text: '自定义渠道',
value: 8,
color: 'pink',
tip: '不推荐使用,请使用 <strong>OpenAI 兼容</strong>渠道类型。注意,这里所需要填入的代理地址仅会在实际请求时替换域名部分,如果你想填入 OpenAI SDK 中所要求的 Base URL请使用 OpenAI 兼容渠道类型',
description: '不推荐使用,请使用 OpenAI 兼容渠道类型',
},
{ key: 22, text: '知识库FastGPT', value: 22, color: 'blue' },
{ key: 21, text: '知识库:AI Proxy', value: 21, color: 'purple' },
{ key: 20, text: 'OpenRouter', value: 20, color: 'black' },
{ key: 2, text: '代理API2D', value: 2, color: 'blue' },
{ key: 5, text: '代理:OpenAI-SB', value: 5, color: 'brown' },
{ key: 7, text: '代理OhMyGPT', value: 7, color: 'purple' },
{ key: 10, text: '代理:AI Proxy', value: 10, color: 'purple' },
{ key: 4, text: '代理:CloseAI', value: 4, color: 'teal' },
{ key: 6, text: '代理:OpenAI Max', value: 6, color: 'violet' },
{ key: 9, text: '代理:AI.LS', value: 9, color: 'yellow' },
{ key: 12, text: '代理API2GPT', value: 12, color: 'blue' },
{ key: 13, text: '代理AIGC2D', value: 13, color: 'purple' },
];