|
| 1 | +#!/usr/bin/env python3 |
| 2 | +""" |
| 3 | +PlannerExecutorAgent example with local HuggingFace models. |
| 4 | +
|
| 5 | +This example demonstrates using local models instead of cloud APIs: |
| 6 | +- Planner: DeepSeek-R1-Distill-Qwen-14B (reasoning model) |
| 7 | +- Executor: Qwen2.5-7B-Instruct (fast instruction following) |
| 8 | +
|
| 9 | +Usage: |
| 10 | + export PREDICATE_API_KEY="sk_..." # Optional, for cloud browser |
| 11 | + python local_models_example.py |
| 12 | +
|
| 13 | +Requirements: |
| 14 | + pip install torch transformers accelerate |
| 15 | +""" |
| 16 | + |
| 17 | +from __future__ import annotations |
| 18 | + |
| 19 | +import asyncio |
| 20 | +import os |
| 21 | +from dataclasses import dataclass |
| 22 | + |
| 23 | +import torch |
| 24 | +from transformers import AutoModelForCausalLM, AutoTokenizer |
| 25 | + |
| 26 | +from predicate import AsyncPredicateBrowser |
| 27 | +from predicate.agent_runtime import AgentRuntime |
| 28 | +from predicate.agents import ( |
| 29 | + PlannerExecutorAgent, |
| 30 | + PlannerExecutorConfig, |
| 31 | + SnapshotEscalationConfig, |
| 32 | +) |
| 33 | +from predicate.backends.playwright_backend import PlaywrightBackend |
| 34 | +from predicate.llm_provider import LLMProvider, LLMResponse |
| 35 | + |
| 36 | + |
| 37 | +@dataclass |
| 38 | +class LocalHFProvider(LLMProvider): |
| 39 | + """ |
| 40 | + Local HuggingFace model provider. |
| 41 | +
|
| 42 | + Loads a model from HuggingFace and runs inference locally. |
| 43 | + """ |
| 44 | + |
| 45 | + def __init__( |
| 46 | + self, |
| 47 | + model_name: str, |
| 48 | + device_map: str = "auto", |
| 49 | + torch_dtype: torch.dtype = torch.bfloat16, |
| 50 | + ): |
| 51 | + super().__init__(model=model_name) |
| 52 | + self._model_name = model_name |
| 53 | + |
| 54 | + print(f"Loading model: {model_name}...") |
| 55 | + self.tokenizer = AutoTokenizer.from_pretrained( |
| 56 | + model_name, |
| 57 | + trust_remote_code=True, |
| 58 | + ) |
| 59 | + self.model = AutoModelForCausalLM.from_pretrained( |
| 60 | + model_name, |
| 61 | + device_map=device_map, |
| 62 | + torch_dtype=torch_dtype, |
| 63 | + trust_remote_code=True, |
| 64 | + low_cpu_mem_usage=True, |
| 65 | + ) |
| 66 | + print(f"Model loaded: {model_name}") |
| 67 | + |
| 68 | + def generate( |
| 69 | + self, |
| 70 | + system_prompt: str, |
| 71 | + user_prompt: str, |
| 72 | + **kwargs, |
| 73 | + ) -> LLMResponse: |
| 74 | + messages = [ |
| 75 | + {"role": "system", "content": system_prompt}, |
| 76 | + {"role": "user", "content": user_prompt}, |
| 77 | + ] |
| 78 | + |
| 79 | + text = self.tokenizer.apply_chat_template( |
| 80 | + messages, |
| 81 | + tokenize=False, |
| 82 | + add_generation_prompt=True, |
| 83 | + ) |
| 84 | + |
| 85 | + inputs = self.tokenizer(text, return_tensors="pt").to(self.model.device) |
| 86 | + prompt_tokens = inputs.input_ids.shape[1] |
| 87 | + |
| 88 | + max_new_tokens = kwargs.get("max_new_tokens", 512) |
| 89 | + temperature = kwargs.get("temperature", 0.0) |
| 90 | + |
| 91 | + with torch.no_grad(): |
| 92 | + outputs = self.model.generate( |
| 93 | + **inputs, |
| 94 | + max_new_tokens=max_new_tokens, |
| 95 | + temperature=temperature if temperature > 0 else None, |
| 96 | + do_sample=temperature > 0, |
| 97 | + pad_token_id=self.tokenizer.eos_token_id, |
| 98 | + ) |
| 99 | + |
| 100 | + completion_tokens = outputs.shape[1] - prompt_tokens |
| 101 | + response_text = self.tokenizer.decode( |
| 102 | + outputs[0][prompt_tokens:], |
| 103 | + skip_special_tokens=True, |
| 104 | + ) |
| 105 | + |
| 106 | + return LLMResponse( |
| 107 | + content=response_text, |
| 108 | + model_name=self._model_name, |
| 109 | + prompt_tokens=prompt_tokens, |
| 110 | + completion_tokens=completion_tokens, |
| 111 | + total_tokens=prompt_tokens + completion_tokens, |
| 112 | + ) |
| 113 | + |
| 114 | + def supports_json_mode(self) -> bool: |
| 115 | + return False |
| 116 | + |
| 117 | + @property |
| 118 | + def model_name(self) -> str: |
| 119 | + return self._model_name |
| 120 | + |
| 121 | + |
| 122 | +async def main() -> None: |
| 123 | + predicate_api_key = os.getenv("PREDICATE_API_KEY") |
| 124 | + |
| 125 | + # Create local model providers |
| 126 | + # Use smaller models for demo; adjust based on your hardware |
| 127 | + planner_model = os.getenv( |
| 128 | + "PLANNER_MODEL", |
| 129 | + "deepseek-ai/DeepSeek-R1-Distill-Qwen-14B", |
| 130 | + ) |
| 131 | + executor_model = os.getenv( |
| 132 | + "EXECUTOR_MODEL", |
| 133 | + "Qwen/Qwen2.5-7B-Instruct", |
| 134 | + ) |
| 135 | + |
| 136 | + planner = LocalHFProvider(planner_model) |
| 137 | + executor = LocalHFProvider(executor_model) |
| 138 | + |
| 139 | + # Create agent with custom config for local models |
| 140 | + config = PlannerExecutorConfig( |
| 141 | + # Slightly larger limits for local models |
| 142 | + snapshot=SnapshotEscalationConfig( |
| 143 | + limit_base=80, |
| 144 | + limit_step=40, |
| 145 | + limit_max=200, |
| 146 | + ), |
| 147 | + # Longer timeouts for local inference |
| 148 | + planner_max_tokens=2048, |
| 149 | + executor_max_tokens=128, |
| 150 | + ) |
| 151 | + |
| 152 | + agent = PlannerExecutorAgent( |
| 153 | + planner=planner, |
| 154 | + executor=executor, |
| 155 | + config=config, |
| 156 | + ) |
| 157 | + |
| 158 | + # Simple task |
| 159 | + task = "Navigate to example.com and find the main heading" |
| 160 | + |
| 161 | + print(f"Task: {task}") |
| 162 | + print(f"Planner: {planner_model}") |
| 163 | + print(f"Executor: {executor_model}") |
| 164 | + print("=" * 60) |
| 165 | + |
| 166 | + async with AsyncPredicateBrowser( |
| 167 | + api_key=predicate_api_key, |
| 168 | + headless=False, |
| 169 | + ) as browser: |
| 170 | + page = await browser.new_page() |
| 171 | + await page.goto("https://example.com") |
| 172 | + await page.wait_for_load_state("networkidle") |
| 173 | + |
| 174 | + backend = PlaywrightBackend(page) |
| 175 | + runtime = AgentRuntime(backend=backend) |
| 176 | + |
| 177 | + result = await agent.run( |
| 178 | + runtime=runtime, |
| 179 | + task=task, |
| 180 | + start_url="https://example.com", |
| 181 | + ) |
| 182 | + |
| 183 | + print("\n" + "=" * 60) |
| 184 | + print(f"Success: {result.success}") |
| 185 | + print(f"Steps: {result.steps_completed}/{result.steps_total}") |
| 186 | + print(f"Duration: {result.total_duration_ms}ms") |
| 187 | + |
| 188 | + |
| 189 | +if __name__ == "__main__": |
| 190 | + asyncio.run(main()) |
0 commit comments