qwen3.8-flash

最后更新:2026-11-14

POSThttps://www.sagelib.com/chat/completions

qwen3.8-flash 模型的聊天生成接口,OpenAI兼容,支持多轮上下文、流式输出、工具调用、结构化输出等。

接口鉴权方式请参考:API接入与鉴权

请求参数

请求头

参数名称 描述
*Authorization string 鉴权令牌,格式为 Bearer ${AIGATEWAY_TOKEN}
*Content-Type string 默认值:application/json
可选值:application/json
内容类型,固定为 application/json

Body 参数

参数名称 描述
*model string 可选值:"qwen3.8-flash"
模型名称,须精确匹配
*messages array 可选值:Object array with role+content
对话消息列表
max_tokens integer 可选值:Positive integer
生成最大 token 数
temperature float 默认值:0.7
可选值:Open interval [0,2)
采样温度,值越大输出越随机
top_p float 默认值:0.8
可选值:(0,1.0]
核采样概率阈值
top_k integer 默认值:20
可选值:Positive integer; null or >100 disables it
采样候选集大小
tools array 可选值:OpenAI format type:"function"+function.parameters
工具定义数组,模型可据此发起工具调用
tool_choice string 默认值:auto
可选值:auto、none
工具调用策略
stream boolean 默认值:false
可选值:true、false
是否 SSE 流式返回
max_completion_tokens integer 可选值:Positive integer
生成回复(含思维链)最大 token 数
seed integer 默认值:1234
可选值:Integer
随机种子,结果可复现
stop string 可选值:String or string array
停止序列
enable_search boolean 默认值:false
可选值:true、false
是否启用联网搜索
thinking_budget integer 默认值:131072
可选值:low→4096, medium→16384, xhigh→262144
思维链最大 token 数
presence_penalty float 默认值:1.5
可选值:[-2.0, 2.0]
存在惩罚
n integer 默认值:1
可选值:1 ~ 4
生成条数
logprobs boolean 默认值:false
可选值:true、false
是否返回输出 token 对数概率
top_logprobs integer 默认值:0
可选值:0 ~ 5
返回概率最高前 N 个 token 对数概率
stream_options object 可选值:Contains include_usage
流式附加选项(include_usage 控制末帧返回 usage)
response_format object 可选值:{"type":"text"} / {"type":"json_object"}
结构化输出格式
parallel_tool_calls boolean 默认值:false
可选值:true、false
是否允许并行工具调用
reasoning_effort string 默认值:xhigh
可选值:xhigh、medium、low
思考强度档位
search_options object 可选值:enable_source、enable_citation、forced_search、search_strategy
联网搜索高级选项

请求示例

curl -v 'https://www.sagelib.com/chat/completions' \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-flash",
    "messages": [
      {
        "role": "user",
        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
      }
    ]
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your Bearer token

url = f"https://www.sagelib.com/chat/completions"

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}

data = {
    "model": "qwen3.8-flash",
    "messages": [
        {
            "role": "user",
            "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
        }
    ]
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/chat/completions";

        String jsonRequestBody = """
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                    }
                ]
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/chat/completions"

    jsonRequestBody := `
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                    }
                ]
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}
curl -v 'https://www.sagelib.com/chat/completions' \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-flash",
    "messages": [
      {
        "role": "user",
        "content": "How is the weather in Beijing today? Please use a tool to query the weather."
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "Get weather information for a specified city",
          "parameters": {
            "type": "object",
            "properties": {
              "city": {
                "type": "string"
              }
            },
            "required": [
              "city"
            ]
          }
        }
      }
    ]
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your Bearer token

url = f"https://www.sagelib.com/chat/completions"

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}

data = {
    "model": "qwen3.8-flash",
    "messages": [
        {
            "role": "user",
            "content": "How is the weather in Beijing today? Please use a tool to query the weather."
        }
    ],
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get weather information for a specified city",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": {
                            "type": "string"
                        }
                    },
                    "required": [
                        "city"
                    ]
                }
            }
        }
    ]
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/chat/completions";

        String jsonRequestBody = """
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "How is the weather in Beijing today? Please use a tool to query the weather."
                    }
                ],
                "tools": [
                    {
                        "type": "function",
                        "function": {
                            "name": "get_weather",
                            "description": "Get weather information for a specified city",
                            "parameters": {
                                "type": "object",
                                "properties": {
                                    "city": {
                                        "type": "string"
                                    }
                                },
                                "required": [
                                    "city"
                                ]
                            }
                        }
                    }
                ]
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/chat/completions"

    jsonRequestBody := `
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "How is the weather in Beijing today? Please use a tool to query the weather."
                    }
                ],
                "tools": [
                    {
                        "type": "function",
                        "function": {
                            "name": "get_weather",
                            "description": "Get weather information for a specified city",
                            "parameters": {
                                "type": "object",
                                "properties": {
                                    "city": {
                                        "type": "string"
                                    }
                                },
                                "required": [
                                    "city"
                                ]
                            }
                        }
                    }
                ]
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}
curl -v 'https://www.sagelib.com/chat/completions' \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-flash",
    "messages": [
      {
        "role": "user",
        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
      }
    ],
    "response_format": {
      "type": "text"
    }
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your Bearer token

url = f"https://www.sagelib.com/chat/completions"

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}

data = {
    "model": "qwen3.8-flash",
    "messages": [
        {
            "role": "user",
            "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
        }
    ],
    "response_format": {
        "type": "text"
    }
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/chat/completions";

        String jsonRequestBody = """
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                    }
                ],
                "response_format": {
                    "type": "text"
                }
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/chat/completions"

    jsonRequestBody := `
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                    }
                ],
                "response_format": {
                    "type": "text"
                }
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}

响应参数

Body 参数

参数名称 描述
id string 会话标识(chatcmpl- 前缀)
object string 固定 chat.completion
model string 模型名称
created integer 创建时间戳
choices array 候选回复数组,含 index/message/finish_reason
usage object token 用量,含 prompt_tokens/completion_tokens/total_tokens
POSThttps://www.sagelib.com/anthropic/v1/messages

qwen3.8-flash 模型的聊天生成接口,Anthropic直连,支持多轮上下文、流式输出、工具调用、结构化输出等。

接口鉴权方式请参考:API接入与鉴权

请求参数

请求头

参数名称 描述
*Content-Type string 可选值:application/json
application/json
*anthropic-version string 可选值:2023-06-01
Anthropic API 版本号,固定为 2023-06-01
*X-Api-Key string 鉴权令牌,格式为 ${AIGATEWAY_TOKEN}

Body 参数

参数名称 描述
*model string 可选值:"qwen3.8-flash"
模型名称,须精确匹配
*messages array 可选值:Object array with role+content
对话消息列表
*max_tokens integer 可选值:Positive integer
回复内容与思维链之和的最大 token 数
temperature float 默认值:0.7
可选值:Open interval [0,2)
采样温度,值越大输出越随机
top_p float 默认值:0.8
可选值:(0,1.0]
核采样概率阈值
top_k integer 默认值:20
可选值:Positive integer; null or >100 disables it
采样候选集大小
tools array 可选值:Anthropic format name+description+input_schema
工具定义数组,模型可发起工具调用
tool_choice object 默认值:auto
可选值:auto、any、none、tool
工具调用策略
stream boolean 默认值:false
可选值:true、false
是否 SSE 流式返回
system string 可选值:String or string array (text content block)
系统指令
stop_sequences array 可选值:String array
停止文本序列数组
thinking object 可选值:type: enabled/disabled + budget_tokens
思考配置对象
cache_control object 可选值:type: ephemeral
缓存断点标记
metadata object 可选值:Key-value pairs
附加元数据
output_config object 可选值:medium
输出配置(思考强度 + 结构化输出)

请求示例

curl -v 'https://www.sagelib.com/anthropic/messages' \
  -H "x-api-key: ***" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-flash",
    "messages": [
      {
        "role": "user",
        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
      }
    ],
    "max_tokens": 4096
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your API key

url = f"https://www.sagelib.com/anthropic/messages"

headers = {
    "x-api-key": api_key,
    "anthropic-version": "2023-06-01",
    "Content-Type": "application/json",
}

data = {
    "model": "qwen3.8-flash",
    "messages": [
        {
            "role": "user",
            "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
        }
    ],
    "max_tokens": 4096
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/anthropic/messages";

        String jsonRequestBody = """
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                    }
                ],
                "max_tokens": 4096
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("x-api-key", apiKey).header("anthropic-version", "2023-06-01")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/anthropic/messages"

    jsonRequestBody := `
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                    }
                ],
                "max_tokens": 4096
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("x-api-key", apiKey)
    req.Header.Set("anthropic-version", "2023-06-01")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}
curl -v 'https://www.sagelib.com/anthropic/messages' \
  -H "x-api-key: ***" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-flash",
    "messages": [
      {
        "role": "user",
        "content": "How is the weather in Beijing today? Please use a tool to query the weather."
      }
    ],
    "max_tokens": 4096,
    "tools": [
      {
        "name": "get_weather",
        "description": "Get weather information for a specified city",
        "input_schema": {
          "type": "object",
          "properties": {
            "city": {
              "type": "string"
            }
          },
          "required": [
            "city"
          ]
        }
      }
    ]
  }'
import json
import requests

base_url = "https://www.sagelib.com"
api_key = "***"
url = f"https://{base_url}/v1/messages"
headers = {"x-api-key": api_key, "anthropic-version": "2023-06-01", "Content-Type": "application/json"}
data = {
    "model": "qwen3.8-flash",
    "messages": [
        {
            "role": "user",
            "content": "How is the weather in Beijing today? Please use a tool to query the weather."
        }
    ],
    "max_tokens": 4096,
    "tools": [
        {
            "name": "get_weather",
            "description": "Get weather information for a specified city",
            "input_schema": {
                "type": "object",
                "properties": {
                    "city": {
                        "type": "string"
                    }
                },
                "required": [
                    "city"
                ]
            }
        }
    ]
}
response = requests.post(url, headers=headers, json=data)
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/anthropic/messages";

        String jsonRequestBody = """
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "How is the weather in Beijing today? Please use a tool to query the weather."
                    }
                ],
                "max_tokens": 4096,
                "tools": [
                    {
                        "name": "get_weather",
                        "description": "Get weather information for a specified city",
                        "input_schema": {
                            "type": "object",
                            "properties": {
                                "city": {
                                    "type": "string"
                                }
                            },
                            "required": [
                                "city"
                            ]
                        }
                    }
                ]
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("x-api-key", apiKey).header("anthropic-version", "2023-06-01")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/anthropic/messages"

    jsonRequestBody := `
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "How is the weather in Beijing today? Please use a tool to query the weather."
                    }
                ],
                "max_tokens": 4096,
                "tools": [
                    {
                        "name": "get_weather",
                        "description": "Get weather information for a specified city",
                        "input_schema": {
                            "type": "object",
                            "properties": {
                                "city": {
                                    "type": "string"
                                }
                            },
                            "required": [
                                "city"
                            ]
                        }
                    }
                ]
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("x-api-key", apiKey)
    req.Header.Set("anthropic-version", "2023-06-01")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}
curl -v 'https://www.sagelib.com/anthropic/messages' \
  -H "x-api-key: ***" \
  -H "anthropic-version: 2023-06-01" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-flash",
    "messages": [
      {
        "role": "user",
        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
      }
    ],
    "max_tokens": 4096,
    "cache_control": {
      "type": "ephemeral"
    }
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your API key

url = f"https://www.sagelib.com/anthropic/messages"

headers = {
    "x-api-key": api_key,
    "anthropic-version": "2023-06-01",
    "Content-Type": "application/json",
}

data = {
    "model": "qwen3.8-flash",
    "messages": [
        {
            "role": "user",
            "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
        }
    ],
    "max_tokens": 4096,
    "cache_control": {
        "type": "ephemeral"
    }
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/anthropic/messages";

        String jsonRequestBody = """
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                    }
                ],
                "max_tokens": 4096,
                "cache_control": {
                    "type": "ephemeral"
                }
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("x-api-key", apiKey).header("anthropic-version", "2023-06-01")
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/anthropic/messages"

    jsonRequestBody := `
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                    }
                ],
                "max_tokens": 4096,
                "cache_control": {
                    "type": "ephemeral"
                }
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("x-api-key", apiKey)
    req.Header.Set("anthropic-version", "2023-06-01")
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}

响应参数

Body 参数

参数名称 描述
id string 消息标识(msg_ 前缀)
type string 固定 message
role string 固定 assistant
model string 模型名称
content array 内容块数组,每块含 type(thinking/text/tool_use)
stop_reason string 停止原因(end_turn/tool_use/max_tokens)
usage object token 用量,含 input_tokens/output_tokens
POSThttps://www.sagelib.com/openai/chat/completions

qwen3.8-flash 模型的聊天生成接口,OpenAI直连,支持多轮上下文、流式输出、工具调用、结构化输出等。

接口鉴权方式请参考:API接入与鉴权

请求参数

请求头

参数名称 描述
*Content-Type string application/json(JSON 端点)或 multipart/form-data; boundary=...(multipart 端点,保持原始 boundary)
*Authorization string 鉴权令牌,格式为 Bearer ${AIGATEWAY_TOKEN}

Body 参数

参数名称 描述
*model string 可选值:"qwen3.8-flash"
模型名称,须精确匹配
*messages array 可选值:Object array with role+content
对话消息列表
max_tokens integer 可选值:Positive integer
生成最大 token 数
temperature float 默认值:0.7
可选值:Open interval [0,2)
采样温度,值越大输出越随机
top_p float 默认值:0.8
可选值:(0,1.0]
核采样概率阈值
top_k integer 默认值:20
可选值:Positive integer; null or >100 disables it
采样候选集大小
tools array 可选值:OpenAI format type:"function"+function.parameters
工具定义数组,模型可据此发起工具调用
tool_choice string 默认值:auto
可选值:auto、none
工具调用策略
stream boolean 默认值:false
可选值:true、false
是否 SSE 流式返回
max_completion_tokens integer 可选值:Positive integer
生成回复(含思维链)最大 token 数
seed integer 默认值:1234
可选值:Integer
随机种子,结果可复现
stop string 可选值:String or string array
停止序列
enable_search boolean 默认值:false
可选值:true、false
是否启用联网搜索
thinking_budget integer 默认值:131072
可选值:low→4096, medium→16384, xhigh→262144
思维链最大 token 数
repetition_penalty float 默认值:1.05
可选值:Greater than 0
重复惩罚
presence_penalty float 默认值:1.5
可选值:[-2.0, 2.0]
存在惩罚
n integer 默认值:1
可选值:1 ~ 4
生成条数
logprobs boolean 默认值:false
可选值:true、false
是否返回输出 token 对数概率
top_logprobs integer 默认值:0
可选值:0 ~ 5
返回概率最高前 N 个 token 对数概率
stream_options object 可选值:Contains include_usage
流式附加选项(include_usage 控制末帧返回 usage)
response_format object 可选值:{"type":"text"} / {"type":"json_object"}
结构化输出格式
parallel_tool_calls boolean 默认值:false
可选值:true、false
是否允许并行工具调用
incremental_output boolean 默认值:false
可选值:true、false
是否增量输出
reasoning_effort string 默认值:xhigh
可选值:xhigh、medium、low
思考强度档位
preserve_thinking boolean 默认值:true
可选值:true、false
是否保持思考历史
tool_stream boolean 可选值:true、false
是否流式工具调用
search_options object 可选值:enable_source、enable_citation、forced_search、search_strategy
联网搜索高级选项

请求示例

curl -v 'https://www.sagelib.com/openai/chat/completions' \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-flash",
    "messages": [
      {
        "role": "user",
        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
      }
    ]
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your Bearer token

url = f"https://www.sagelib.com/openai/chat/completions"

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}

data = {
    "model": "qwen3.8-flash",
    "messages": [
        {
            "role": "user",
            "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
        }
    ]
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/openai/chat/completions";

        String jsonRequestBody = """
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                    }
                ]
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/openai/chat/completions"

    jsonRequestBody := `
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "What model are you? Which company made you? When were you launched? Briefly describe your capability boundaries."
                    }
                ]
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}
curl -v 'https://www.sagelib.com/openai/chat/completions' \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-flash",
    "messages": [
      {
        "role": "user",
        "content": "How is the weather in Beijing today? Please use a tool to query the weather."
      }
    ],
    "tools": [
      {
        "type": "function",
        "function": {
          "name": "get_weather",
          "description": "Get weather information for a specified city",
          "parameters": {
            "type": "object",
            "properties": {
              "city": {
                "type": "string"
              }
            },
            "required": [
              "city"
            ]
          }
        }
      }
    ]
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your Bearer token

url = f"https://www.sagelib.com/openai/chat/completions"

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}

data = {
    "model": "qwen3.8-flash",
    "messages": [
        {
            "role": "user",
            "content": "How is the weather in Beijing today? Please use a tool to query the weather."
        }
    ],
    "tools": [
        {
            "type": "function",
            "function": {
                "name": "get_weather",
                "description": "Get weather information for a specified city",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": {
                            "type": "string"
                        }
                    },
                    "required": [
                        "city"
                    ]
                }
            }
        }
    ]
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/openai/chat/completions";

        String jsonRequestBody = """
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "How is the weather in Beijing today? Please use a tool to query the weather."
                    }
                ],
                "tools": [
                    {
                        "type": "function",
                        "function": {
                            "name": "get_weather",
                            "description": "Get weather information for a specified city",
                            "parameters": {
                                "type": "object",
                                "properties": {
                                    "city": {
                                        "type": "string"
                                    }
                                },
                                "required": [
                                    "city"
                                ]
                            }
                        }
                    }
                ]
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/openai/chat/completions"

    jsonRequestBody := `
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "How is the weather in Beijing today? Please use a tool to query the weather."
                    }
                ],
                "tools": [
                    {
                        "type": "function",
                        "function": {
                            "name": "get_weather",
                            "description": "Get weather information for a specified city",
                            "parameters": {
                                "type": "object",
                                "properties": {
                                    "city": {
                                        "type": "string"
                                    }
                                },
                                "required": [
                                    "city"
                                ]
                            }
                        }
                    }
                ]
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}
curl -v 'https://www.sagelib.com/openai/chat/completions' \
  -H "Authorization: Bearer ***" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "qwen3.8-flash",
    "messages": [
      {
        "role": "user",
        "content": "Output the time complexity of 5 sorting algorithms in JSON format; must be a valid JSON object with each item containing name/best/average/worst fields."
      }
    ],
    "response_format": {
      "type": "json_object"
    }
  }'
import json
import requests

# Configure base variables
base_url = "https://www.sagelib.com"  # 把 base_url 换成你的网关地址 https://www.sagelib.com
api_key = "***"  # Replace with your Bearer token

url = f"https://www.sagelib.com/openai/chat/completions"

headers = {
    "Authorization": f"Bearer {api_key}",
    "Content-Type": "application/json",
}

data = {
    "model": "qwen3.8-flash",
    "messages": [
        {
            "role": "user",
            "content": "Output the time complexity of 5 sorting algorithms in JSON format; must be a valid JSON object with each item containing name/best/average/worst fields."
        }
    ],
    "response_format": {
        "type": "json_object"
    }
}

# Send the POST request
response = requests.post(url, headers=headers, json=data)

# Print the status code and the returned JSON data
print(f"Status Code: {response.status_code}")
try:
    print(json.dumps(response.json(), indent=2, ensure_ascii=False))
except Exception:
    print(response.text)
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

public class LlmStreamClient {
    public static void main(String[] args) {
        String baseUrl = "https://www.sagelib.com";
        String apiKey = "***";
        String url = "https://www.sagelib.com/openai/chat/completions";

        String jsonRequestBody = """
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "Output the time complexity of 5 sorting algorithms in JSON format; must be a valid JSON object with each item containing name/best/average/worst fields."
                    }
                ],
                "response_format": {
                    "type": "json_object"
                }
            }
            """;

        HttpClient client = HttpClient.newHttpClient();
        HttpRequest request = HttpRequest.newBuilder()
                .uri(URI.create(url))
                .header("Authorization", "Bearer " + apiKey)
                .header("Content-Type", "application/json")
                .POST(HttpRequest.BodyPublishers.ofString(jsonRequestBody))
                .build();

        try {
            // Use ofInputStream to handle the streaming response
            HttpResponse<java.io.InputStream> response = client.send(request, HttpResponse.BodyHandlers.ofInputStream());

            try (BufferedReader reader = new BufferedReader(new InputStreamReader(response.body()))) {
                String line;
                while ((line = reader.readLine()) != null) {
                    line = line.trim();
                    if (line.startsWith("data:")) {
                        String data = line.substring(5).trim();
                        if ("[DONE]".equals(data)) {
                            break;
                        }
                        // Tip: you can bring in Gson or Jackson here to parse the JSON in data and extract delta.content
                        System.out.println("Received stream chunk: " + data);
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
package main

import (
    "bytes"
    "encoding/json"
    "fmt"
    "io"
    "net/http"
)

func main() {
    baseUrl := "https://www.sagelib.com"
    apiKey := "***"
    url := "https://www.sagelib.com/openai/chat/completions"

    jsonRequestBody := `
            {
                "model": "qwen3.8-flash",
                "messages": [
                    {
                        "role": "user",
                        "content": "Output the time complexity of 5 sorting algorithms in JSON format; must be a valid JSON object with each item containing name/best/average/worst fields."
                    }
                ],
                "response_format": {
                    "type": "json_object"
                }
            }
`

    req, err := http.NewRequest("POST", url, bytes.NewBufferString(jsonRequestBody))
    if err != nil {
        fmt.Println("Failed to create request:", err)
        return
    }
    req.Header.Set("Authorization", "Bearer "+apiKey)
    req.Header.Set("Content-Type", "application/json")

    client := &http.Client{}
    resp, err := client.Do(req)
    if err != nil {
        fmt.Println("Request failed:", err)
        return
    }
    defer resp.Body.Close()

    body, _ := io.ReadAll(resp.Body)
    // Pretty-print the returned JSON data
    var prettyBody map[string]interface{}
    if err := json.Unmarshal(body, &prettyBody); err == nil {
        pretty, _ := json.MarshalIndent(prettyBody, "", "  ")
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(pretty))
    } else {
        fmt.Println("Status Code:", resp.StatusCode)
        fmt.Println(string(body))
    }
}

响应参数

Body 参数

参数名称 描述
id string 会话标识(chatcmpl- 前缀)
object string 固定 chat.completion
model string 模型名称
created integer 创建时间戳
choices array 候选回复数组,含 finish_reason/index/message
usage object token 用量,含 prompt_tokens/completion_tokens/total_tokens