> ## Documentation Index
> Fetch the complete documentation index at: https://docs.geekai.co/llms.txt
> Use this file to discover all available pages before exploring further.

# 流式对话

几乎所有对话模型都支持流式对话响应，即边回答边输出的效果。

以下是最简单的流式对话请求示例，只需要将 `stream` 设置为 `true` 即可：

<CodeGroup>
  ```bash curl theme={null}
  curl --location --request POST 'https://geekai.co/api/v1/chat/completions' \
  --header 'Authorization: Bearer $GEEKAI_API_KEY' \
  --header 'Content-Type: application/json' \
  --data-raw '{
      "model": "gpt-5-mini",
      "messages": [
          {
              "role": "user",
              "content": "你好"
          }
      ],
      "stream": true
  }'
  ```

  ```bash python theme={null}
  # 先安装网络库 `pip3 install aiohttp asyncio`

  import aiohttp
  import asyncio
  import json

  async def invoke_geekai():
  	api_token = "$GEEKAI_API_KEY"  # Replace with your actual API token

  	headers = {
  		"Authorization": "Bearer " + api_token,
  		"Content-Type": "application/json"
  	}
  	
  	body =     {
        "model": "gpt-5-mini",
        "messages": [
          {
            "role": "user",
            "content": "你好"
          }
        ],
        "stream": True
      }

  	async with aiohttp.ClientSession() as session:
  		async with session.post(
  			"https://geekai.co/v1/chat/completions", 
  			headers=headers,
  			json=body
  		) as response:
  			async for line in response.content:
  				line = line.decode("utf-8").strip()
  				if line.startswith("data: "):
  					data = line[6:]
  					if data == "[DONE]":
  						break
  					try:
  						chunk = data.strip()
  						if chunk:
  							print(chunk)
  					except Exception as e:
  						print(f"Error parsing chunk: {e}")

  asyncio.run(invoke_geekai())
  ```

  ```bash javascript theme={null}
  const response = await fetch("https://geekai.co/v1/chat/completions", {
      method: "POST",
      headers: {
          "Authorization": "Bearer $GEEKAI_API_KEY",
          "Content-Type": "application/json"
      },
      body: JSON.stringify({
          "model": "gpt-5-mini",
          "messages": [
              {
                  "role": "user",
                  "content": "你好"
              }
          ],
          "stream": true
      })
  });

  const data = await response.json();
  console.log(data);
  ```

  ```bash go theme={null}
  package main

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

  func main() {
  	requestBody := map[string]interface{}{
  		"model": "gpt-5-mini",
  		"messages": []interface{}{
              map[string]interface{}{
                  "role": "user", 
                  "content": "你好",
              },
          },
          "stream": true,
  	}
  	
  	jsonData, err := json.Marshal(requestBody)
  	if err != nil {
  		panic(err)
  	}

  	client := &http.Client{}
  	req, err := http.NewRequest("POST", "https://geekai.co/api/v1/chat/completions", bytes.NewBuffer(jsonData))
  	if err != nil {
  		panic(err)
  	}

  	req.Header.Set("Authorization", "Bearer $GEEKAI_API_KEY")
  	req.Header.Set("Content-Type", "application/json")

  	resp, err := client.Do(req)
  	if err != nil {
  		panic(err)
  	}
  	defer resp.Body.Close()

  	body, err := io.ReadAll(resp.Body)
  	if err != nil {
  		panic(err)
  	}

  	fmt.Println(string(body))
  }
  ```
</CodeGroup>

对于流式请求，需要在客户端接收响应时进行特殊处理才能获取到，以 JavaScript 为例，需要通过 `EventSource` 进行监听获取。
