mirror of
https://github.com/RuoJi6/ARTEX.git
synced 2026-11-23 01:21:51 +08:00
54 lines
1.7 KiB
Go
54 lines
1.7 KiB
Go
// Package llmhttp contains the shared outbound HTTP client construction used by
|
|
// LLM endpoints. An empty proxy deliberately means direct and does not inherit
|
|
// HTTP_PROXY/HTTPS_PROXY from the process environment.
|
|
package llmhttp
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"net"
|
|
"net/http"
|
|
"net/url"
|
|
"strings"
|
|
|
|
"golang.org/x/net/proxy"
|
|
)
|
|
|
|
// NewClient builds an HTTP client for an LLM endpoint. Supported proxies are
|
|
// http, https, and socks5, matching the profile configuration contract.
|
|
func NewClient(rawProxy string) (*http.Client, error) {
|
|
transport := http.DefaultTransport.(*http.Transport).Clone()
|
|
rawProxy = strings.TrimSpace(rawProxy)
|
|
if rawProxy == "" {
|
|
transport.Proxy = nil
|
|
} else {
|
|
proxyURL, err := url.Parse(rawProxy)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("llm: invalid proxy %q: %w", rawProxy, err)
|
|
}
|
|
switch proxyURL.Scheme {
|
|
case "http", "https":
|
|
transport.Proxy = http.ProxyURL(proxyURL)
|
|
case "socks5":
|
|
auth := proxy.Auth{}
|
|
if user := proxyURL.User; user != nil {
|
|
auth.User = user.Username()
|
|
auth.Password, _ = user.Password()
|
|
}
|
|
dialer, err := proxy.SOCKS5("tcp", proxyURL.Host, &auth, proxy.Direct)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("llm: invalid socks5 proxy %q: %w", rawProxy, err)
|
|
}
|
|
transport.Proxy = nil
|
|
transport.DialContext = func(_ context.Context, network, address string) (net.Conn, error) {
|
|
return dialer.Dial(network, address)
|
|
}
|
|
case "":
|
|
return nil, fmt.Errorf("llm: proxy %q missing scheme (use http://, https:// or socks5://)", rawProxy)
|
|
default:
|
|
return nil, fmt.Errorf("llm: unsupported proxy scheme %q (use http, https or socks5)", proxyURL.Scheme)
|
|
}
|
|
}
|
|
return &http.Client{Transport: transport}, nil
|
|
}
|