|
| 1 | +""" |
| 2 | +Example: Using Authentication Session Injection with SentienceAgent |
| 3 | +
|
| 4 | +Demonstrates how to inject pre-recorded authentication sessions (cookies + localStorage) |
| 5 | +into SentienceBrowser to start agents already logged in, bypassing login screens and CAPTCHAs. |
| 6 | +
|
| 7 | +Two Workflows: |
| 8 | +1. Inject Pre-recorded Session: Load a saved session from a JSON file |
| 9 | +2. Persistent Sessions: Use a user data directory to persist sessions across runs |
| 10 | +
|
| 11 | +Benefits: |
| 12 | +- Bypass login screens and CAPTCHAs |
| 13 | +- Save tokens and reduce costs (no login steps needed) |
| 14 | +- Maintain stateful sessions across agent runs |
| 15 | +- Act as authenticated users (access "My Orders", "My Account", etc.) |
| 16 | +
|
| 17 | +Usage: |
| 18 | + # Workflow 1: Inject pre-recorded session |
| 19 | + python examples/auth_injection_agent.py --storage-state auth.json |
| 20 | +
|
| 21 | + # Workflow 2: Use persistent user data directory |
| 22 | + python examples/auth_injection_agent.py --user-data-dir ./chrome_profile |
| 23 | +
|
| 24 | +Requirements: |
| 25 | +- OpenAI API key (OPENAI_API_KEY) for LLM |
| 26 | +- Optional: Sentience API key (SENTIENCE_API_KEY) for Pro/Enterprise features |
| 27 | +- Optional: Pre-saved storage state file (auth.json) or user data directory |
| 28 | +""" |
| 29 | + |
| 30 | +import argparse |
| 31 | +import os |
| 32 | + |
| 33 | +from sentience import SentienceAgent, SentienceBrowser, save_storage_state |
| 34 | +from sentience.llm_provider import OpenAIProvider |
| 35 | + |
| 36 | + |
| 37 | +def example_inject_storage_state(): |
| 38 | + """Example 1: Inject pre-recorded session from file""" |
| 39 | + print("=" * 60) |
| 40 | + print("Example 1: Inject Pre-recorded Session") |
| 41 | + print("=" * 60) |
| 42 | + |
| 43 | + # Path to saved storage state file |
| 44 | + # You can create this file using save_storage_state() after logging in manually |
| 45 | + storage_state_file = "auth.json" |
| 46 | + |
| 47 | + if not os.path.exists(storage_state_file): |
| 48 | + print(f"\n⚠️ Storage state file not found: {storage_state_file}") |
| 49 | + print("\n To create this file:") |
| 50 | + print(" 1. Log in manually to your target website") |
| 51 | + print(" 2. Use save_storage_state() to save the session") |
| 52 | + print("\n Example code:") |
| 53 | + print(" ```python") |
| 54 | + print(" from sentience import SentienceBrowser, save_storage_state") |
| 55 | + print(" browser = SentienceBrowser()") |
| 56 | + print(" browser.start()") |
| 57 | + print(" browser.goto('https://example.com')") |
| 58 | + print(" # ... log in manually ...") |
| 59 | + print(" save_storage_state(browser.context, 'auth.json')") |
| 60 | + print(" ```") |
| 61 | + print("\n Skipping this example...\n") |
| 62 | + return |
| 63 | + |
| 64 | + openai_key = os.environ.get("OPENAI_API_KEY") |
| 65 | + if not openai_key: |
| 66 | + print("❌ Error: OPENAI_API_KEY not set") |
| 67 | + return |
| 68 | + |
| 69 | + # Create browser with storage state injection |
| 70 | + browser = SentienceBrowser( |
| 71 | + storage_state=storage_state_file, # Inject saved session |
| 72 | + headless=False, |
| 73 | + ) |
| 74 | + |
| 75 | + llm = OpenAIProvider(api_key=openai_key, model="gpt-4o-mini") |
| 76 | + agent = SentienceAgent(browser, llm, verbose=True) |
| 77 | + |
| 78 | + try: |
| 79 | + print("\n🚀 Starting browser with injected session...") |
| 80 | + browser.start() |
| 81 | + |
| 82 | + print("🌐 Navigating to authenticated page...") |
| 83 | + # Agent starts already logged in! |
| 84 | + browser.page.goto("https://example.com/orders") # Or your authenticated page |
| 85 | + browser.page.wait_for_load_state("networkidle") |
| 86 | + |
| 87 | + print("\n✅ Browser started with pre-injected authentication!") |
| 88 | + print(" Agent can now access authenticated pages without logging in") |
| 89 | + |
| 90 | + # Example: Use agent on authenticated pages |
| 91 | + agent.act("Show me my recent orders") |
| 92 | + agent.act("Click on the first order") |
| 93 | + |
| 94 | + print("\n✅ Agent execution complete!") |
| 95 | + |
| 96 | + except Exception as e: |
| 97 | + print(f"\n❌ Error: {e}") |
| 98 | + raise |
| 99 | + |
| 100 | + finally: |
| 101 | + browser.close() |
| 102 | + |
| 103 | + |
| 104 | +def example_persistent_session(): |
| 105 | + """Example 2: Use persistent user data directory""" |
| 106 | + print("=" * 60) |
| 107 | + print("Example 2: Persistent Session (User Data Directory)") |
| 108 | + print("=" * 60) |
| 109 | + |
| 110 | + # Directory to persist browser session |
| 111 | + user_data_dir = "./chrome_profile" |
| 112 | + |
| 113 | + openai_key = os.environ.get("OPENAI_API_KEY") |
| 114 | + if not openai_key: |
| 115 | + print("❌ Error: OPENAI_API_KEY not set") |
| 116 | + return |
| 117 | + |
| 118 | + # Create browser with persistent user data directory |
| 119 | + browser = SentienceBrowser( |
| 120 | + user_data_dir=user_data_dir, # Persist cookies and localStorage |
| 121 | + headless=False, |
| 122 | + ) |
| 123 | + |
| 124 | + llm = OpenAIProvider(api_key=openai_key, model="gpt-4o-mini") |
| 125 | + agent = SentienceAgent(browser, llm, verbose=True) |
| 126 | + |
| 127 | + try: |
| 128 | + print("\n🚀 Starting browser with persistent session...") |
| 129 | + browser.start() |
| 130 | + |
| 131 | + # Check if this is first run (no existing session) |
| 132 | + browser.page.goto("https://example.com") |
| 133 | + browser.page.wait_for_load_state("networkidle") |
| 134 | + |
| 135 | + # First run: Agent needs to log in |
| 136 | + # Second run: Agent is already logged in (cookies persist) |
| 137 | + if os.path.exists(user_data_dir): |
| 138 | + print("\n✅ Using existing session from previous run") |
| 139 | + print(" Cookies and localStorage are loaded automatically") |
| 140 | + else: |
| 141 | + print("\n📝 First run - session will be saved after login") |
| 142 | + print(" Next run will automatically use saved session") |
| 143 | + |
| 144 | + # Example: Log in (first run) or use existing session (subsequent runs) |
| 145 | + agent.act("Click the sign in button") |
| 146 | + agent.act("Type your email into the email field") |
| 147 | + agent.act("Type your password into the password field") |
| 148 | + agent.act("Click the login button") |
| 149 | + |
| 150 | + print("\n✅ Session will persist in:", user_data_dir) |
| 151 | + print(" Next run will automatically use this session") |
| 152 | + |
| 153 | + except Exception as e: |
| 154 | + print(f"\n❌ Error: {e}") |
| 155 | + raise |
| 156 | + |
| 157 | + finally: |
| 158 | + browser.close() |
| 159 | + |
| 160 | + |
| 161 | +def example_save_storage_state(): |
| 162 | + """Example 3: Save current session for later use""" |
| 163 | + print("=" * 60) |
| 164 | + print("Example 3: Save Current Session") |
| 165 | + print("=" * 60) |
| 166 | + |
| 167 | + openai_key = os.environ.get("OPENAI_API_KEY") |
| 168 | + if not openai_key: |
| 169 | + print("❌ Error: OPENAI_API_KEY not set") |
| 170 | + return |
| 171 | + |
| 172 | + browser = SentienceBrowser(headless=False) |
| 173 | + llm = OpenAIProvider(api_key=openai_key, model="gpt-4o-mini") |
| 174 | + agent = SentienceAgent(browser, llm, verbose=True) |
| 175 | + |
| 176 | + try: |
| 177 | + print("\n🚀 Starting browser...") |
| 178 | + browser.start() |
| 179 | + |
| 180 | + print("🌐 Navigate to your target website and log in manually...") |
| 181 | + browser.page.goto("https://example.com") |
| 182 | + browser.page.wait_for_load_state("networkidle") |
| 183 | + |
| 184 | + print("\n⏸️ Please log in manually in the browser window") |
| 185 | + print(" Press Enter when you're done logging in...") |
| 186 | + input() |
| 187 | + |
| 188 | + # Save the current session |
| 189 | + storage_state_file = "auth.json" |
| 190 | + save_storage_state(browser.context, storage_state_file) |
| 191 | + |
| 192 | + print(f"\n✅ Session saved to: {storage_state_file}") |
| 193 | + print(" You can now use this file with storage_state parameter:") |
| 194 | + print(f" browser = SentienceBrowser(storage_state='{storage_state_file}')") |
| 195 | + |
| 196 | + except Exception as e: |
| 197 | + print(f"\n❌ Error: {e}") |
| 198 | + raise |
| 199 | + |
| 200 | + finally: |
| 201 | + browser.close() |
| 202 | + |
| 203 | + |
| 204 | +def main(): |
| 205 | + """Run auth injection examples""" |
| 206 | + parser = argparse.ArgumentParser(description="Auth Injection Examples") |
| 207 | + parser.add_argument( |
| 208 | + "--storage-state", |
| 209 | + type=str, |
| 210 | + help="Path to storage state JSON file to inject", |
| 211 | + ) |
| 212 | + parser.add_argument( |
| 213 | + "--user-data-dir", |
| 214 | + type=str, |
| 215 | + help="Path to user data directory for persistent sessions", |
| 216 | + ) |
| 217 | + parser.add_argument( |
| 218 | + "--save-session", |
| 219 | + action="store_true", |
| 220 | + help="Save current session to auth.json", |
| 221 | + ) |
| 222 | + |
| 223 | + args = parser.parse_args() |
| 224 | + |
| 225 | + print("\n" + "=" * 60) |
| 226 | + print("Sentience SDK - Authentication Session Injection Examples") |
| 227 | + print("=" * 60 + "\n") |
| 228 | + |
| 229 | + if args.save_session: |
| 230 | + example_save_storage_state() |
| 231 | + elif args.storage_state: |
| 232 | + # Override default file path |
| 233 | + import sys |
| 234 | + |
| 235 | + sys.modules[__name__].storage_state_file = args.storage_state |
| 236 | + example_inject_storage_state() |
| 237 | + elif args.user_data_dir: |
| 238 | + # Override default directory |
| 239 | + import sys |
| 240 | + |
| 241 | + sys.modules[__name__].user_data_dir = args.user_data_dir |
| 242 | + example_persistent_session() |
| 243 | + else: |
| 244 | + # Run all examples |
| 245 | + example_save_storage_state() |
| 246 | + print("\n") |
| 247 | + example_inject_storage_state() |
| 248 | + print("\n") |
| 249 | + example_persistent_session() |
| 250 | + |
| 251 | + print("\n" + "=" * 60) |
| 252 | + print("Examples Complete!") |
| 253 | + print("=" * 60) |
| 254 | + print("\n💡 Tips:") |
| 255 | + print(" - Use storage_state to inject pre-recorded sessions") |
| 256 | + print(" - Use user_data_dir to persist sessions across runs") |
| 257 | + print(" - Save sessions after manual login for reuse") |
| 258 | + print(" - Bypass login screens and CAPTCHAs with valid sessions") |
| 259 | + print(" - Reduce token costs by skipping login steps\n") |
| 260 | + |
| 261 | + |
| 262 | +if __name__ == "__main__": |
| 263 | + main() |
0 commit comments