Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.
Python agent-contextagent-memoryagent-pluginsagentic-ragcontext-databasedsh-pluginknowledge-basememorymemory-managementself-evolvingvector-database
# Copyright (c) 2026 Beijing Volcano Engine Technology Co., Ltd.
# SPDX-License-Identifier: AGPL-3.0
"""VolcEngine VLM backend implementation."""
import base64
import json
import time
import uuid
from pathlib import Path
from typing import Any, Dict, List, Optional, Union
from openviking.models.model_error import model_error_boundary
from openviking.models.network import (
create_optional_async_httpx_client,
create_optional_sync_httpx_client,
)
from openviking.telemetry import tracer
from openviking.utils.message_format import format_messages, sanitize_openai_messages
from openviking.utils.multimodal import redact_image_data_urls
from openviking_cli.utils import get_logger
from ..base import ToolCall, VLMResponse
from .openai_vlm import OpenAIVLM
logger = get_logger(__name__)
VOLCENGINE_CLIENT_REQUEST_ID_HEADER = "X-Client-Request-Id"
VOLCENGINE_CLIENT_REQUEST_ID = "ToB-direct,OpenViking_Service,openviking-service_cn-beijing"
DEFAULT_VOLCENGINE_API_BASE = "https://ark.cn-beijing.volces.com/api/v3"
def _build_volcengine_headers(extra_headers: Optional[Dict[str, str]]) -> Dict[str, str]:
headers = dict(extra_headers or {})
if not any(k.lower() == VOLCENGINE_CLIENT_REQUEST_ID_HEADER.lower() for k in headers):
headers[VOLCENGINE_CLIENT_REQUEST_ID_HEADER] = VOLCENGINE_CLIENT_REQUEST_ID
return headers
def build_volcengine_request_headers(
extra_headers: Optional[Dict[str, str]],
) -> Dict[str, str]:
"""Return per-request headers with a unique default client request ID.
The existing prefix identifies OpenViking service traffic. A UUID suffix
makes an individual Ark request searchable while custom client request ID
values remain unchanged.
"""
headers = _build_volcengine_headers(extra_headers)
header_key = next(
key for key in headers if key.lower() == VOLCENGINE_CLIENT_REQUEST_ID_HEADER.lower()
)
if headers[header_key] == VOLCENGINE_CLIENT_REQUEST_ID:
headers[header_key] = f"{VOLCENGINE_CLIENT_REQUEST_ID},{uuid.uuid4().hex}"
return headers
class VolcEngineVLM(OpenAIVLM):
"""VolcEngine VLM backend with Chat Completions API support."""
def __init__(self, config: Dict[str, Any]):
super().__init__(config)
self._sync_client = None
self.provider = "volcengine"
self.extra_headers = _build_volcengine_headers(self.extra_headers)
if not self.api_base:
self.api_base = DEFAULT_VOLCENGINE_API_BASE
if not self.model:
self.model = "doubao-seed-2-0-lite-260428"
def _parse_tool_calls(self, message) -> List[ToolCall]:
"""Parse tool calls from VolcEngine response message."""
tool_calls = []
if hasattr(message, "tool_calls") and message.tool_calls:
for tc in message.tool_calls:
args = tc.function.arguments
if isinstance(args, str):
try:
args = json.loads(args)
except json.JSONDecodeError:
args = {"raw": args}
tool_calls.append(ToolCall(id=tc.id, name=tc.function.name, arguments=args))
return tool_calls
def _build_vlm_response(self, response, has_tools: bool) -> Union[str, VLMResponse]:
"""Build response from Chat Completions response. Returns str or VLMResponse based on has_tools."""
if isinstance(response, str):
return VLMResponse(content=response) if has_tools else response
choice = response.choices[0]
message = choice.message
if hasattr(message, "tool_calls") and message.tool_calls:
tracer.info(f"message.tool_calls={message.tool_calls}")
if has_tools:
usage = {}
if hasattr(response, "usage") and response.usage:
usage = {
"prompt_tokens": response.usage.prompt_tokens,
"completion_tokens": response.usage.completion_tokens,
"total_tokens": response.usage.total_tokens,
"prompt_tokens_details": getattr(response.usage, "prompt_tokens_details", None),
"completion_tokens_details": getattr(
response.usage, "completion_tokens_details", None
),
}
return VLMResponse(
content=message.content,
tool_calls=self._parse_tool_calls(message),
finish_reason=choice.finish_reason or "stop",
usage=usage,
)
return message.content or ""
def get_client(self):
"""Get sync client"""
if self._sync_client is None:
try:
import volcenginesdkarkruntime
except ImportError:
raise ImportError(
"Please install volcenginesdkarkruntime: pip install volcenginesdkarkruntime"
)
kwargs = {
"api_key": self.api_key,
"base_url": self.api_base,
"timeout": self.timeout,
"max_retries": 0,
}
http_client = create_optional_sync_httpx_client(
self.api_base,
timeout=self.timeout,
)
if http_client is not None:
kwargs["http_client"] = http_client
self._sync_client = volcenginesdkarkruntime.Ark(**kwargs)
return self._sync_client
def _build_async_client(self):
"""Create an async client for the current event loop."""
try:
import volcenginesdkarkruntime
except ImportError:
raise ImportError(
"Please install volcenginesdkarkruntime: pip install volcenginesdkarkruntime"
)
kwargs = {
"api_key": self.api_key,
"base_url": self.api_base,
"timeout": self.timeout,
"max_retries": 0,
}
http_client = create_optional_async_httpx_client(
self.api_base,
timeout=self.timeout,
)
if http_client is not None:
kwargs["http_client"] = http_client
return volcenginesdkarkruntime.AsyncArk(**kwargs)
def supports_media(
self,
*,
media_type: str,
filename: str,
size_bytes: int,
) -> bool:
from .volcengine_media import supports_media
return supports_media(
media_type=media_type,
filename=filename,
size_bytes=size_bytes,
)
async def get_media_completion_async(
self,
*,
prompt: str,
media_path: Path,
filename: str,
media_type: str,
) -> str:
from .volcengine_media import understand_media
return await understand_media(
self,
prompt=prompt,
media_path=media_path,
filename=filename,
media_type=media_type,
)
@model_error_boundary
def get_completion(
self,
prompt: str = "",
thinking: Optional[bool] = None,
tools: Optional[List[Dict[str, Any]]] = None,
tool_choice: Optional[str] = None,
messages: Optional[List[Dict[str, Any]]] = None,
) -> Union[str, VLMResponse]:
"""Get text completion; configured effort applies only when thinking is enabled."""
effective_thinking = self.thinking if thinking is None else thinking
kwargs_messages = sanitize_openai_messages(
messages or [{"role": "user", "content": prompt}]
)
kwargs = {
"model": self.model or "doubao-seed-2-0-lite-260428",
"messages": kwargs_messages,
"temperature": self.temperature,
"thinking": {"type": "disabled" if not effective_thinking else "enabled"},
"extra_headers": build_volcengine_request_headers(self.extra_headers),
}
if self.extra_request_body:
kwargs["extra_body"] = dict(self.extra_request_body)
if self.max_tokens is not None:
kwargs["max_tokens"] = self.max_tokens
if effective_thinking and self.reasoning_effort is not None:
kwargs["reasoning_effort"] = self.reasoning_effort
if tools:
kwargs["tools"] = tools
kwargs["tool_choice"] = tool_choice or "auto"
client = self.get_client()
t0 = time.perf_counter()
try:
response = client.chat.completions.create(**kwargs)
except Exception as error:
self.record_failed_call(duration_seconds=time.perf_counter() - t0, error=error)
raise
elapsed = time.perf_counter() - t0
self._update_token_usage_from_response(response, duration_seconds=elapsed)
if tools is not None:
result = self._build_vlm_response(response, has_tools=True)
if not tools:
result.content = self._clean_response(result.content or "")
return result
result = self._build_vlm_response(response, has_tools=False)
return self._clean_response(str(result))
@model_error_boundary
async def get_completion_async(
self,
prompt: str = "",
thinking: Optional[bool] = None,
tools: Optional[List[Dict[str, Any]]] = None,
tool_choice: Optional[str] = None,
messages: Optional[List[Dict[str, Any]]] = None,
max_tokens: Optional[int] = None,
reasoning_effort: Optional[str] = None,
) -> Union[str, VLMResponse]:
"""Get text completion; explicit effort overrides configured effort when thinking is enabled."""
effective_thinking = self.thinking if thinking is None else thinking
if reasoning_effort is None:
reasoning_effort = self.reasoning_effort
effective_max_tokens = max_tokens if max_tokens is not None else self.max_tokens
kwargs_messages = sanitize_openai_messages(
messages or [{"role": "user", "content": prompt}]
)
kwargs = {
"model": self.model or "doubao-seed-2-0-lite-260428",
"messages": kwargs_messages,
"temperature": self.temperature,
"thinking": {"type": "disabled" if not effective_thinking else "enabled"},
"extra_headers": build_volcengine_request_headers(self.extra_headers),
}
if self.extra_request_body:
kwargs["extra_body"] = dict(self.extra_request_body)
if effective_max_tokens is not None:
kwargs["max_tokens"] = effective_max_tokens
if effective_thinking and reasoning_effort is not None:
kwargs["reasoning_effort"] = reasoning_effort
if tools:
kwargs["tools"] = tools
kwargs["tool_choice"] = tool_choice or "auto"
# 用 tracer.info 打印请求(人类可读格式)
tracer.info(
"llm_input_messages=" + format_messages(redact_image_data_urls(kwargs_messages))
)
if tools:
tracer.info(
f"tools: {json.dumps([t['function']['name'] for t in tools], ensure_ascii=False)}"
)
client = self.get_async_client()
async def _call() -> Union[str, VLMResponse]:
t0 = time.perf_counter()
try:
response = await client.chat.completions.create(**kwargs)
except Exception as error:
self.record_failed_call(duration_seconds=time.perf_counter() - t0, error=error)
raise
elapsed = time.perf_counter() - t0
self._update_token_usage_from_response(response, duration_seconds=elapsed)
if tools is not None:
result = self._build_vlm_response(response, has_tools=True)
if not tools:
result.content = self._clean_response(result.content or "")
return result
result = self._build_vlm_response(response, has_tools=False)
content = self._clean_response(str(result))
if content:
tracer.info(f"message.content={content}")
return content
return await _call()
def _detect_image_format(self, data: bytes) -> str:
"""Detect image format from magic bytes.
Returns the MIME type, or raises ValueError for unsupported formats like SVG.
Supported formats per VolcEngine docs:
https://www.volcengine.com/docs/82379/1362931
- JPEG, PNG, GIF, WEBP, BMP, TIFF, ICO, DIB, ICNS, SGI, JPEG2000, HEIC, HEIF
"""
if len(data) < 12:
logger.warning(f"[VolcEngineVLM] Image data too small: {len(data)} bytes")
return "image/png"
# PNG: 89 50 4E 47 0D 0A 1A 0A
if data[:8] == b"\x89PNG\r\n\x1a\n":
return "image/png"
# JPEG: FF D8
elif data[:2] == b"\xff\xd8":
return "image/jpeg"
# GIF: GIF87a or GIF89a
elif data[:6] in (b"GIF87a", b"GIF89a"):
return "image/gif"
# WEBP: RIFF....WEBP
elif data[:4] == b"RIFF" and len(data) >= 12 and data[8:12] == b"WEBP":
return "image/webp"
# BMP: BM
elif data[:2] == b"BM":
return "image/bmp"
# TIFF (little-endian): 49 49 2A 00
# TIFF (big-endian): 4D 4D 00 2A
elif data[:4] == b"II*\x00" or data[:4] == b"MM\x00*":
return "image/tiff"
# ICO: 00 00 01 00
elif data[:4] == b"\x00\x00\x01\x00":
return "image/ico"
# ICNS: 69 63 6E 73 ("icns")
elif data[:4] == b"icns":
return "image/icns"
# SGI: 01 DA
elif data[:2] == b"\x01\xda":
return "image/sgi"
# JPEG2000: 00 00 00 0C 6A 50 20 20 (JP2 signature)
elif data[:8] == b"\x00\x00\x00\x0cjP " or data[:4] == b"\xff\x4f\xff\x51":
return "image/jp2"
# HEIC/HEIF: ftyp box with heic/heif brand
# 00 00 00 XX 66 74 79 70 68 65 69 63 (heic)
# 00 00 00 XX 66 74 79 70 68 65 69 66 (heif)
elif len(data) >= 12 and data[4:8] == b"ftyp":
brand = data[8:12]
if brand == b"heic":
return "image/heic"
elif brand == b"heif":
return "image/heif"
elif brand[:3] == b"mif":
return "image/heif"
# SVG (not supported)
elif data[:4] == b"<svg" or (data[:5] == b"<?xml" and b"<svg" in data[:100]):
raise ValueError(
"SVG format is not supported by VolcEngine VLM API. "
"Supported formats: JPEG, PNG, GIF, WEBP, BMP, TIFF, ICO, ICNS, SGI, JPEG2000, HEIC, HEIF"
)
# Unknown format - log and default to PNG
logger.warning(f"[VolcEngineVLM] Unknown image format, magic bytes: {data[:16].hex()}")
return "image/png"
def _prepare_image(self, image: Union[str, Path, bytes]) -> Dict[str, Any]:
"""Prepare image data"""
if isinstance(image, bytes):
b64 = base64.b64encode(image).decode("utf-8")
mime_type = self._detect_image_format(image)
logger.info(
f"[VolcEngineVLM] Preparing image from bytes, size={len(image)}, detected mime={mime_type}"
)
return {
"type": "image_url",
"image_url": {"url": f"data:{mime_type};base64,{b64}"},
}
elif isinstance(image, Path) or (
isinstance(image, str) and not image.startswith(("http://", "https://"))
):
path = Path(image)
suffix = path.suffix.lower()
mime_type = {
".png": "image/png",
".jpg": "image/jpeg",
".jpeg": "image/jpeg",
".gif": "image/gif",
".webp": "image/webp",
".bmp": "image/bmp",
".dib": "image/bmp",
".tiff": "image/tiff",
".tif": "image/tiff",
".ico": "image/ico",
".icns": "image/icns",
".sgi": "image/sgi",
".j2c": "image/jp2",
".j2k": "image/jp2",
".jp2": "image/jp2",
".jpc": "image/jp2",
".jpf": "image/jp2",
".jpx": "image/jp2",
".heic": "image/heic",
".heif": "image/heif",
}.get(suffix, "image/png")
with open(path, "rb") as f:
b64 = base64.b64encode(f.read()).decode("utf-8")
return {
"type": "image_url",
"image_url": {"url": f"data:{mime_type};base64,{b64}"},
}
else:
return {"type": "image_url", "image_url": {"url": image}}
@model_error_boundary
def get_vision_completion(
self,
prompt: str = "",
images: Optional[List[Union[str, Path, bytes]]] = None,
thinking: Optional[bool] = None,
tools: Optional[List[Dict[str, Any]]] = None,
tool_choice: Optional[str] = None,
messages: Optional[List[Dict[str, Any]]] = None,
) -> Union[str, VLMResponse]:
"""Get vision completion via Chat Completions API."""
effective_thinking = self.thinking if thinking is None else thinking
if messages:
kwargs_messages = sanitize_openai_messages(messages)
else:
content = []
if images:
content.extend(self._prepare_image(img) for img in images)
if prompt:
content.append({"type": "text", "text": prompt})
kwargs_messages = sanitize_openai_messages([{"role": "user", "content": content}])
kwargs = {
"model": self.model or "doubao-seed-2-0-lite-260428",
"messages": kwargs_messages,
"temperature": self.temperature,
"thinking": {"type": "disabled" if not effective_thinking else "enabled"},
"extra_headers": build_volcengine_request_headers(self.extra_headers),
}
if self.extra_request_body:
kwargs["extra_body"] = dict(self.extra_request_body)
if self.max_tokens is not None:
kwargs["max_tokens"] = self.max_tokens
if tools:
kwargs["tools"] = tools
kwargs["tool_choice"] = tool_choice or "auto"
client = self.get_client()
t0 = time.perf_counter()
try:
response = client.chat.completions.create(**kwargs)
except Exception as error:
self.record_failed_call(duration_seconds=time.perf_counter() - t0, error=error)
raise
elapsed = time.perf_counter() - t0
self._update_token_usage_from_response(response, duration_seconds=elapsed)
if tools is not None:
result = self._build_vlm_response(response, has_tools=True)
if not tools:
result.content = self._clean_response(result.content or "")
return result
result = self._build_vlm_response(response, has_tools=False)
return self._clean_response(str(result))
@model_error_boundary
async def get_vision_completion_async(
self,
prompt: str = "",
images: Optional[List[Union[str, Path, bytes]]] = None,
thinking: Optional[bool] = None,
tools: Optional[List[Dict[str, Any]]] = None,
tool_choice: Optional[str] = None,
messages: Optional[List[Dict[str, Any]]] = None,
) -> Union[str, VLMResponse]:
"""Get vision completion asynchronously via Chat Completions API."""
effective_thinking = self.thinking if thinking is None else thinking
if messages:
kwargs_messages = sanitize_openai_messages(messages)
else:
content = []
if images:
content.extend(self._prepare_image(img) for img in images)
if prompt:
content.append({"type": "text", "text": prompt})
kwargs_messages = sanitize_openai_messages([{"role": "user", "content": content}])
kwargs = {
"model": self.model or "doubao-seed-2-0-lite-260428",
"messages": kwargs_messages,
"temperature": self.temperature,
"thinking": {"type": "disabled" if not effective_thinking else "enabled"},
"extra_headers": build_volcengine_request_headers(self.extra_headers),
}
if self.extra_request_body:
kwargs["extra_body"] = dict(self.extra_request_body)
if self.max_tokens is not None:
kwargs["max_tokens"] = self.max_tokens
if tools:
kwargs["tools"] = tools
kwargs["tool_choice"] = tool_choice or "auto"
client = self.get_async_client()
t0 = time.perf_counter()
try:
response = await client.chat.completions.create(**kwargs)
except Exception as error:
self.record_failed_call(duration_seconds=time.perf_counter() - t0, error=error)
raise
elapsed = time.perf_counter() - t0
self._update_token_usage_from_response(response, duration_seconds=elapsed)
if tools is not None:
result = self._build_vlm_response(response, has_tools=True)
if not tools:
result.content = self._clean_response(result.content or "")
return result
result = self._build_vlm_response(response, has_tools=False)
return self._clean_response(str(result))