import json import requests url = "https://代理域名/v1/chat/completions" # 替換爲目標URL data = { "stream": True, "model": "gpt-3.5-turbo", "messages": [ { "role": "user", "content": "你是誰" }, ] } headers = { "Authorization": "Bearer key", } # 使用 with 語句確保請求完成後釋放資源 with requests.post(url, json=data, headers=headers, timeout=60000, stream=True) as response: # print(response.headers) for chunk in response.iter_lines(chunk_size=None): mChunk = chunk.decode('utf-8') if "[DONE]" in mChunk: break # print(mChunk) lines = mChunk.splitlines() for line in lines: respStr = line.strip().replace("data: ", "") respContent = "" try: respJson = json.loads(respStr) respContent = respJson["choices"][0]["delta"]["content"] except Exception as e: respContent = "" print(respContent)