Repository navigation
feat(integrations): add Deep Agents examples #2653
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
428644e
feat(integrations): add Deep Agents examples
miguelg719 4127593
docs(integrations): security model section + de-vendor accuracy in de…
miguelg719 386ebff
fix(integrations): deepagents review findings
miguelg719 8cccd4d
test(docs): bound the sdk-reference parity test at 30s
miguelg719 2c2d712
fix(integrations): deepagents follow-ups from review threads
miguelg719 10d1807
revert(integrations): restore local example model defaults
miguelg719 8e9e87a
chore(integrations): use published stagehand wheel
miguelg719 f00e673
chore(integrations): default managed deep-agent model to openai:gpt-5…
miguelg719 df620a0
fix(integrations): default local browser to headed
miguelg719 File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,5 @@ | ||
| .venv/ | ||
| __pycache__/ | ||
| .pytest_cache/ | ||
| .ruff_cache/ | ||
| *.py[cod] |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| 3.11 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,109 @@ | ||
| # Stagehand Deep Agents integration | ||
|
|
||
| This local integration exposes one stateful Stagehand browser to LangChain Deep Agents through a | ||
| stdio MCP server. Its complete tool surface is `run`, `snapshot`, and `screenshot`. | ||
|
|
||
| ## Run locally | ||
|
|
||
| Set a model-provider key and select the Deep Agents model: | ||
|
|
||
| ```bash | ||
| export OPENAI_API_KEY=... | ||
| export DEEPAGENTS_MODEL=openai:gpt-5.6-luna | ||
| ``` | ||
|
|
||
| The MCP server launches a visible local Chrome browser by default. Then run: | ||
|
|
||
| ```bash | ||
| cd packages/integrations/deepagents | ||
| uv run --project examples/local python examples/local/agent.py | ||
| ``` | ||
|
|
||
| The model, instruction, and Pydantic response classes are declared directly in `agent.py` so the | ||
| example can be edited and rerun without passing command-line arguments. Set `response_format` to a | ||
| Pydantic model class for structured output, or `None` for the normal text response. | ||
|
|
||
| `agents2.py` is a form-filling example inspired by Stagehand's sensible form-filling example. The | ||
| Deep Agent navigates to the form, snapshots it, fills the requested fields with mock data, and | ||
| returns a typed Pydantic summary without submitting the form: | ||
|
|
||
| ```bash | ||
| uv run --project examples/local python examples/local/agents2.py | ||
| ``` | ||
|
|
||
| To use Browserbase instead: | ||
|
|
||
| ```bash | ||
| export STAGEHAND_BROWSER=browserbase | ||
| export BROWSERBASE_API_KEY=... | ||
| uv run --project examples/local python examples/local/agent.py | ||
| ``` | ||
|
|
||
| Browserbase sessions use a 1280 × 720 viewport by default. | ||
|
|
||
| The server and client intentionally use separate Python environments. Stagehand currently requires | ||
| `websockets>=16.1.1`, while the current LangGraph SDK used by Deep Agents requires `websockets<16`. | ||
| The stdio transport isolates those dependency sets. | ||
|
|
||
| The example deliberately creates a persistent MCP `ClientSession`. Do not replace it with | ||
| `MultiServerMCPClient.get_tools()`: the default stateless tools create a new stdio process for each | ||
| call and therefore lose the browser and snapshot IDs. | ||
|
|
||
| ## Server configuration | ||
|
|
||
| | Variable | Default | Meaning | | ||
| | -------------------------- | ------- | -------------------------------------------------------- | | ||
| | `STAGEHAND_BROWSER` | `local` | `local` or `browserbase` | | ||
| | `STAGEHAND_HEADLESS` | `false` | Headless local Chrome | | ||
| | `STAGEHAND_START_URL` | unset | Optional URL opened when the server starts | | ||
| | `STAGEHAND_MODEL` | unset | Optional model used by Stagehand AI methods inside `run` | | ||
| | `STAGEHAND_RUN_TIMEOUT_MS` | `60000` | Callback-batch timeout | | ||
| | `BROWSERBASE_API_KEY` | unset | Required for Browserbase | | ||
|
|
||
| `run` accepts exactly one of JavaScript `code` or snapshot `actions`. JavaScript executes against | ||
| the Playwright-shaped `page`, `context`, and `browser` facade. Snapshot actions use bracketed IDs | ||
| from the most recent `snapshot` call. | ||
|
|
||
| ## Managed Deep Agents | ||
|
|
||
| The managed example lives in `examples/managed`. Its authored LangChain tools run the Python | ||
| Stagehand SDK directly and expose the same `run`, `snapshot`, and `screenshot` contract. The managed | ||
| thread ID is injected by `ToolRuntime` and scopes an in-process Browserbase runtime; it is not | ||
|
miguelg719 marked this conversation as resolved.
Resolved
|
||
| exposed to the model. | ||
|
|
||
| The current LangGraph SDK requires `websockets<16`, while Stagehand declares `websockets>=16.1.1`. | ||
| For this spike, the managed project overrides the shared dependency to `websockets==15.0.1`. Remove | ||
| the override once the SDK ranges converge. Browser continuity is guaranteed while the managed | ||
|
miguelg719 marked this conversation as resolved.
Resolved
|
||
| worker remains warm; durable reconnection after worker replacement is future work. | ||
|
|
||
| ### Develop and deploy the managed agent | ||
|
|
||
| From `examples/managed`, copy `.env.example` to `.env` and configure: | ||
|
|
||
| - `DEEPAGENTS_MODEL` and the matching provider key, such as `OPENAI_API_KEY`. | ||
| - `BROWSERBASE_API_KEY` for the hosted browser. | ||
| - Either `STAGEHAND_API_URL` for Browserbase Model Gateway, or `STAGEHAND_MODEL` plus | ||
| `STAGEHAND_MODEL_API_KEY` for direct-provider BYOK. | ||
|
|
||
| Then run: | ||
|
|
||
| ```bash | ||
| uv sync | ||
| uv run mda dev . | ||
| uv run mda deploy . | ||
| ``` | ||
|
|
||
| Managed Deep Agents forwards non-reserved `.env` entries as deployment secrets. The agent model key | ||
| and the optional Stagehand model key are independent: users can bring their own key for either, | ||
| while Browserbase Model Gateway remains the zero-additional-key Stagehand path. | ||
|
|
||
| The published `stagehand` wheel bundles the browser extension and `browserbase.launch` provisions | ||
| it automatically. Set `STAGEHAND_EXTENSION_ID` to reuse a pre-uploaded extension instead. | ||
|
|
||
| ## Security model | ||
|
|
||
| The `run` tool executes model-authored JavaScript inside the Stagehand browser extension's service | ||
| worker — browser-side, never in the host process. Browserbase is the recommended isolation | ||
| boundary: the privileged execution environment is a disposable cloud browser with no access to the | ||
| host machine. Only `STAGEHAND_*` and `BROWSERBASE_*` environment variables are forwarded to the | ||
|
miguelg719 marked this conversation as resolved.
Resolved
|
||
| browser session; host secrets such as the deep-agent model key never reach it. | ||
1 change: 1 addition & 0 deletions
1
packages/integrations/deepagents/examples/local/.python-version
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1 @@ | ||
| 3.11 |
47 changes: 47 additions & 0 deletions
47
packages/integrations/deepagents/examples/local/_client.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,47 @@ | ||
| """Shared MCP client config for the local Deep Agents examples. | ||
|
|
||
| The MCP stdio client strips the parent environment down to a safe default | ||
| set (HOME, PATH, SHELL, TERM, USER), so the server would never see | ||
| STAGEHAND_* / BROWSERBASE_* configuration without an explicit env block. | ||
| Every script in this example builds its client here so the allowlist can't | ||
| regress in one copy. | ||
| """ | ||
|
|
||
| from __future__ import annotations | ||
|
|
||
| import os | ||
| from pathlib import Path | ||
|
|
||
| from langchain_mcp_adapters.client import MultiServerMCPClient | ||
|
|
||
| SERVER_NAME = "stagehand_browser" | ||
|
|
||
| _SERVER_PROJECT = Path(__file__).resolve().parents[2] | ||
|
|
||
|
|
||
| def _allowlisted_env() -> dict[str, str]: | ||
|
miguelg719 marked this conversation as resolved.
Resolved
|
||
| """Forward only STAGEHAND_* and BROWSERBASE_* variables to the server.""" | ||
| return { | ||
| name: value | ||
| for name, value in os.environ.items() | ||
| if (name.startswith("STAGEHAND_") or name.startswith("BROWSERBASE_")) and value | ||
| } | ||
|
|
||
|
|
||
| def create_stagehand_client() -> MultiServerMCPClient: | ||
| return MultiServerMCPClient( | ||
| { | ||
| SERVER_NAME: { | ||
| "transport": "stdio", | ||
| "command": "uv", | ||
| "args": [ | ||
| "run", | ||
| "--project", | ||
| str(_SERVER_PROJECT), | ||
|
miguelg719 marked this conversation as resolved.
Resolved
|
||
| "--locked", | ||
| "stagehand-deepagents-mcp", | ||
| ], | ||
| "env": _allowlisted_env(), | ||
| } | ||
| } | ||
| ) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,64 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
|
|
||
| import dotenv | ||
| from _client import SERVER_NAME, create_stagehand_client | ||
| from deepagents import create_deep_agent | ||
| from langchain_mcp_adapters.tools import load_mcp_tools | ||
| from pydantic import BaseModel, ConfigDict, Field | ||
|
|
||
| dotenv.load_dotenv() | ||
|
|
||
| BROWSER_INSTRUCTIONS = """You control one persistent browser through exactly three tools: | ||
| - snapshot: inspect the active page and hydrate bracketed element IDs. | ||
| - run: provide either snapshot actions or JavaScript using the Playwright-shaped page API. | ||
| - screenshot: inspect the rendered page visually. | ||
|
|
||
| Use snapshot actions for simple interactions and run code for multi-step workflows. Snapshot IDs are | ||
| valid only for the latest snapshot of the active page. Snapshot again after navigation or stale IDs. | ||
| Do not launch another browser. | ||
| """ | ||
|
|
||
|
|
||
| class SportsEvent(BaseModel): | ||
| model_config = ConfigDict(extra="forbid") | ||
|
|
||
| name: str = Field(description="The name of the event") | ||
| sport: str = Field(description="The sport being played") | ||
| summary: str = Field(description="A concise summary of the event") | ||
| source_url: str = Field(description="The source URL for the event information") | ||
|
|
||
|
|
||
| class SportsSummary(BaseModel): | ||
| model_config = ConfigDict(extra="forbid") | ||
|
|
||
| events: list[SportsEvent] = Field(description="The day's main sporting events") | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| model = "openai:gpt-5.6-luna" | ||
| instruction = "Go find me a summary of all main sports events today" | ||
| response_format = SportsSummary | ||
|
|
||
| client = create_stagehand_client() | ||
|
|
||
| async with client.session(SERVER_NAME) as session: | ||
| tools = await load_mcp_tools(session) | ||
| agent = create_deep_agent( | ||
| model=model, | ||
| tools=tools, | ||
| system_prompt=BROWSER_INSTRUCTIONS, | ||
| response_format=response_format, | ||
| ) | ||
| result = await agent.ainvoke({"messages": [{"role": "user", "content": instruction}]}) | ||
|
|
||
| if response_format is not None: | ||
| response = result["structured_response"] | ||
| print(response.model_dump_json(indent=2)) | ||
| return | ||
| print(result["messages"][-1].content) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) |
71 changes: 71 additions & 0 deletions
71
packages/integrations/deepagents/examples/local/agents2.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,71 @@ | ||
| from __future__ import annotations | ||
|
|
||
| import asyncio | ||
|
|
||
| import dotenv | ||
| from _client import SERVER_NAME, create_stagehand_client | ||
| from deepagents import create_deep_agent | ||
| from langchain_mcp_adapters.tools import load_mcp_tools | ||
| from pydantic import BaseModel, ConfigDict, Field | ||
|
|
||
| dotenv.load_dotenv() | ||
|
|
||
| BROWSER_INSTRUCTIONS = """You control one persistent browser through exactly three tools: | ||
| - snapshot: inspect the active page and hydrate bracketed element IDs. | ||
| - run: provide either snapshot actions or JavaScript using the Playwright-shaped page API. | ||
| - screenshot: inspect the rendered page visually. | ||
|
|
||
| Navigate to the requested form, take a snapshot, identify the requested fields, and fill them with | ||
| the supplied mock data. Prefer one batched run actions call after taking the snapshot. Do not submit | ||
| the form unless explicitly asked. | ||
| """ | ||
|
|
||
|
|
||
| class FilledField(BaseModel): | ||
| model_config = ConfigDict(extra="forbid") | ||
|
|
||
| field: str = Field(description="The form field that was filled") | ||
| value: str = Field(description="The mock value entered into the field") | ||
|
|
||
|
|
||
| class FormFillResult(BaseModel): | ||
| model_config = ConfigDict(extra="forbid") | ||
|
|
||
| url: str = Field(description="The final page URL") | ||
| fields: list[FilledField] = Field(description="The fields successfully filled") | ||
| completed: bool = Field(description="Whether all requested fields were filled") | ||
|
|
||
|
|
||
| async def main() -> None: | ||
| model = "openai:gpt-5.6-luna" | ||
| instruction = """Navigate to https://file.1040.com/estimate/ and wait for it to load. Fill the | ||
| form with this mock data: | ||
| - age: 26 | ||
| - dependents under age 17: 1 | ||
| - wages / W-2 Box 1: 54321 | ||
| - federal tax / Box 2: 8345 | ||
| - state tax / Box 17: 2222 | ||
|
|
||
| and then every other field with data of your choice. | ||
|
|
||
| Do not submit the form. Return a summary of the fields you successfully filled.""" | ||
| response_format = FormFillResult | ||
|
|
||
| client = create_stagehand_client() | ||
|
|
||
| async with client.session(SERVER_NAME) as session: | ||
| tools = await load_mcp_tools(session) | ||
| agent = create_deep_agent( | ||
| model=model, | ||
| tools=tools, | ||
| system_prompt=BROWSER_INSTRUCTIONS, | ||
| response_format=response_format, | ||
| ) | ||
| result = await agent.ainvoke({"messages": [{"role": "user", "content": instruction}]}) | ||
| response: FormFillResult = result["structured_response"] | ||
|
|
||
| print(response.model_dump_json(indent=2)) | ||
|
|
||
|
|
||
| if __name__ == "__main__": | ||
| asyncio.run(main()) |
14 changes: 14 additions & 0 deletions
14
packages/integrations/deepagents/examples/local/pyproject.toml
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,14 @@ | ||
| [project] | ||
| name = "stagehand-deepagents-local-example" | ||
| version = "0.1.0" | ||
| requires-python = ">=3.11,<3.14" | ||
| dependencies = [ | ||
| "python-dotenv>=1.0", | ||
| "deepagents>=0.7,<1", | ||
| "langchain-mcp-adapters>=0.3,<1", | ||
| "langchain-openai>=1,<2", | ||
| "pydantic>=2,<3", | ||
|
miguelg719 marked this conversation as resolved.
Resolved
|
||
| ] | ||
|
|
||
| [tool.uv] | ||
| package = false | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.