Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(vlm): add streaming response handling for OpenAI VLM (#756)

KorenKritad739a5be35e0
diff --git a/docs/en/guides/01-configuration.md b/docs/en/guides/01-configuration.md
index 52a55a91a..dacb665cf 100644
--- a/docs/en/guides/01-configuration.md
+++ b/docs/en/guides/01-configuration.md
@@ -304,6 +304,7 @@ Vision Language Model for semantic extraction (L0/L1 generation).
| `thinking` | bool | Enable thinking mode for VolcEngine models (default: `false`) |
| `max_concurrent` | int | Maximum concurrent semantic LLM calls (default: `100`) |
| `extra_headers` | object | Custom HTTP headers (for OpenAI-compatible providers, optional) |
+| `stream` | bool | Enable streaming mode (for OpenAI-compatible providers, default: `false`) |
**Available Models**
@@ -343,6 +344,24 @@ Common use cases:
- **Custom proxies**: Add authentication or tracing headers
- **API gateways**: Add version or routing identifiers
+**Streaming Mode**
+
+For OpenAI-compatible providers that return SSE (Server-Sent Events) format responses, enable `stream` mode:
+
+```json
+{
+ "vlm": {
+ "provider": "openai",
+ "api_key": "your-api-key",
+ "model": "gpt-4o",
+ "api_base": "https://api.example.com/v1",
+ "stream": true
+ }
+}
+```
+
+> **Note**: The OpenAI SDK requires `stream=true` to properly parse SSE responses. When using providers that force SSE format, you must set this option to `true`.
+
### code
Controls how code files are summarized via `code_summary_mode`. Both config formats are equivalent:
@@ -706,7 +725,8 @@ For details on the lock mechanism, see [Path Locks and Crash Recovery](../concep
"api_base": "string",
"thinking": false,
"max_concurrent": 100,
- "extra_headers": {}
+ "extra_headers": {},
+ "stream": false
},
"rerank": {
"provider": "volcengine",
diff --git a/docs/zh/guides/01-configuration.md b/docs/zh/guides/01-configuration.md
index 1c83eb85c..bf6a8ea21 100644
--- a/docs/zh/guides/01-configuration.md
+++ b/docs/zh/guides/01-configuration.md
@@ -277,6 +277,7 @@ OpenViking 使用 JSON 配置文件(`ov.conf`)进行设置。配置文件支
| `thinking` | bool | 启用思考模式(仅对部分火山模型生效,默认:`false`) |
| `max_concurrent` | int | 语义处理阶段 LLM 最大并发调用数(默认:`100`) |
| `extra_headers` | object | 自定义 HTTP 请求头(OpenAI 兼容 provider 可用,可选) |
+| `stream` | bool | 启用流式模式(OpenAI 兼容 provider 可用,默认:`false`) |
**可用模型**
@@ -316,6 +317,24 @@ OpenViking 使用 JSON 配置文件(`ov.conf`)进行设置。配置文件支
- **自定义代理**: 添加认证头或追踪头
- **API 网关**: 添加版本或路由标识
+**流式模式**
+
+对于返回 SSE(Server-Sent Events)格式响应的 OpenAI 兼容 provider,启用 `stream` 模式:
+
+```json
+{
+ "vlm": {
+ "provider": "openai",
+ "api_key": "your-api-key",
+ "model": "gpt-4o",
+ "api_base": "https://api.example.com/v1",
+ "stream": true
+ }
+}
+```
+
+> **注意**: OpenAI SDK 需要 `stream=true` 才能正确解析 SSE 响应。使用强制返回 SSE 格式的 provider 时,必须将此选项设置为 `true`。
+
### code
通过 `code_summary_mode` 控制代码文件的摘要生成方式。以下两种写法等价:
@@ -681,7 +700,8 @@ HTTP 客户端(`SyncHTTPClient` / `AsyncHTTPClient`)和 CLI 工具连接远
"api_base": "string",
"thinking": false,
"max_concurrent": 100,
- "extra_headers": {}
+ "extra_headers": {},
+ "stream": false
},
"rerank": {
"provider": "volcengine",
diff --git a/openviking/models/vlm/backends/openai_vlm.py b/openviking/models/vlm/backends/openai_vlm.py
index d1f6d05d3..633c9816d 100644
--- a/openviking/models/vlm/backends/openai_vlm.py
+++ b/openviking/models/vlm/backends/openai_vlm.py
@@ -60,6 +60,93 @@ class OpenAIVLM(VLMBase):
)
return
+ def _extract_from_chunk(self, chunk):
+ """Extract content and usage from a single chunk.
+
+ Returns:
+ tuple: (content, prompt_tokens, completion_tokens)
+ """
+ content = None
+ prompt_tokens = 0
+ completion_tokens = 0
+
+ # Extract content from delta
+ if chunk.choices and chunk.choices[0].delta:
+ content = getattr(chunk.choices[0].delta, "content", None)
+
+ # Extract usage from chunk if available
+ if hasattr(chunk, "usage") and chunk.usage:
+ prompt_tokens = chunk.usage.prompt_tokens or 0
+ completion_tokens = chunk.usage.completion_tokens or 0
+
+ return content, prompt_tokens, completion_tokens
+
+ def _process_streaming_response(self, response):
+ """Process streaming response and extract content and token usage.
+
+ Args:
+ response: Streaming response iterator from OpenAI client
+
+ Returns:
+ str: Extracted content
+ """
+ content_parts = []
+ prompt_tokens = 0
+ completion_tokens = 0
+
+ for chunk in response:
+ content, pt, ct = self._extract_from_chunk(chunk)
+ if content:
+ content_parts.append(content)
+ if pt > 0:
+ prompt_tokens = pt
+ if ct > 0:
+ completion_tokens = ct
+
+ # Update token usage if we got it from streaming chunks
+ if prompt_tokens > 0 or completion_tokens > 0:
+ self.update_token_usage(
+ model_name=self.model or "gpt-4o-mini",
+ provider=self.provider,
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ )
+
+ return "".join(content_parts)
+
+ async def _process_streaming_response_async(self, response):
+ """Process async streaming response and extract content and token usage.
+
+ Args:
+ response: Async streaming response iterator from OpenAI client
+
+ Returns:
+ str: Extracted content
+ """
+ content_parts = []
+ prompt_tokens = 0
+ completion_tokens = 0
+
+ async for chunk in response:
+ content, pt, ct = self._extract_from_chunk(chunk)
+ if content:
+ content_parts.append(content)
+ if pt > 0:
+ prompt_tokens = pt
+ if ct > 0:
+ completion_tokens = ct
+
+ # Update token usage if we got it from streaming chunks
+ if prompt_tokens > 0 or completion_tokens > 0:
+ self.update_token_usage(
+ model_name=self.model or "gpt-4o-mini",
+ provider=self.provider,
+ prompt_tokens=prompt_tokens,
+ completion_tokens=completion_tokens,
+ )
+
+ return "".join(content_parts)
+
def get_completion(self, prompt: str, thinking: bool = False) -> str:
"""Get text completion"""
client = self.get_client()
@@ -67,13 +154,20 @@ class OpenAIVLM(VLMBase):
"model": self.model or "gpt-4o-mini",
"messages": [{"role": "user", "content": prompt}],
"temperature": self.temperature,
+ "stream": self.stream,
}
if self.max_tokens is not None:
kwargs["max_tokens"] = self.max_tokens
response = client.chat.completions.create(**kwargs)
- self._update_token_usage_from_response(response)
- return self._clean_response(response.choices[0].message.content or "")
+
+ if self.stream:
+ content = self._process_streaming_response(response)
+ else:
+ self._update_token_usage_from_response(response)
+ content = response.choices[0].message.content or ""
+
+ return self._clean_response(content)
async def get_completion_async(
self, prompt: str, thinking: bool = False, max_retries: int = 0
@@ -84,6 +178,7 @@ class OpenAIVLM(VLMBase):
"model": self.model or "gpt-4o-mini",
"messages": [{"role": "user", "content": prompt}],
"temperature": self.temperature,
+ "stream": self.stream,
}
if self.max_tokens is not None:
kwargs["max_tokens"] = self.max_tokens
@@ -92,8 +187,14 @@ class OpenAIVLM(VLMBase):
for attempt in range(max_retries + 1):
try:
response = await client.chat.completions.create(**kwargs)
- self._update_token_usage_from_response(response)
- return self._clean_response(response.choices[0].message.content or "")
+
+ if self.stream:
+ content = await self._process_streaming_response_async(response)
+ else:
+ self._update_token_usage_from_response(response)
+ content = response.choices[0].message.content or ""
+
+ return self._clean_response(content)
except Exception as e:
last_error = e
if attempt < max_retries:
@@ -174,13 +275,20 @@ class OpenAIVLM(VLMBase):
"model": self.model or "gpt-4o-mini",
"messages": [{"role": "user", "content": content}],
"temperature": self.temperature,
+ "stream": self.stream,
}
if self.max_tokens is not None:
kwargs["max_tokens"] = self.max_tokens
response = client.chat.completions.create(**kwargs)
- self._update_token_usage_from_response(response)
- return self._clean_response(response.choices[0].message.content or "")
+
+ if self.stream:
+ content = self._process_streaming_response(response)
+ else:
+ self._update_token_usage_from_response(response)
+ content = response.choices[0].message.content or ""
+
+ return self._clean_response(content)
async def get_vision_completion_async(
self,
@@ -200,10 +308,17 @@ class OpenAIVLM(VLMBase):
"model": self.model or "gpt-4o-mini",
"messages": [{"role": "user", "content": content}],
"temperature": self.temperature,
+ "stream": self.stream,
}
if self.max_tokens is not None:
kwargs["max_tokens"] = self.max_tokens
response = await client.chat.completions.create(**kwargs)
- self._update_token_usage_from_response(response)
- return self._clean_response(response.choices[0].message.content or "")
+
+ if self.stream:
+ content = await self._process_streaming_response_async(response)
+ else:
+ self._update_token_usage_from_response(response)
+ content = response.choices[0].message.content or ""
+
+ return self._clean_response(content)
diff --git a/openviking/models/vlm/base.py b/openviking/models/vlm/base.py
index 64c3d5cf8..079cd3a9f 100644
--- a/openviking/models/vlm/base.py
+++ b/openviking/models/vlm/base.py
@@ -27,6 +27,7 @@ class VLMBase(ABC):
self.max_retries = config.get("max_retries", 2)
self.max_tokens = config.get("max_tokens")
self.extra_headers = config.get("extra_headers")
+ self.stream = config.get("stream", False)
# Token usage tracking
self._token_tracker = TokenUsageTracker()
diff --git a/openviking_cli/utils/config/vlm_config.py b/openviking_cli/utils/config/vlm_config.py
index 0b999ca8b..2a33711bd 100644
--- a/openviking_cli/utils/config/vlm_config.py
+++ b/openviking_cli/utils/config/vlm_config.py
@@ -27,7 +27,8 @@ class VLMConfig(BaseModel):
default_provider: Optional[str] = Field(default=None, description="Default provider name")
max_tokens: Optional[int] = Field(
- default=None, description="Maximum tokens for VLM completion output (None = provider default)"
+ default=None,
+ description="Maximum tokens for VLM completion output (None = provider default)",
)
thinking: bool = Field(default=False, description="Enable thinking mode for VolcEngine models")
@@ -40,6 +41,10 @@ class VLMConfig(BaseModel):
default=None, description="Extra HTTP headers for OpenAI-compatible providers"
)
+ stream: bool = Field(
+ default=False, description="Enable streaming mode for OpenAI-compatible providers"
+ )
+
_vlm_instance: Optional[Any] = None
model_config = {"arbitrary_types_allowed": True, "extra": "forbid"}
@@ -78,6 +83,8 @@ class VLMConfig(BaseModel):
self.providers[self.provider]["api_base"] = self.api_base
if self.extra_headers and "extra_headers" not in self.providers[self.provider]:
self.providers[self.provider]["extra_headers"] = self.extra_headers
+ if self.stream and "stream" not in self.providers[self.provider]:
+ self.providers[self.provider]["stream"] = self.stream
def _has_any_config(self) -> bool:
"""Check if any config is provided."""
@@ -138,6 +145,11 @@ class VLMConfig(BaseModel):
"""Build VLM instance config dict."""
config, name = self.get_provider_config()
+ # Get stream from provider config if available, fallback to self.stream
+ stream = (
+ config.get("stream") if config and config.get("stream") is not None else self.stream
+ )
+
result = {
"model": self.model,
"temperature": self.temperature,
@@ -145,6 +157,7 @@ class VLMConfig(BaseModel):
"provider": name,
"thinking": self.thinking,
"max_tokens": self.max_tokens,
+ "stream": stream,
}
if config:
diff --git a/tests/unit/test_stream_config_vlm.py b/tests/unit/test_stream_config_vlm.py
new file mode 100644
index 000000000..faf5b6e25
--- /dev/null
+++ b/tests/unit/test_stream_config_vlm.py
@@ -0,0 +1,464 @@
+# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
+# SPDX-License-Identifier: Apache-2.0
+"""Tests for VLM stream configuration support."""
+
+from unittest.mock import MagicMock, patch
+
+import pytest
+
+from openviking.models.vlm.backends.openai_vlm import OpenAIVLM
+
+
+class MockDelta:
+ """Mock delta object for streaming chunks."""
+
+ def __init__(self, content=None):
+ self.content = content
+
+
+class MockChoice:
+ """Mock choice object for streaming chunks."""
+
+ def __init__(self, delta=None):
+ self.delta = delta
+
+
+class MockChunk:
+ """Mock chunk object for streaming response."""
+
+ def __init__(self, content=None, usage=None):
+ self.choices = [MockChoice(delta=MockDelta(content=content))] if content is not None else []
+ self.usage = usage
+
+
+class MockUsage:
+ """Mock usage object."""
+
+ def __init__(self, prompt_tokens=0, completion_tokens=0):
+ self.prompt_tokens = prompt_tokens
+ self.completion_tokens = completion_tokens
+
+
+class TestVLMStreamConfig:
+ """Test stream configuration is passed to OpenAI API calls."""
+
+ @patch("openviking.models.vlm.backends.openai_vlm.openai.OpenAI")
+ def test_stream_false_by_default(self, mock_openai_class):
+ """stream should default to False."""
+ mock_client = MagicMock()
+ mock_response = MagicMock()
+ mock_response.choices = [MagicMock()]
+ mock_response.choices[0].message.content = "Hello"
+ mock_response.usage = None
+ mock_client.chat.completions.create.return_value = mock_response
+ mock_openai_class.return_value = mock_client
+
+ vlm = OpenAIVLM(
+ {
+ "api_key": "sk-test",
+ "api_base": "https://api.openai.com/v1",
+ }
+ )
+
+ vlm.get_completion("test prompt")
+
+ call_kwargs = mock_client.chat.completions.create.call_args[1]
+ assert call_kwargs.get("stream") is False
+
+ @patch("openviking.models.vlm.backends.openai_vlm.openai.OpenAI")
+ def test_stream_true_passed_to_api(self, mock_openai_class):
+ """stream=True should be passed to API call."""
+ mock_client = MagicMock()
+ # Simulate streaming response
+ chunks = [
+ MockChunk(content="Hello"),
+ MockChunk(content=" world"),
+ MockChunk(content="!", usage=MockUsage(prompt_tokens=10, completion_tokens=3)),
+ ]
+ mock_client.chat.completions.create.return_value = iter(chunks)
+ mock_openai_class.return_value = mock_client
+
+ vlm = OpenAIVLM(
+ {
+ "api_key": "sk-test",
+ "api_base": "https://api.openai.com/v1",
+ "stream": True,
+ }
+ )
+
+ result = vlm.get_completion("test prompt")
+
+ call_kwargs = mock_client.chat.completions.create.call_args[1]
+ assert call_kwargs.get("stream") is True
+ assert result == "Hello world!"
+
+ @patch("openviking.models.vlm.backends.openai_vlm.openai.OpenAI")
+ def test_stream_false_uses_non_streaming_path(self, mock_openai_class):
+ """stream=False should use non-streaming response handling."""
+ mock_client = MagicMock()
+ mock_response = MagicMock()
+ mock_response.choices = [MagicMock()]
+ mock_response.choices[0].message.content = "Non-streaming response"
+ mock_response.usage = MockUsage(prompt_tokens=5, completion_tokens=10)
+ mock_client.chat.completions.create.return_value = mock_response
+ mock_openai_class.return_value = mock_client
+
+ vlm = OpenAIVLM(
+ {
+ "api_key": "sk-test",
+ "api_base": "https://api.openai.com/v1",
+ "stream": False,
+ }
+ )
+
+ result = vlm.get_completion("test prompt")
+
+ assert result == "Non-streaming response"
+ call_kwargs = mock_client.chat.completions.create.call_args[1]
+ assert call_kwargs.get("stream") is False
+
+ @patch("openviking.models.vlm.backends.openai_vlm.openai.AsyncOpenAI")
+ async def test_async_stream_true(self, mock_async_openai_class):
+ """stream=True should work with async methods."""
+ mock_client = MagicMock()
+
+ async def async_generator():
+ chunks = [
+ MockChunk(content="Async"),
+ MockChunk(content=" result"),
+ MockChunk(content="!", usage=MockUsage(prompt_tokens=8, completion_tokens=4)),
+ ]
+ for chunk in chunks:
+ yield chunk
+
+ async def mock_create(*args, **kwargs):
+ return async_generator()
+
+ mock_client.chat.completions.create = mock_create
+ mock_async_openai_class.return_value = mock_client
+
+ vlm = OpenAIVLM(
+ {
+ "api_key": "sk-test",
+ "api_base": "https://api.openai.com/v1",
+ "stream": True,
+ }
+ )
+
+ result = await vlm.get_completion_async("test prompt")
+
+ call_kwargs = mock_client.chat.completions.create.call_args[1]
+ assert call_kwargs.get("stream") is True
+ assert result == "Async result!"
+
+ @patch("openviking.models.vlm.backends.openai_vlm.openai.AsyncOpenAI")
+ async def test_async_stream_false(self, mock_async_openai_class):
+ """stream=False should work with async methods."""
+ mock_client = MagicMock()
+ mock_response = MagicMock()
+ mock_response.choices = [MagicMock()]
+ mock_response.choices[0].message.content = "Async non-streaming"
+ mock_response.usage = MockUsage(prompt_tokens=5, completion_tokens=5)
+
+ async def mock_create(*args, **kwargs):
+ return mock_response
+
+ mock_client.chat.completions.create = mock_create
+ mock_async_openai_class.return_value = mock_client
+
+ vlm = OpenAIVLM(
+ {
+ "api_key": "sk-test",
+ "api_base": "https://api.openai.com/v1",
+ "stream": False,
+ }
+ )
+
+ result = await vlm.get_completion_async("test prompt")
+
+ assert result == "Async non-streaming"
+
+ @patch("openviking.models.vlm.backends.openai_vlm.openai.OpenAI")
+ def test_vision_completion_stream_true(self, mock_openai_class):
+ """stream=True should work with vision completion."""
+ mock_client = MagicMock()
+ chunks = [
+ MockChunk(content="Image"),
+ MockChunk(content=" description"),
+ MockChunk(content=".", usage=MockUsage(prompt_tokens=20, completion_tokens=5)),
+ ]
+ mock_client.chat.completions.create.return_value = iter(chunks)
+ mock_openai_class.return_value = mock_client
+
+ vlm = OpenAIVLM(
+ {
+ "api_key": "sk-test",
+ "api_base": "https://api.openai.com/v1",
+ "stream": True,
+ }
+ )
+
+ result = vlm.get_vision_completion("describe this", ["http://example.com/image.jpg"])
+
+ call_kwargs = mock_client.chat.completions.create.call_args[1]
+ assert call_kwargs.get("stream") is True
+ assert result == "Image description."
+
+ @patch("openviking.models.vlm.backends.openai_vlm.openai.AsyncOpenAI")
+ async def test_vision_completion_async_stream_true(self, mock_async_openai_class):
+ """stream=True should work with async vision completion."""
+ mock_client = MagicMock()
+
+ async def async_generator():
+ chunks = [
+ MockChunk(content="Async"),
+ MockChunk(content=" image"),
+ MockChunk(
+ content=" result", usage=MockUsage(prompt_tokens=15, completion_tokens=6)
+ ),
+ ]
+ for chunk in chunks:
+ yield chunk
+
+ async def mock_create(*args, **kwargs):
+ return async_generator()
+
+ mock_client.chat.completions.create = mock_create
+ mock_async_openai_class.return_value = mock_client
+
+ vlm = OpenAIVLM(
+ {
+ "api_key": "sk-test",
+ "api_base": "https://api.openai.com/v1",
+ "stream": True,
+ }
+ )
+
+ result = await vlm.get_vision_completion_async(
+ "describe this", ["http://example.com/image.jpg"]
+ )
+
+ call_kwargs = mock_client.chat.completions.create.call_args[1]
+ assert call_kwargs.get("stream") is True
+ assert result == "Async image result"
+
+
+class TestVLMBaseStreamConfig:
+ """Test VLMBase extracts stream from config."""
+
+ def test_stream_defaults_to_false(self):
+ """VLMBase should default stream to False."""
+
+ class StubVLM(OpenAIVLM):
+ def get_completion(self, prompt, thinking=False):
+ return ""
+
+ async def get_completion_async(self, prompt, thinking=False, max_retries=0):
+ return ""
+
+ def get_vision_completion(self, prompt, images, thinking=False):
+ return ""
+
+ async def get_vision_completion_async(self, prompt, images, thinking=False):
+ return ""
+
+ vlm = StubVLM(
+ {
+ "api_key": "sk-test",
+ }
+ )
+
+ assert vlm.stream is False
+
+ def test_stream_extracted_from_config(self):
+ """VLMBase should extract stream from config."""
+
+ class StubVLM(OpenAIVLM):
+ def get_completion(self, prompt, thinking=False):
+ return ""
+
+ async def get_completion_async(self, prompt, thinking=False, max_retries=0):
+ return ""
+
+ def get_vision_completion(self, prompt, images, thinking=False):
+ return ""
+
+ async def get_vision_completion_async(self, prompt, images, thinking=False):
+ return ""
+
+ vlm = StubVLM(
+ {
+ "api_key": "sk-test",
+ "stream": True,
+ }
+ )
+
+ assert vlm.stream is True
+
+
+class TestVLMConfigStream:
+ """Test VLMConfig passes stream to VLM instance."""
+
+ def test_vlm_config_accepts_stream(self):
+ """VLMConfig should accept stream field."""
+ from openviking_cli.utils.config.vlm_config import VLMConfig
+
+ config = VLMConfig(
+ model="gpt-4o",
+ provider="openai",
+ stream=True,
+ providers={
+ "openai": {
+ "api_key": "sk-test",
+ "api_base": "https://api.openai.com/v1",
+ }
+ },
+ )
+
+ assert config.stream is True
+
+ def test_vlm_config_stream_defaults_to_false(self):
+ """VLMConfig should default stream to False."""
+ from openviking_cli.utils.config.vlm_config import VLMConfig
+
+ config = VLMConfig(
+ model="gpt-4o",
+ provider="openai",
+ providers={
+ "openai": {
+ "api_key": "sk-test",
+ }
+ },
+ )
+
+ assert config.stream is False
+
+ def test_vlm_config_stream_passed_to_vlm_dict(self):
+ """VLMConfig should pass stream to _build_vlm_config_dict."""
+ from openviking_cli.utils.config.vlm_config import VLMConfig
+
+ config = VLMConfig(
+ model="gpt-4o",
+ provider="openai",
+ stream=True,
+ providers={
+ "openai": {
+ "api_key": "sk-test",
+ }
+ },
+ )
+
+ result = config._build_vlm_config_dict()
+ assert result["stream"] is True
+
+ def test_vlm_config_stream_migrated_to_providers(self):
+ """VLMConfig should migrate stream to providers structure."""
+ from openviking_cli.utils.config.vlm_config import VLMConfig
+
+ config = VLMConfig(
+ model="gpt-4o",
+ provider="openai",
+ api_key="sk-test",
+ api_base="https://api.openai.com/v1",
+ stream=True,
+ )
+
+ # Verify stream is migrated to providers structure
+ assert config.providers["openai"]["stream"] is True
+
+ # Verify _build_vlm_config_dict uses the migrated value
+ result = config._build_vlm_config_dict()
+ assert result["stream"] is True
+
+ def test_vlm_config_stream_in_providers_takes_precedence(self):
+ """stream in providers config should take precedence over flat config."""
+ from openviking_cli.utils.config.vlm_config import VLMConfig
+
+ config = VLMConfig(
+ model="gpt-4o",
+ provider="openai",
+ stream=False, # flat config is False
+ providers={
+ "openai": {
+ "api_key": "sk-test",
+ "stream": True, # provider config is True, should take precedence
+ }
+ },
+ )
+
+ result = config._build_vlm_config_dict()
+ assert result["stream"] is True
+
+
+class TestStreamingResponseProcessing:
+ """Test streaming response processing logic."""
+
+ def test_process_streaming_response_with_content(self):
+ """_process_streaming_response should extract content from chunks."""
+ vlm = OpenAIVLM({"api_key": "sk-test"})
+
+ chunks = [
+ MockChunk(content="Hello"),
+ MockChunk(content=" "),
+ MockChunk(content="world"),
+ ]
+
+ result = vlm._process_streaming_response(iter(chunks))
+ assert result == "Hello world"
+
+ def test_process_streaming_response_with_usage(self):
+ """_process_streaming_response should extract usage from chunks."""
+ vlm = OpenAIVLM({"api_key": "sk-test"})
+
+ chunks = [
+ MockChunk(content="Hello", usage=MockUsage(prompt_tokens=10, completion_tokens=5)),
+ ]
+
+ with patch.object(vlm, "update_token_usage") as mock_update:
+ vlm._process_streaming_response(iter(chunks))
+
+ mock_update.assert_called_once_with(
+ model_name="gpt-4o-mini",
+ provider="openai",
+ prompt_tokens=10,
+ completion_tokens=5,
+ )
+
+ def test_process_streaming_response_empty_chunks(self):
+ """_process_streaming_response should handle empty chunks."""
+ vlm = OpenAIVLM({"api_key": "sk-test"})
+
+ result = vlm._process_streaming_response(iter([]))
+ assert result == ""
+
+ @pytest.mark.asyncio
+ async def test_process_streaming_response_async(self):
+ """_process_streaming_response_async should extract content from async chunks."""
+ vlm = OpenAIVLM({"api_key": "sk-test"})
+
+ async def async_chunks():
+ yield MockChunk(content="Async")
+ yield MockChunk(content=" result")
+ yield MockChunk(content="!", usage=MockUsage(prompt_tokens=5, completion_tokens=3))
+
+ result = await vlm._process_streaming_response_async(async_chunks())
+ assert result == "Async result!"
+
+ @pytest.mark.asyncio
+ async def test_process_streaming_response_async_with_usage(self):
+ """_process_streaming_response_async should extract usage from chunks."""
+ vlm = OpenAIVLM({"api_key": "sk-test"})
+
+ async def async_chunks():
+ yield MockChunk(content="Test")
+ yield MockChunk(content="", usage=MockUsage(prompt_tokens=15, completion_tokens=8))
+
+ with patch.object(vlm, "update_token_usage") as mock_update:
+ await vlm._process_streaming_response_async(async_chunks())
+
+ mock_update.assert_called_once_with(
+ model_name="gpt-4o-mini",
+ provider="openai",
+ prompt_tokens=15,
+ completion_tokens=8,
+ )