Skip to content

Open-source Python library for AI browser agents, plus Browser Use Cloud: stealth browsers and a hosted agent API.

patch 2 code-style & type-checker : add deepseek llm chat model

boned990ab15df3a
diff --git a/browser_use/llm/deepseek/chat.py b/browser_use/llm/deepseek/chat.py
index b1a0754cb..b13d5c0bb 100644
--- a/browser_use/llm/deepseek/chat.py
+++ b/browser_use/llm/deepseek/chat.py
@@ -5,7 +5,14 @@ from dataclasses import dataclass
from typing import Any, TypeVar, overload
import httpx
-from openai import AsyncOpenAI, APIError, APIConnectionError, APITimeoutError, APIStatusError, RateLimitError
+from openai import (
+ AsyncOpenAI,
+ APIError,
+ APIConnectionError,
+ APITimeoutError,
+ APIStatusError,
+ RateLimitError,
+)
from pydantic import BaseModel
from browser_use.llm.base import BaseChatModel
@@ -99,7 +106,7 @@ class ChatDeepSeek(BaseChatModel):
common["stop"] = stop
# ① 普通多轮对话/文本输出
- if output_format is None and (not tools):
+ if output_format is None and not tools:
try:
resp = await client.chat.completions.create( # type: ignore
model=self.model,
@@ -117,12 +124,12 @@ class ChatDeepSeek(BaseChatModel):
except Exception as e:
raise ModelProviderError(str(e), model=self.name) from e
- # ② Function Calling 路径(有 tools 或 output_format 为 pydantic 模型)
- if tools or (output_format and hasattr(output_format, "model_json_schema")):
+ # ② Function Calling 路径(有 tools 或 output_format)
+ if tools or (output_format is not None and hasattr(output_format, "model_json_schema")):
try:
call_tools = tools
tool_choice = None
- if output_format and hasattr(output_format, "model_json_schema"):
+ if output_format is not None and hasattr(output_format, "model_json_schema"):
tool_name = output_format.__name__
schema = SchemaOptimizer.create_optimized_json_schema(output_format)
schema.pop("title", None)
@@ -152,10 +159,18 @@ class ChatDeepSeek(BaseChatModel):
parsed = json.loads(raw_args)
else:
parsed = raw_args
- return ChatInvokeCompletion(
- completion=output_format.model_validate(parsed),
- usage=None,
- )
+ # --------- 修复点: 只有 output_format 不为 None 才能用 model_validate ----------
+ if output_format is not None:
+ return ChatInvokeCompletion(
+ completion=output_format.model_validate(parsed),
+ usage=None,
+ )
+ else:
+ # 若无 output_format,直接返回 dict
+ return ChatInvokeCompletion(
+ completion=parsed,
+ usage=None,
+ )
except RateLimitError as e:
raise ModelRateLimitError(str(e), model=self.name) from e
except (APIError, APIConnectionError, APITimeoutError, APIStatusError) as e:
diff --git a/browser_use/llm/deepseek/serializer.py b/browser_use/llm/deepseek/serializer.py
index c84e3c954..3f96926c0 100644
--- a/browser_use/llm/deepseek/serializer.py
+++ b/browser_use/llm/deepseek/serializer.py
@@ -1,16 +1,9 @@
-"""
-DeepSeekMessageSerializer
-~~~~~~~~~~~~~~~~~~~~~~~~~
-把 browser-use 自定义消息格式序列化为 DeepSeek(OpenAI-兼容) /chat/completions
-API 可接受的 messages 列表。
-"""
from __future__ import annotations
-import base64
import json
from typing import Any, overload
-from browser_use.llm.messages import ( # 同 Anthropic/Ollama 依赖
+from browser_use.llm.messages import (
AssistantMessage,
BaseMessage,
ContentPartImageParam,
@@ -20,7 +13,6 @@ from browser_use.llm.messages import ( # 同 Anthropic/Ollama 依赖
UserMessage,
)
-# OpenAI-兼容接口的 message 类型 = dict
MessageDict = dict[str, Any]
@@ -28,7 +20,6 @@ class DeepSeekMessageSerializer:
"""Serializer for converting browser-use messages to DeepSeek messages."""
# -------- content 处理 --------------------------------------------------
-
@staticmethod
def _serialize_text_part(part: ContentPartTextParam) -> str:
return part.text
@@ -37,25 +28,15 @@ class DeepSeekMessageSerializer:
def _serialize_image_part(part: ContentPartImageParam) -> dict[str, Any]:
url = part.image_url.url
if url.startswith("data:"):
- # 直接透传 base64 dataURL
return {"type": "image_url", "image_url": {"url": url}}
- # 远程 URL
return {"type": "image_url", "image_url": {"url": url}}
@staticmethod
def _serialize_content(content: Any) -> str | list[dict[str, Any]]:
- """
- 将 browser_use 消息 content 转成 OpenAI 兼容格式:
- - 纯文本 → str
- - 混合(文本/图片等) → list[{type:..., ...}, ...]
- """
if content is None:
return ""
-
if isinstance(content, str):
return content
-
- # content 为 list[ContentPart*]
serialized: list[dict[str, Any]] = []
for part in content:
if part.type == "text":
@@ -69,7 +50,6 @@ class DeepSeekMessageSerializer:
return serialized
# -------- Tool-call 处理 -------------------------------------------------
-
@staticmethod
def _serialize_tool_calls(tool_calls: list[ToolCall]) -> list[dict[str, Any]]:
deepseek_tool_calls: list[dict[str, Any]] = []
@@ -91,7 +71,6 @@ class DeepSeekMessageSerializer:
return deepseek_tool_calls
# -------- 单条消息序列化 -------------------------------------------------
-
@overload
@staticmethod
def serialize(message: UserMessage) -> MessageDict:
@@ -114,28 +93,22 @@ class DeepSeekMessageSerializer:
"role": "user",
"content": DeepSeekMessageSerializer._serialize_content(message.content),
}
-
if isinstance(message, SystemMessage):
return {
"role": "system",
"content": DeepSeekMessageSerializer._serialize_content(message.content),
}
-
if isinstance(message, AssistantMessage):
msg: MessageDict = {
"role": "assistant",
"content": DeepSeekMessageSerializer._serialize_content(message.content),
}
if message.tool_calls:
- msg["tool_calls"] = DeepSeekMessageSerializer._serialize_tool_calls(
- message.tool_calls
- )
+ msg["tool_calls"] = DeepSeekMessageSerializer._serialize_tool_calls(message.tool_calls)
return msg
-
raise ValueError(f"Unknown message type: {type(message)}")
# -------- 列表序列化 -----------------------------------------------------
-
@staticmethod
def serialize_messages(messages: list[BaseMessage]) -> list[MessageDict]:
return [DeepSeekMessageSerializer.serialize(m) for m in messages]