generate_content_stream fails with UnknownApiResponseError when a streamed text part contains U+2028 / U+2029 / U+0085 (httpx transport)
維護者通常 1 天內回覆
評估
這個 Issue 還沒有評估資料。
描述
Environment details
- Programming language: Python
- OS: Windows 11 (transport-level, not OS-specific)
- Language runtime version: 3.14
- Package version: google-genai 2.33.0 (code unchanged on main)
Symptom
If a streamed chunk's JSON contains a raw U+2028 (LINE SEPARATOR), U+2029 or U+0085 (NEL) inside a string, models.generate_content_stream (sync) and aio.models.generate_content_stream with an httpx client raise:
UnknownApiResponseError: Failed to parse response as JSON. Raw response: {"candidates": [{"content": {"role": "model", "parts": [{"text": "line one
The same bytes parse correctly on the aiohttp async path.
Steps to reproduce
Self-contained script with a local SSE server, no API key (below):
sync (httpx) ERR UnknownApiResponseError ... "text": "line one
async (httpx) ERR UnknownApiResponseError ... "text": "line one
async (aiohttp) ['line one
line two', ' done']
The body is valid JSON (RFC 8259 doesn't require escaping these code points), one data: line per event.
repro_genai_linesep.py
"""google-genai: streamed text containing U+2028 / U+2029 / U+0085 breaks SSE parsing (httpx path)."""
import asyncio, json, sys, threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import httpx
from google import genai
TEXT = sys.argv[1].encode().decode("unicode_escape") if len(sys.argv) > 1 else "line one\u2028line two"
CHUNKS = [
{"candidates": [{"content": {"role": "model", "parts": [{"text": TEXT}]}}]},
{"candidates": [{"content": {"role": "model", "parts": [{"text": " done"}]}, "finishReason": "STOP"}]},
]
# Valid JSON (RFC 8259 does not require escaping these code points); one event per line.
BODY = b"".join(b"data: " + json.dumps(c, ensure_ascii=False).encode() + b"\r\n\r\n" for c in CHUNKS)
class H(BaseHTTPRequestHandler):
def do_POST(self):
self.rfile.read(int(self.headers["Content-Length"]))
self.send_response(200)
self.send_header("Content-Type", "text/event-stream")
self.send_header("Content-Length", str(len(BODY)))
self.end_headers()
self.wfile.write(BODY)
def log_message(self, *a): pass
srv = ThreadingHTTPServer(("127.0.0.1", 0), H)
threading.Thread(target=srv.serve_forever, daemon=True).start()
base = f"http://127.0.0.1:{srv.server_port}"
print(f"genai {genai.__version__}, text={TEXT!r}")
def run_sync():
c = genai.Client(api_key="test", http_options={"base_url": base})
return [ch.text for ch in c.models.generate_content_stream(model="gemini-2.5-flash", contents="hi")]
async def run_async(httpx_client):
opts = {"base_url": base}
if httpx_client:
opts["httpx_async_client"] = httpx.AsyncClient()
c = genai.Client(api_key="test", http_options=opts)
return [ch.text async for ch in await c.aio.models.generate_content_stream(model="gemini-2.5-flash", contents="hi")]
for name, fn in [("sync (httpx) ", run_sync),
("async (httpx) ", lambda: asyncio.run(run_async(True))),
("async (aiohttp)", lambda: asyncio.run(run_async(False)))]:
try:
print(name, fn())
except Exception as e:
print(name, "ERR", type(e).__name__, str(e)[:160].replace("\n", " "))
Root cause
google/genai/_api_client.py:488 (iter_lines()) and :545 (aiter_lines()) use httpx's line decoder, which follows str.splitlines() and also breaks on U+2028/U+2029/U+0085 (and , , -). The SSE spec treats only CRLF, LF and CR as line terminators. The aiohttp branch (:587, readline() on bytes) gets this right.
Suggested fix
Split the byte stream on `
/
/
only (e.g. iterateiter_bytes()/aiter_bytes()` through a small line splitter, as the aiohttp branch effectively does), then decode each line.
- 主要語言
- Python
- 星號
- 4.1k
- 分支
- 1.1k
- 平均合併
- 1 天 20 小時
- 30 天內合併 PR
- 99
環境準備
- 沒有 Dockerfile 或 Docker Compose 檔案
- 沒有 Pull Request 範本
- 閱讀貢獻指南
從這裡開始
- 先讀完整個 Issue,再讀專案的貢獻指南。
- 在 Issue 下留言說明你要接手 —— 這能避免兩個人做同樣的事。
- Fork 儲存庫,在一個分支上完成修改。
- 送出 Pull Request,並在描述裡引用這個 Issue 編號。
googleapis/python-genai 的其他 Issue
-
Interactions retries ignore the documented `initial_delay` and `max_delay` defaults可能已有人在做 @Sun-Wukhan 今天認領。 未關閉
難度 2/5 1-3 小時 新手友好度 68/100
googleapis/python-genai#3317 ·
維護者通常 1 天內回覆
-
Test import module that doesn't exist可能已有人在做 @Venkaiahbabuneelam 於 26 天前認領。 未關閉priority: p2 type: bug
難度 2/5 1-3 小時 新手友好度 66/100
googleapis/python-genai#3122 · 6 則留言 · 已指派 1 人 ·
維護者通常 1 天內回覆
-
Curated history keeps half a user turn when the model turn is invalid可能已有人在做 @Venkaiahbabuneelam 於 35 天前認領。 未關閉priority: p2 type: bug
難度 2/5 1-3 小時 新手友好度 62/100
googleapis/python-genai#3051 · 3 則留言 · 已指派 1 人 ·
維護者通常 1 天內回覆
-
[Bug]: Unsubscripted typing.List and typing.Dict crash convert_if_exist_pydantic_model in AFC可能已有人在做 @Venkaiahbabuneelam 於 35 天前認領。 未關閉priority: p2 type: bug
難度 2/5 1-3 小時 新手友好度 82/100
googleapis/python-genai#3044 · 1 則留言 · 已指派 1 人 ·
維護者通常 1 天內回覆
-
all `client.webhooks` operations fail with API error occurred: Status 404可能已有人在做 @VISHNU0906 今天認領。 未關閉priority: p2 type: bug
難度 3/5 1-2 天 新手友好度 54/100
googleapis/python-genai#3316 ·
維護者通常 1 天內回覆
查看 googleapis/python-genai 的全部 Issue
相似的 Issue
-
bug
難度 2/5 1-3 小時 新手友好度 78/100
cunla/fakeredis-py#636 ·
維護者通常 2 天內回覆
-
難度 2/5 1-3 小時 新手友好度 78/100
opensafely-core/job-server#6180 · 1 則留言 ·
維護者通常 1 天內回覆
-
area:models enhancement
難度 2/5 1-3 小時 新手友好度 76/100
維護者通常 1 天內回覆
-
bug needs-triage
難度 2/5 1-3 小時 新手友好度 86/100
newrelic/newrelic-python-agent#1913 · 1 則留言 ·
維護者通常 1 天內回覆
-
難度 2/5 1-3 小時 新手友好度 77/100
維護者通常 1 天內回覆