web-ui: Error when using DeepSeek on Ollama

It runs with ‘qwen2.5:7b’ so it must be specific to ‘deepseek-r1:14b’ model? Maybe it’s not parsing the data properly? I’m on MacOS and not sure if that’s the issue. I checked off the vision also.

INFO [src.agent.custom_agent] 🚀 Starting task: go to google.com and type 'OpenAI' click search and give me the first url INFO [src.agent.custom_agent] 📍 Step 1 ERROR [agent] ❌ Result failed 1/5 times: Expecting value: line 1 column 1 (char 0) INFO [src.agent.custom_agent] 📍 Step 1 ERROR [agent] ❌ Result failed 2/5 times: Expecting value: line 1 column 1 (char 0) INFO [src.agent.custom_agent] 📍 Step 1 ERROR [agent] ❌ Result failed 3/5 times: Expecting value: line 1 column 1 (char 0) INFO [src.agent.custom_agent] 📍 Step 1 ERROR [agent] ❌ Result failed 4/5 times: Expecting value: line 1 column 1 (char 0) INFO [src.agent.custom_agent] 📍 Step 1 ERROR [agent] ❌ Result failed 5/5 times: Expecting value: line 1 column 1 (char 0) ERROR [agent] ❌ Stopping due to 5 consecutive failures WARNING [src.agent.custom_agent] No history or first screenshot to create GIF from

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Reactions: 3
  • Comments: 20 (2 by maintainers)

Most upvoted comments

and pip install -r requirements.txt, i also update to adapt latest version of browser-use

please update the latest code and try again. recommend use deepseek-r1:14b or bigger. i try 7b and 8b, sometimes it failed to parse json. and please remember uncheck Use Vision.

it breaks with any other models than deepseek r1 thru ollama. Will revise tomorrow

web-ui > src > agent > custom_agent.py

Under CustomAgent class, add:


def _extract_json_from_raw(self, raw_response: str) -> dict:
    """
    Extracts and parses JSON from raw LLM response text.
    :param raw_response: Raw text response from the LLM.
    :return: Parsed JSON as a dictionary.
    """
    try:
        # Log the raw response for debugging
        logger.debug(f"Raw LLM response: {raw_response}")

        # Use regex to locate JSON blocks, allowing for extra text before/after
        json_pattern = re.compile(r"\{.*\}", re.DOTALL)
        matches = json_pattern.findall(raw_response)

        for match in matches:
            try:
                # Try to parse each match as JSON
                return json.loads(match)
            except json.JSONDecodeError as e:
                logger.debug(f"Failed to parse JSON match: {match} | Error: {e}")
                continue  # Try the next match if parsing fails

        # Raise error if no valid JSON is found
        raise ValueError("No valid JSON found in LLM response.")
    except Exception as e:
        logger.error(f"Error extracting JSON from response: {e}")
        raise

Replace get_next_action:


async def get_next_action(self, input_messages: list[BaseMessage]) -> AgentOutput:
    """Get next action from LLM based on current state"""
    if self.use_function_calling:
        try:
            structured_llm = self.llm.with_structured_output(self.AgentOutput, include_raw=True)
            response: dict[str, Any] = await structured_llm.ainvoke(input_messages)  # type: ignore

            parsed: AgentOutput = response['parsed']
            parsed.action = parsed.action[: self.max_actions_per_step]
            self._log_response(parsed)
            self.n_steps += 1

            return parsed
        except Exception as e:
            # If structured output fails, fallback to manual parsing
            ret = self.llm.invoke(input_messages)
            parsed_json = self._extract_json_from_raw(ret.content)
            parsed: AgentOutput = self.AgentOutput(**parsed_json)
            if parsed is None:
                raise ValueError(f'Could not parse response.')

            parsed.action = parsed.action[: self.max_actions_per_step]
            self._log_response(parsed)
            self.n_steps += 1

            return parsed
    else:
        ret = self.llm.invoke(input_messages)
        parsed_json = self._extract_json_from_raw(ret.content)
        parsed: AgentOutput = self.AgentOutput(**parsed_json)
        if parsed is None:
            raise ValueError(f'Could not parse response.')

        parsed.action = parsed.action[: self.max_actions_per_step]
        self._log_response(parsed)
        self.n_steps += 1

        return parsed

web-ui > src > utils > utils.py

Replace qwen2.5:7b with deepseek-r1:14b:


elif provider == "ollama":
    if not kwargs.get("base_url", ""):
        base_url = os.getenv("OLLAMA_ENDPOINT", "http://localhost:11434")
    else:
        base_url = kwargs.get("base_url")
        
    return ChatOllama(
        model=kwargs.get("model_name", "deepseek-r1:14b"),
        temperature=kwargs.get("temperature", 0.0),
        num_ctx=kwargs.get("num_ctx", 32000),
        base_url=base_url,
    )

Add deepseek-r1:14b to model dropdown:


model_names = { “anthropic”: [“claude-3-5-sonnet-20240620”, “claude-3-opus-20240229”], “openai”: [“gpt-4o”, “gpt-4”, “gpt-3.5-turbo”], “deepseek”: [“deepseek-chat”, “deepseek-reasoner”], “gemini”: [“gemini-2.0-flash-exp”, “gemini-2.0-flash-thinking-exp”, “gemini-1.5-flash-latest”, “gemini-1.5-flash-8b-latest”, “gemini-2.0-flash-thinking-exp-1219” ], “ollama”: [“qwen2.5:7b”, “llama2:7b”, “deepseek-r1:14b”], “azure_openai”: [“gpt-4o”, “gpt-4”, “gpt-3.5-turbo”] }