From 506a68be0c5dd672de3cad54e70e04b3e731873f Mon Sep 17 00:00:00 2001 From: ljn Date: Fri, 22 Dec 2023 15:08:17 +0800 Subject: [PATCH] init --- .env | 2 + .gitignore | 1 + Makefile | 45 +++++++++ README.md | 57 ++++++++++- go.mod | 38 +++++++ go.sum | 97 ++++++++++++++++++ main.go | 284 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 7 files changed, 522 insertions(+), 2 deletions(-) create mode 100644 .env create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 go.mod create mode 100644 go.sum create mode 100644 main.go diff --git a/.env b/.env new file mode 100644 index 0000000..6b8d60b --- /dev/null +++ b/.env @@ -0,0 +1,2 @@ +PORT=8081 +GHU_TOKEN= \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..5c40354 --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +copilot2gpt diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..bca4db3 --- /dev/null +++ b/Makefile @@ -0,0 +1,45 @@ +# Binary name +BINARY=copilot2gpt +# 构建目录 +DIST_DIR := ./dist +# Builds the project +build: + GO111MODULE=on go build -o ${BINARY} -ldflags "-X main.Version=${VERSION}" +# GO111MODULE=on go test -v +# Installs our project: copies binaries +install: + GO111MODULE=on go install +release: + # Clean + go clean + rm -rf ${DIST_DIR}/*.gz + # Build for mac + GO111MODULE=on go build -ldflags "-s -w -X main.Version=${VERSION}" + tar czvf ${DIST_DIR}/${BINARY}-mac64-${VERSION}.tar.gz ./${BINARY} .env + # Build for arm + go clean + CGO_ENABLED=0 GOOS=linux GOARCH=arm64 GO111MODULE=on go build -ldflags "-s -w -X main.Version=${VERSION}" + tar czvf ${DIST_DIR}/${BINARY}-arm64-${VERSION}.tar.gz ./${BINARY} .env + # Build for linux386 + go clean + CGO_ENABLED=0 GOOS=linux GOARCH=386 GO111MODULE=on go build -ldflags "-s -w -X main.Version=${VERSION}" + tar czvf ${DIST_DIR}/${BINARY}-linux386-${VERSION}.tar.gz ./${BINARY} .env + # Build for linux + go clean + CGO_ENABLED=0 GOOS=linux GOARCH=amd64 GO111MODULE=on go build -ldflags "-s -w -X main.Version=${VERSION}" + tar czvf ${DIST_DIR}/${BINARY}-linux64-${VERSION}.tar.gz ./${BINARY} .env + # Build for win386 + go clean + CGO_ENABLED=0 GOOS=windows GOARCH=386 GO111MODULE=on go build -ldflags "-s -w -X main.Version=${VERSION}" + tar czvf ${DIST_DIR}/${BINARY}-win386-${VERSION}.tar.gz ./${BINARY}.exe .env + # Build for win + go clean + CGO_ENABLED=0 GOOS=windows GOARCH=amd64 GO111MODULE=on go build -ldflags "-s -w -X main.Version=${VERSION}" + tar czvf ${DIST_DIR}/${BINARY}-win64-${VERSION}.tar.gz ./${BINARY}.exe .env + go clean +# Cleans our projects: deletes binaries +clean: + go clean + rm -rf ${DIST_DIR}/*.gz + +.PHONY: clean build \ No newline at end of file diff --git a/README.md b/README.md index 39d5bfb..9ab2809 100644 --- a/README.md +++ b/README.md @@ -1,2 +1,55 @@ -# cocopilot2gpt -cocopilot2gpt +# 将你的 copilot 转成 ChatGPT API(支持GPT4) + + + +## 使用声明❗❗❗ + +> 本项目可以导致你的 copilt 账号被封,请谨慎使用。 + + + +## ghu token 获取 + + + +点击链接:[cocopilot](https://cocopilot.org/copilot/token),根据提示拿到 ghu_xxxx 格式的 token。务必保存好,不要泄露给其他人。 + +## 下载程序 + +点击右侧的 release 下载跟你运行环境一致的可执行文件 + +## 运行程序 + +`./copilot2gpt` + +默认监听端口为 8081,可以在 .env 中修改 + +## 使用方式 + +可以在任意第三方客户端使用 + +API 域名:http://127.0.0.1:8081 + +API token:ghu_xxx + +curl 测试 + +``` bash +curl --location 'http://127.0.0.1:8081/v1/chat/completions' \ +--header 'Content-Type: application/json' \ +--header 'Authorization: Bearer ghu_xxx' \ +--data '{ + "stream": "true", + "model": "gpt-4", + "messages": [{"role": "user", "content": "hi"}] +}' +``` + + + +## 感谢以下项目,灵感来自于VV佬 + +[CaoYunzhou/cocopilot-gpt](https://github.com/CaoYunzhou/cocopilot-gpt) + +[lvguanjun/copilot_to_chatgpt4](https://github.com/lvguanjun/copilot_to_chatgpt4) + diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..c9c1fc0 --- /dev/null +++ b/go.mod @@ -0,0 +1,38 @@ +module copilot2gpt + +go 1.21.0 + +require ( + github.com/bytedance/sonic v1.10.2 // indirect + github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d // indirect + github.com/chenzhuoyu/iasm v0.9.1 // indirect + github.com/gabriel-vasile/mimetype v1.4.3 // indirect + github.com/gin-contrib/sse v0.1.0 // indirect + github.com/gin-gonic/gin v1.9.1 // indirect + github.com/go-playground/locales v0.14.1 // indirect + github.com/go-playground/universal-translator v0.18.1 // indirect + github.com/go-playground/validator/v10 v10.16.0 // indirect + github.com/goccy/go-json v0.10.2 // indirect + github.com/google/uuid v1.5.0 // indirect + github.com/joho/godotenv v1.5.1 // indirect + github.com/json-iterator/go v1.1.12 // indirect + github.com/klauspost/cpuid/v2 v2.2.6 // indirect + github.com/leodido/go-urn v1.2.4 // indirect + github.com/mattn/go-isatty v0.0.20 // indirect + github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect + github.com/modern-go/reflect2 v1.0.2 // indirect + github.com/patrickmn/go-cache v2.1.0+incompatible // indirect + github.com/pelletier/go-toml/v2 v2.1.1 // indirect + github.com/tidwall/gjson v1.17.0 // indirect + github.com/tidwall/match v1.1.1 // indirect + github.com/tidwall/pretty v1.2.0 // indirect + github.com/twitchyliquid64/golang-asm v0.15.1 // indirect + github.com/ugorji/go/codec v1.2.12 // indirect + golang.org/x/arch v0.6.0 // indirect + golang.org/x/crypto v0.16.0 // indirect + golang.org/x/net v0.19.0 // indirect + golang.org/x/sys v0.15.0 // indirect + golang.org/x/text v0.14.0 // indirect + google.golang.org/protobuf v1.31.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..be168a1 --- /dev/null +++ b/go.sum @@ -0,0 +1,97 @@ +github.com/bytedance/sonic v1.5.0/go.mod h1:ED5hyg4y6t3/9Ku1R6dU/4KyJ48DZ4jPhfY1O2AihPM= +github.com/bytedance/sonic v1.10.0-rc/go.mod h1:ElCzW+ufi8qKqNW0FY314xriJhyJhuoJ3gFZdAHF7NM= +github.com/bytedance/sonic v1.10.2 h1:GQebETVBxYB7JGWJtLBi07OVzWwt+8dWA00gEVW2ZFE= +github.com/bytedance/sonic v1.10.2/go.mod h1:iZcSUejdk5aukTND/Eu/ivjQuEL0Cu9/rf50Hi0u/g4= +github.com/chenzhuoyu/base64x v0.0.0-20211019084208-fb5309c8db06/go.mod h1:DH46F32mSOjUmXrMHnKwZdA8wcEefY7UVqBKYGjpdQY= +github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311/go.mod h1:b583jCggY9gE99b6G5LEC39OIiVsWj+R97kbl5odCEk= +github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d h1:77cEq6EriyTZ0g/qfRdp61a3Uu/AWrgIq2s0ClJV1g0= +github.com/chenzhuoyu/base64x v0.0.0-20230717121745-296ad89f973d/go.mod h1:8EPpVsBuRksnlj1mLy4AWzRNQYxauNi62uWcE3to6eA= +github.com/chenzhuoyu/iasm v0.9.0/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= +github.com/chenzhuoyu/iasm v0.9.1 h1:tUHQJXo3NhBqw6s33wkGn9SP3bvrWLdlVIJ3hQBL7P0= +github.com/chenzhuoyu/iasm v0.9.1/go.mod h1:Xjy2NpN3h7aUqeqM+woSuuvxmIe6+DDsiNLIrkAmYog= +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0= +github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk= +github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE= +github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI= +github.com/gin-gonic/gin v1.9.1 h1:4idEAncQnU5cB7BeOkPtxjfCSye0AAm1R0RVIqJ+Jmg= +github.com/gin-gonic/gin v1.9.1/go.mod h1:hPrL7YrpYKXt5YId3A/Tnip5kqbEAP+KLuI3SUcPTeU= +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= +github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY= +github.com/go-playground/validator/v10 v10.16.0 h1:x+plE831WK4vaKHO/jpgUGsvLKIqRRkz6M78GuJAfGE= +github.com/go-playground/validator/v10 v10.16.0/go.mod h1:9iXMNT7sEkjXb0I+enO7QXmzG6QCsPWY4zveKFVRSyU= +github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU= +github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I= +github.com/golang/protobuf v1.5.0/go.mod h1:FsONVRAS9T7sI+LIUmWTfcYkHO4aIWwzhcaSAoJOfIk= +github.com/google/go-cmp v0.5.5/go.mod h1:v8dTdLbMG2kIc/vJvl+f65V22dbkXbowE6jgT/gNBxE= +github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg= +github.com/google/uuid v1.5.0 h1:1p67kYwdtXjb0gL0BPiP1Av9wiZPo5A8z2cWkTZ+eyU= +github.com/google/uuid v1.5.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/joho/godotenv v1.5.1 h1:7eLL/+HRGLY0ldzfGMeQkb7vMd0as4CfYvUVzLqw0N0= +github.com/joho/godotenv v1.5.1/go.mod h1:f4LDr5Voq0i2e/R5DDNOoa2zzDfwtkZa6DnEwAbqwq4= +github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM= +github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= +github.com/klauspost/cpuid/v2 v2.2.6 h1:ndNyv040zDGIDh8thGkXYjnFtiN02M1PVVF+JE/48xc= +github.com/klauspost/cpuid/v2 v2.2.6/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws= +github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M= +github.com/leodido/go-urn v1.2.4 h1:XlAE/cm/ms7TE/VMVoduSpNBoyc2dOxHs5MZSwAN63Q= +github.com/leodido/go-urn v1.2.4/go.mod h1:7ZrI8mTSeBSHl/UaRyKQW1qZeMgak41ANeCNaVckg+4= +github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY= +github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y= +github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg= +github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q= +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/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.1.1 h1:LWAJwfNvjQZCFIDKWYQaM62NcYeYViCmWIwmOStowAI= +github.com/pelletier/go-toml/v2 v2.1.1/go.mod h1:tJU2Z3ZkXwnxa4DPO899bsyIoywizdUvyaeZurnPPDc= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw= +github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.2/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo= +github.com/tidwall/gjson v1.17.0 h1:/Jocvlh98kcTfpN2+JzGQWQcqrPQwDrVEMApx/M5ZwM= +github.com/tidwall/gjson v1.17.0/go.mod h1:/wbyibRr2FHMks5tjHJ5F8dMZh3AcwJEMf5vlfC0lxk= +github.com/tidwall/match v1.1.1 h1:+Ho715JplO36QYgwN9PGYNhgZvoUSc9X2c80KVTi+GA= +github.com/tidwall/match v1.1.1/go.mod h1:eRSPERbgtNPcGhD8UCthc6PmLEQXEWd3PRB5JTxsfmM= +github.com/tidwall/pretty v1.2.0 h1:RWIZEg2iJ8/g6fDDYzMpobmaoGh5OLl4AXtGUGPcqCs= +github.com/tidwall/pretty v1.2.0/go.mod h1:ITEVvHYasfjBbM0u2Pg8T2nJnzm8xPwvNhhsoaGGjNU= +github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI= +github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08= +github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE= +github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg= +golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8= +golang.org/x/arch v0.6.0 h1:S0JTfE48HbRj80+4tbvZDYsJ3tGv6BUU3XxyZ7CirAc= +golang.org/x/arch v0.6.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys= +golang.org/x/crypto v0.16.0 h1:mMMrFzRSCF0GvB7Ne27XVtVAaXLrPmgPC7/v0tkwHaY= +golang.org/x/crypto v0.16.0/go.mod h1:gCAAfMLgwOJRpTjQ2zCCt2OcSfYMTeZVSRtQlPC7Nq4= +golang.org/x/net v0.19.0 h1:zTwKpTd2XuCqf8huc7Fo2iSy+4RHPd10s4KzeTnVr1c= +golang.org/x/net v0.19.0/go.mod h1:CfAk/cbD4CthTvqiEl8NpboMuiuOYsAr/7NOjZJtv1U= +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.15.0 h1:h48lPFYpsTvQJZF4EKyI4aLHaev3CxivZmv7yZig9pc= +golang.org/x/sys v0.15.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0= +google.golang.org/protobuf v1.26.0-rc.1/go.mod h1:jlhhOSvTdKEhbULTjvd4ARK9grFBp09yW+WbY/TyQbw= +google.golang.org/protobuf v1.31.0 h1:g0LDEJHgrBl9N9r17Ru3sqWhkIx2NB67okBHPwC7hs8= +google.golang.org/protobuf v1.31.0/go.mod h1:HV8QOd/L58Z+nl8r43ehVNZIU/HEI6OcFqwMG9pJV4I= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +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= +nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50= +rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4= diff --git a/main.go b/main.go new file mode 100644 index 0000000..4de2d2b --- /dev/null +++ b/main.go @@ -0,0 +1,284 @@ +package main + +import ( + "bufio" + "bytes" + "compress/gzip" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "fmt" + "io" + "log" + "net/http" + "os" + "strings" + "time" + + "github.com/gin-gonic/gin" + "github.com/google/uuid" + "github.com/joho/godotenv" + "github.com/patrickmn/go-cache" + "github.com/tidwall/gjson" +) + +const tokenUrl = "https://api.github.com/copilot_internal/v2/token" +const completionsUrl = "https://api.githubcopilot.com/chat/completions" + +type Model struct { + ID string `json:"id"` + Object string `json:"object"` + Created int `json:"created"` + OwnedBy string `json:"owned_by"` + Root string `json:"root"` + Parent *string `json:"parent"` +} + +type ModelList struct { + Object string `json:"object"` + Data []Model `json:"data"` +} + +var port = "8080" +var ghuToken = "" + +func main() { + err := godotenv.Load() + if err == nil { + // 从环境变量中获取配置值 + portEnv := os.Getenv("PORT") + if portEnv != "" { + port = portEnv + } + ghuToken = os.Getenv("GHU_TOKEN") + } + + log.Printf("Server is running on port %s, with ghu: %s", port, ghuToken) + + gin.SetMode(gin.ReleaseMode) + + r := gin.Default() + + // CORS 中间件 + r.Use(func(c *gin.Context) { + c.Writer.Header().Set("Access-Control-Allow-Origin", "*") + c.Writer.Header().Set("Access-Control-Allow-Credentials", "true") + c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Content-Length, Accept-Encoding, X-CSRF-Token, Authorization, accept, origin, Cache-Control, X-Requested-With") + c.Writer.Header().Set("Access-Control-Allow-Methods", "POST, OPTIONS, GET, PUT") + + if c.Request.Method == "OPTIONS" { + c.AbortWithStatus(204) + return + } + + c.Next() + }) + + r.GET("/", func(c *gin.Context) { + c.JSON(http.StatusOK, "") + }) + + r.GET("/v1/models", func(c *gin.Context) { + c.JSON(http.StatusOK, models()) + }) + + r.POST("/v1/chat/completions", func(c *gin.Context) { + c.Header("Cache-Control", "no-cache, must-revalidate") + c.Header("Connection", "keep-alive") + + forwardRequest(c) + }) + + r.Run(":" + port) +} + +func forwardRequest(c *gin.Context) { + var jsonBody map[string]interface{} + if err := c.ShouldBindJSON(&jsonBody); err != nil { + c.JSON(http.StatusBadRequest, gin.H{"error": "Request body is missing or not in JSON format"}) + return + } + + if ghuToken == "" { + ghuToken = strings.Split(c.GetHeader("Authorization"), " ")[1] + } + + if ghuToken == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": "gho_token not found"}) + return + } + accToken, err := getAccToken(ghuToken) + if accToken == "" { + c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()}) + return + } + + sessionId := fmt.Sprintf("%s%d", uuid.New().String(), time.Now().UnixNano()/int64(time.Millisecond)) + machineID := sha256.Sum256([]byte(uuid.New().String())) + machineIDStr := hex.EncodeToString(machineID[:]) + accHeaders := getAccHeaders(accToken, uuid.New().String(), sessionId, machineIDStr) + client := &http.Client{} + + jsonData, err := json.Marshal(jsonBody) + if err != nil { + c.AbortWithError(http.StatusInternalServerError, err) + return + } + + req, err := http.NewRequest("POST", completionsUrl, bytes.NewBuffer(jsonData)) + if err != nil { + c.AbortWithError(http.StatusInternalServerError, err) + } + + for key, value := range accHeaders { + req.Header.Add(key, value) + } + + resp, err := client.Do(req) + if err != nil { + return + } + defer resp.Body.Close() + + if resp.StatusCode != http.StatusOK { + bodyBytes, err := io.ReadAll(resp.Body) + if err != nil { + log.Fatal(err) + } + bodyString := string(bodyBytes) + log.Printf("对话失败:%d, %s ", resp.StatusCode, bodyString) + cache := cache.New(5*time.Minute, 10*time.Minute) + cache.Delete("token") + c.AbortWithError(resp.StatusCode, err) + return + } + + c.Header("Content-Type", "text/event-stream; charset=utf-8") + + // 创建一个缓冲读取器 + reader := bufio.NewReader(resp.Body) + + // 读取流并替换 "content":null 为 "content":"" + for { + line, err := reader.ReadBytes('\n') + if err == io.EOF { + break + } + if err != nil { + c.AbortWithError(http.StatusInternalServerError, err) + return + } + + // 替换 "content":null 为 "content":"" + modifiedLine := bytes.Replace(line, []byte(`"content":null`), []byte(`"content":""`), -1) + + // 将修改后的数据写入响应体 + if _, err := c.Writer.Write(modifiedLine); err != nil { + c.AbortWithError(http.StatusInternalServerError, err) + return + } + } + return +} + +func models() ModelList { + jsonStr := `{ + "object": "list", + "data": [ + {"id": "gpt-4-0314", "object": "model", "created": 1687882410, "owned_by": "openai", "root": "gpt-4-0314", "parent": null}, + {"id": "gpt-4-0613", "object": "model", "created": 1686588896, "owned_by": "openai", "root": "gpt-4-0613", "parent": null}, + {"id": "gpt-4", "object": "model", "created": 1687882411, "owned_by": "openai", "root": "gpt-4", "parent": null}, + {"id": "gpt-3.5-turbo", "object": "model", "created": 1677610602, "owned_by": "openai", "root": "gpt-3.5-turbo", "parent": null}, + {"id": "gpt-3.5-turbo-0301", "object": "model", "created": 1677649963, "owned_by": "openai", "root": "gpt-3.5-turbo-0301", "parent": null} + ] + }` + + var modelList ModelList + json.Unmarshal([]byte(jsonStr), &modelList) + return modelList +} + +func getAccToken(ghuToken string) (string, error) { + var accToken = "" + + cache := cache.New(15*time.Minute, 60*time.Minute) + cacheToken, found := cache.Get("token") + if found { + accToken = cacheToken.(string) + } else { + client := &http.Client{} + req, err := http.NewRequest("GET", tokenUrl, nil) + if err != nil { + return accToken, err + } + + headers := getHeaders(ghuToken) + + for key, value := range headers { + req.Header.Add(key, value) + } + + resp, err := client.Do(req) + if err != nil { + return accToken, err + } + defer resp.Body.Close() + + var reader interface{} + switch resp.Header.Get("Content-Encoding") { + case "gzip": + reader, err = gzip.NewReader(resp.Body) + if err != nil { + return accToken, fmt.Errorf("数据解压失败") + } + default: + reader = resp.Body + } + + body, err := io.ReadAll(reader.(io.Reader)) + if err != nil { + return accToken, fmt.Errorf("数据读取失败") + } + if resp.StatusCode == http.StatusOK { + accToken = gjson.GetBytes(body, "token").String() + if accToken == "" { + return accToken, fmt.Errorf("acc_token 未返回") + } + cache.Set("token", accToken, 14*time.Minute) + } else { + log.Printf("获取 acc_token 请求失败:%d, %s ", resp.StatusCode, string(body)) + return accToken, fmt.Errorf("获取 acc_token 请求失败: %d", resp.StatusCode) + } + } + return accToken, nil +} + +func getHeaders(ghoToken string) map[string]string { + return map[string]string{ + "Host": "api.github.com", + "Authorization": "token " + ghoToken, + "Editor-Version": "vscode/1.84.2", + "Editor-Plugin-Version": "copilot/1.138.0", + "User-Agent": "GithubCopilot/1.138.0", + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate, br", + "Connection": "close", + } +} + +func getAccHeaders(accessToken, uuid string, sessionId string, machineId string) map[string]string { + return map[string]string{ + "Authorization": "Bearer " + accessToken, + "X-Request-Id": uuid, + "Vscode-Sessionid": sessionId, + "Vscode-machineid": machineId, + "Editor-Version": "vscode/1.84.2", + "Editor-Plugin-Version": "copilot-chat/0.10.2", + "Openai-Organization": "github-copilot", + "Openai-Intent": "conversation-panel", + "Content-Type": "application/json", + "User-Agent": "GitHubCopilotChat/0.10.2", + "Accept": "*/*", + "Accept-Encoding": "gzip, deflate, br", + } +}