Skip to content

Instantly share code, notes, and snippets.

@liruqi
Created March 29, 2026 11:12
Show Gist options
  • Select an option

  • Save liruqi/e70295e4b0abe241b74a87a14cf7d5f7 to your computer and use it in GitHub Desktop.

Select an option

Save liruqi/e70295e4b0abe241b74a87a14cf7d5f7 to your computer and use it in GitHub Desktop.
Get Google AI mode answer with Cloudflare AI gateway
import asyncio
import sys
import os
from dotenv import load_dotenv
from browser_use import Agent, Browser, BrowserProfile, ChatOpenAI
load_dotenv()
# Cloudflare AI Gateway provider-specific endpoint for OpenAI.
# To use an authenticated gateway with the OpenAI upstream:
# 1. Pass the OpenAI API key as the standard 'api_key'.
# 2. Pass the Cloudflare Token as a 'cf-aig-authorization' header.
CF_GATEWAY_URL = "https://gateway.ai.cloudflare.com/v1/{REPLACE-WITH-YOUR-CF-ID}/openclaw/openai/v1"
async def main():
# Get query from CLI or use default
query = " ".join(sys.argv[1:]) if len(sys.argv) > 1 else "introduce meme TACO"
# Reuse your existing Chrome profile (cookies, Google login, AI mode access).
# IMPORTANT: Chrome must be fully closed before running, otherwise it will
# lock the profile and prevent the agent from opening it.
chrome_profile = BrowserProfile(
user_data_dir=os.path.expanduser("~/Library/Application Support/Google/Chrome"),
profile_directory="Default",
)
browser = Browser(browser_profile=chrome_profile)
# Use browser_use's ChatOpenAI wrapper.
# We provide the OpenAI key and the Cloudflare Auth token separately.
llm = ChatOpenAI(
model=os.environ.get("CF_MODEL", "gpt-4o"),
api_key=os.environ.get("OPENAI_API_KEY"),
base_url=CF_GATEWAY_URL,
default_headers={"cf-aig-authorization": f"Bearer {os.environ.get('CF_API_KEY')}"},
add_schema_to_system_prompt=True,
dont_force_structured_output=True,
frequency_penalty=None,
max_completion_tokens=None,
)
task = (
f"Go to google.com, Click the 'AI mode' button if available and search for '{query}'. "
f"wait for the AI mode to finish generating. "
f"Return the markdown answer."
)
agent = Agent(
browser=browser,
task=task,
llm=llm,
extend_system_message="IMPORTANT: You MUST respond with ONLY raw JSON. DO NOT use markdown code blocks (like ```json). Your entire response must be a single valid JSON object satisfying the provided schema.",
)
print(f"--- Running search for: {query} ---")
history = await agent.run()
print("\n--- AI Agent Result ---")
print(history.final_result())
if __name__ == "__main__":
asyncio.run(main())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment