|
150刀自用还是不错的,翻译啥的。
有几个坑,不支持内地、香港的主机,地区不可用,我找了个日本的可以用。

运行后通过post http://服务器地址:8089/ask
body格式
{
"prompt": "AdGuard 9设备终身价格仅需16刀折合人民币116元"
}
go写的,自行替换key编译一下就能用,端口和细节按需修改。
#main.go 源代码
- package main
- import (
- "bytes"
- "encoding/json"
- "fmt"
- "io"
- "net/http"
- "time"
- )
- // xAiRequest 定义请求结构体
- type xAiRequest struct {
- Prompt string `json:"prompt"`
- }
- // xAiResponse 定义简化后的响应结构体
- type xAiResponse struct {
- Content string `json:"content"`
- }
- // Message 定义消息结构体
- type Message struct {
- Role string `json:"role"`
- Content string `json:"content"`
- }
- // APIRequest 定义API请求结构体
- type APIRequest struct {
- Messages []Message `json:"messages"`
- Model string `json:"model"`
- }
- func main() {
- http.HandleFunc("/ask", func(w http.ResponseWriter, r *http.Request) {
- // 解析请求体
- var req xAiRequest
- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
- http.Error(w, fmt.Sprintf("解析请求失败: %v", err), http.StatusBadRequest)
- return
- }
- // 调用xAi API
- xAiResponse, err := callxAiAPI(req.Prompt)
- if err != nil {
- http.Error(w, fmt.Sprintf("调用API失败: %v", err), http.StatusInternalServerError)
- return
- }
- // 返回响应
- w.Header().Set("Content-Type", "application/json")
- if err := json.NewEncoder(w).Encode(xAiResponse); err != nil {
- http.Error(w, fmt.Sprintf("编码响应失败: %v", err), http.StatusInternalServerError)
- return
- }
- })
- // 启动HTTP服务器
- server := &http.Server{
- Addr: ":8089",
- ReadTimeout: 10 * time.Second,
- WriteTimeout: 10 * time.Second,
- }
- fmt.Println("服务器正在运行,监听端口 8089...")
- if err := server.ListenAndServe(); err != nil {
- fmt.Printf("服务器启动失败: %v\n", err)
- }
- }
- // callxAiAPI 调用xAi API
- func callxAiAPI(prompt string) (*xAiResponse, error) {
- url := "https://api.x.ai/v1/chat/completions"
- // 创建请求体
- requestBody, err := json.Marshal(APIRequest{
- Messages: []Message{
- {
- Role: "user", // 角色为用户
- Content: prompt, // 用户输入的内容
- },
- },
- Model: "grok-2-latest", // 模型名称
- })
- if err != nil {
- return nil, fmt.Errorf("创建请求体失败: %v", err)
- }
- // 创建HTTP请求
- req, err := http.NewRequest("POST", url, bytes.NewBuffer(requestBody))
- if err != nil {
- return nil, fmt.Errorf("创建HTTP请求失败: %v", err)
- }
- // 添加Authorization头
- req.Header.Set("Authorization", "Bearer 改成你的key")
- req.Header.Set("Content-Type", "application/json")
- // 发送请求
- client := &http.Client{
- Timeout: 10 * time.Second, // 设置超时时间
- }
- resp, err := client.Do(req)
- if err != nil {
- return nil, fmt.Errorf("发送请求失败: %v", err)
- }
- defer resp.Body.Close()
- // 读取响应体
- body, err := io.ReadAll(resp.Body)
- if err != nil {
- return nil, fmt.Errorf("读取响应体失败: %v", err)
- }
-
- // 打印 HTTP 状态码和响应体
- fmt.Printf("HTTP Status Code: %d\n", resp.StatusCode)
- fmt.Printf("Response Body: %s\n", string(body))
- // 检查响应状态码
- if resp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("API请求失败,状态码: %d, 响应: %s", resp.StatusCode, string(body))
- }
- // 解析响应体
- var apiResponse struct {
- Choices []struct {
- Message struct {
- Content string `json:"content"`
- } `json:"message"`
- } `json:"choices"`
- }
- if err := json.Unmarshal(body, &apiResponse); err != nil {
- return nil, fmt.Errorf("解析响应体失败: %v", err)
- }
- // 提取并返回content字段
- if len(apiResponse.Choices) > 0 {
- return &xAiResponse{
- Content: apiResponse.Choices[0].Message.Content,
- }, nil
- }
- return nil, fmt.Errorf("API响应格式错误,没有找到content")
- }
复制代码 |
|