openai-go通过SOCKS5代理调用外网大模型

首先通过Shadowscoks配置代理成功科学上网

(具体方式自己查找)

使用curl进行测试

Gemini示例

bash 复制代码
# !/bin/bash
curl --socks5 127.0.0.1:1080 "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent" \
  -H 'Content-Type: application/json' \
  -H 'X-goog-api-key: GEMINI_API_KEY' \
  -X POST \
  -d '{
    "contents": [
      {
        "parts": [
          {
            "text": "Introduce yourself"
          }
        ]
      }
    ]
  }'

Gork示例

bash 复制代码
# !/bin/bash
curl --socks5 127.0.0.1:1080 "https://api.x.ai/v1/chat/completions" \
   -H "Content-Type: application/json" \
   -H "Authorization: Bearer X_API_KEY" \
   -d '{
     "messages": [
       {
         "role": "system",
         "content": "You are a test assistant."
       },
       {
         "role": "user",
         "content": "Testing. Just say hi and hello world and nothing else."
       }
     ],
     "model": "grok-2-latest",
     "stream": false,
     "temperature": 0
   }'

使用go语言和openai-go

go 复制代码
package main

import (
	"context"
	"fmt"
	"log"
	"net"
	"net/http"
	"time"

	"github.com/openai/openai-go/v3"
	"github.com/openai/openai-go/v3/option"
	"golang.org/x/net/proxy"
)

// newHTTPClientWithSocks5 创建一个走 SOCKS5 代理的 http.Client
func newHTTPClientWithSocks5(proxyAddr string) (*http.Client, error) {
	dialer, err := proxy.SOCKS5("tcp", proxyAddr, nil, proxy.Direct)
	if err != nil {
		return nil, fmt.Errorf("create socks5 dialer: %w", err)
	}

	transport := &http.Transport{
		DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
			// 注意:dialer.Dial 的签名是不带 context 的,因此忽略 ctx 并直接调用它。
			return dialer.Dial(network, addr)
		},
	}

	return &http.Client{Transport: transport}, nil
}

func main() {
	// 1) 安全:不要在代码中硬编码 API Key。优先从环境变量读取。
	apiKey := "GEMINI_API_KEY" // 填写实际的GEMINI_API_KEY
	baseUrl := "https://generativelanguage.googleapis.com/v1beta"
	model := "gemini-2.0-flash"
        
	// apiKey := "X_API_KEY" // 填写实际的X_API_KEY
	// baseUrl := "https://api.x.ai/v1"
	// model := "grok-2-latest"
        
	// 2) SOCKS5 代理地址,也可从环境变量或配置文件读取
	socks5Addr := "127.0.0.1:1080"
	httpClient, err := newHTTPClientWithSocks5(socks5Addr)
	if err != nil {
		log.Fatalf("failed to create http client with socks5: %v", err)
	}

	client := openai.NewClient(
		option.WithAPIKey(apiKey),
		option.WithBaseURL(baseUrl),
		option.WithHTTPClient(httpClient),
	)

	// =============== 发起请求 ===============
	// 使用带超时的 context,避免网络请求无限期挂起
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
	defer cancel()

	chatCompletion, err := client.Chat.Completions.New(ctx, openai.ChatCompletionNewParams{
		Model: model,
		Messages: []openai.ChatCompletionMessageParamUnion{
			openai.UserMessage("请详细介绍一下你自己"),
		},
	})
	if err != nil {
		// 更友好的错误处理:记录并退出
		log.Fatalf("chat completion request failed: %v", err)
	}

	fmt.Println("Gemini Response:")
	if len(chatCompletion.Choices) == 0 {
		fmt.Println("no choices returned")
		return
	}
	fmt.Println(chatCompletion.Choices[0].Message.Content)
}
相关推荐
todoitbo1 分钟前
本地图库语义搜索实战:接上蓝耘元生代,让“傍晚的海边“能搜到图
人工智能·ai·api·工具实战
羊羊小栈6 分钟前
基于「YOLO目标检测 + 多模态AI分析」的水稻病害智能检测分析预警系统(LangChain框架)
人工智能·yolo·目标检测·毕业设计·创业创新·大作业
IT_陈寒8 分钟前
Vue的响应式让我熬到凌晨三点,原来漏了这个小细节
前端·人工智能·后端
lisw0511 分钟前
提升社会科学领域的计算可重复性
人工智能·数字时代
HyperAI超神经15 分钟前
HyperAI 入选 36氪「East Forward 2026 出海全球化拓新企业」
人工智能·深度学习·全球化企业
9呀18 分钟前
VS Code Codex 多窗口使用与补丁记录
人工智能
七仔啊21 分钟前
安防通行人脸抓拍识别
人工智能
颜进强41 分钟前
01 · NestJS 是什么:用途、解决什么问题、与热门框架对比
前端·后端·ai编程
isfox1 小时前
MapReduce Shuffle 深度解析:数据从 Map 到 Reduce 的完整旅程
后端
guoran_shini1 小时前
SVD矩阵分解
人工智能