browser-use: [BUG] Gemini does not work with Browser-Use

@MahlerTom and I are trying to use Browser-Use with gemini, but it doesn’t seem to work. The problem is mostly related to https://github.com/langchain-ai/langchain-google/issues/657 and we opened an issue and a PR to fix that: https://github.com/langchain-ai/langchain-google/pull/658 for anyone experiencing the same issues.

However, we also discovered that when sending the llm.with_structured_output here:

@time_execution_async('--get_next_action')
	async def get_next_action(self, input_messages: list[BaseMessage]) -> AgentOutput:
		"""Get next action from LLM based on current state"""

		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']

		self._log_response(parsed)
		self.n_steps += 1

		return parsed

It makes a big difference if the pydantic fields include a description.

We propose adding descriptions for all the pydantic classes in browser-use, for example instead of:

class AgentBrain(BaseModel):
	"""Current state of the agent"""

	valuation_previous_goal: str
	memory: str
	next_goal: str

It is better to do this:

class AgentBrain(BaseModel):
	"""Current state of the agent"""

	valuation_previous_goal: str = Field(
		...,
		description="String starting with 'Success', 'Failed:' or 'Unknown' to evaluate if the previous next_goal is achieved. If failed or unknown describe why.",
	)
	memory: str = Field(
		...,
		description="Your memory with things you need to remember until the end of the task for the user. You can also store overall progress in a bigger task. You have access to this in the next steps.",
	)
	next_goal: str = Field(
		...,
		description="String describing the next immediate goal which can be achieved with one action",
	)

This is based on the prompts from browser_use\agent\prompts.py. BTW, in this particular case, we could also remove this part:

You have to respond in the following RESPONSE FORMAT: 
{self.response_format()}

from SystemPrompt.get_system_message

As the descriptions will already be included in the pydantic structure.

We didn’t submit a PR yet because it’s a big change and we wanted to discuss it with you before making it.

What do you think?

About this issue

  • Original URL
  • State: open
  • Created 2 years ago
  • Reactions: 7
  • Comments: 17 (3 by maintainers)

Commits related to this issue

Most upvoted comments

Would be great if it works with Google Gemini since I think it’s the only LLM service that allows to test without any cost 😅.

fwiw this doesnt work with langchain-google-vertexai

Instead of depending on Langchain for multiple model integration can we integrate agent services to utilize “https://github.com/andrewyng/aisuite”

Simple, unified interface to multiple Generative AI providers.

aisuite makes it easy for developers to use multiple LLM through a standardized interface. Using an interface similar to OpenAI’s, aisuite makes it easy to interact with the most popular LLMs and compare the results. It is a thin wrapper around python client libraries, and allows creators to seamlessly swap out and test responses from different LLM providers without changing their code. Today, the library is primarily focussed on chat completions. We will expand it cover more use cases in near future.

Currently supported providers are - OpenAI, Anthropic, Azure, Google, AWS, Groq, Mistral, HuggingFace Ollama, Sambanova and Watsonx. To maximize stability, aisuite uses either the HTTP endpoint or the SDK for making calls to the provider.

Langchain still did not push the pr, we applied the changes from the pr above (langchain-ai/langchain-google#657) locally and it works perfectly with Gemini. Hope they accept the pr soon so it’s part of the official version.

Have you gotten it to work with Groq API yet? I keep getting this error with my code

📍 Step 1        
ERROR    [agent] ❌ Result failed 1/5 times:
 Error code: 400 - {'error': {'message': 'message[2].content must be a string', 'type': 'invalid_request_error'}}
import os
from langchain_groq import ChatGroq
from browser_use import Agent

async def main():
    agent = Agent(
        task="What is the capital of France?",        
        llm=ChatGroq(
            model="llama3-8b-8192",
            temperature=0,
            max_tokens=None,
            groq_api_key=os.getenv('GROQ_API_KEY')
        )
    )

    try:
        result = await agent.run()
        print(result)
    except ValueError as e:
        print(f"Validation error: {str(e)}")
    except Exception as e:
        print(f"An error occurred: {str(e)}")

if __name__ == "__main__":
    import asyncio
    asyncio.run(main())

The issue is likely within the browser_use library’s code where it formats the prompt for the LLM. It’s probably constructing a message where the content field is accidentally set to a non-string value, such as a list, dictionary, or None.

any thoughts?

langchain-google-genai 2.0.8 has released and with browser-use-0.1.19, demo script worked with Gemini(*) 🙌 @Shahar-Y Thank you very much for https://github.com/langchain-ai/langchain-google/pull/658

(*) I use Google AI Gemini API with GOOGLE_API_KEY environment variable. https://cloud.google.com/vertex-ai/generative-ai/docs/overview#how-gemini-vertex-different-gemini-aistudio

hi, I managed to work around the vertex AI anyOf issue by modifying the .venv/lib/python3.11/site-packages/langchain_google_vertexai/functions_utils.py file locally. Change pydantic_version to “v2”.

    tool: Union[FunctionDescription, Dict[str, Any]],
) -> gapic.FunctionDeclaration:
    # Ensure we send "anyOf" parameters through pydantic v2 schema parsing
    pydantic_version = "v2"       ####              <------------------ CHANGE THIS TO V2 !

    if isinstance(tool, dict):
        properties = tool.get("parameters", {}).get("properties", {}).values()
        for property in properties:
            if "anyOf" in property:
                pydantic_version = "v2"
    if pydantic_version:
        parameters = _dict_to_gapic_schema(
            tool.get("parameters", {}), pydantic_version=pydantic_version
        )
    else:
        parameters = _dict_to_gapic_schema(tool.get("parameters", {}))

    return gapic.FunctionDeclaration(
        name=tool.get("name"),
        description=tool.get("description"),
        parameters=parameters,
    )

This loop seems to be bugged, because “anyOf” is hidden in a deeper level of the properties.

Great work @Shahar-Y Langchain merged your improvement - we are only waiting for a new pip release to update browser-use.

For what does it make a big difference if the pydantic fields include a description? - Do all APIs include that description in the system prompt - so that we can remove

{self.response_format()}

Of course we can make that change. Happy to accept that PR.

Huge news @MagMueller I wonder, is this issue related to #7?

It seems to be the same error we saw, so it probably has the same origin. We must have missed it when we opened the issue.

Okay thanks @Shahar-Y! Will test it out once browser-use is updated in pip

Huge news @MagMueller

I wonder, is this issue related to #7?

It seems to be the same error we saw, so it probably has the same origin. We must have missed it when we opened the issue.

Yeah this can be a separate issue but if we can integrate aisute developed by Andrew NG we can easily configure any llm providers and use it without need of separately looking for structured output dependices via langchain model integrations,

This can be one Stop solution for all kind of model usage.

Langchain still did not push the pr, we applied the changes from the pr above (langchain-ai/langchain-google#657) locally and it works perfectly with Gemini. Hope they accept the pr soon so it’s part of the official version.