feat: 添加 SOCKS5 和 HTTP/HTTPS 代理支持,以优化 OpenAI API 的网络请求
This commit is contained in:
parent
131e273e5f
commit
22aa541bd1
@ -3,6 +3,10 @@ package headmaster
|
|||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
|
"net"
|
||||||
|
"net/http"
|
||||||
|
"net/url"
|
||||||
"strings"
|
"strings"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@ -12,6 +16,7 @@ import (
|
|||||||
"git.lxtend.com/qqbot/model"
|
"git.lxtend.com/qqbot/model"
|
||||||
"git.lxtend.com/qqbot/util"
|
"git.lxtend.com/qqbot/util"
|
||||||
"github.com/sashabaranov/go-openai"
|
"github.com/sashabaranov/go-openai"
|
||||||
|
"golang.org/x/net/proxy"
|
||||||
)
|
)
|
||||||
|
|
||||||
var (
|
var (
|
||||||
@ -49,6 +54,36 @@ func ask(from string, question string) (reply string) {
|
|||||||
llmConfig := openai.DefaultAzureConfig(config.ConfigManager.GetConfig().OpenaiApiKey, config.ConfigManager.GetConfig().OpenaiApiBaseUrl)
|
llmConfig := openai.DefaultAzureConfig(config.ConfigManager.GetConfig().OpenaiApiKey, config.ConfigManager.GetConfig().OpenaiApiBaseUrl)
|
||||||
llmConfig.APIType = openai.APITypeOpenAI
|
llmConfig.APIType = openai.APITypeOpenAI
|
||||||
llmConfig.APIVersion = ""
|
llmConfig.APIVersion = ""
|
||||||
|
if config.ConfigManager.GetConfig().Management.ProxyAddr != "" {
|
||||||
|
proxyURL, err := url.Parse(config.ConfigManager.GetConfig().Management.ProxyAddr)
|
||||||
|
if err != nil {
|
||||||
|
log.Printf("解析代理地址失败: %v\n", err)
|
||||||
|
} else {
|
||||||
|
if proxyURL.Scheme == "socks5" {
|
||||||
|
dialer, err := proxy.SOCKS5("tcp", proxyURL.Host, nil, proxy.Direct)
|
||||||
|
if err == nil {
|
||||||
|
llmConfig.HTTPClient = &http.Client{
|
||||||
|
Timeout: 10 * time.Second,
|
||||||
|
Transport: &http.Transport{
|
||||||
|
Dial: func(network, addr string) (net.Conn, error) {
|
||||||
|
return dialer.Dial(network, addr)
|
||||||
|
},
|
||||||
|
},
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
log.Printf("创建SOCKS5代理失败: %v\n", err)
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
// 使用 HTTP/HTTPS 代理
|
||||||
|
llmConfig.HTTPClient = &http.Client{
|
||||||
|
Timeout: 10 * time.Second,
|
||||||
|
Transport: &http.Transport{
|
||||||
|
Proxy: http.ProxyURL(proxyURL),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
client := openai.NewClientWithConfig(llmConfig)
|
client := openai.NewClientWithConfig(llmConfig)
|
||||||
resp, err := client.CreateChatCompletion(
|
resp, err := client.CreateChatCompletion(
|
||||||
context.Background(),
|
context.Background(),
|
||||||
|
Loading…
x
Reference in New Issue
Block a user