跳到主要内容
import { Stagehand } from "@browserbasehq/stagehand";
import {
  StagehandActTool,
  StagehandNavigateTool,
} from "@langchain/community/agents/toolkits/stagehand";
import { ChatOpenAI } from "@langchain/openai";
import { createAgent } from "langchain";

async function main() {
  // Initialize Stagehand once and pass it to the tools
  const stagehand = new Stagehand({
    env: "LOCAL",
    enableCaching: true,
  });

  const actTool = new StagehandActTool(stagehand);
  const navigateTool = new StagehandNavigateTool(stagehand);

  // Initialize the model
  const model = new ChatOpenAI({
    modelName: "gpt-4",
    temperature: 0,
  });

  // Create the agent using langgraph
  const agent = createAgent({
    model,
    tools: [actTool, navigateTool],
  });

  // Execute the agent using streams
  const inputs1 = {
    messages: [
      {
        role: "user",
        content: "Navigate to https://www.google.com",
      },
    ],
  };

  const stream1 = await agent.stream(inputs1, {
    streamMode: "values",
  });

  for await (const { messages } of stream1) {
    const msg =
      messages && messages.length > 0
        ? messages[messages.length - 1]
        : undefined;
    if (msg?.content) {
      console.log(msg.content);
    } else if (msg?.tool_calls && msg.tool_calls.length > 0) {
      console.log(msg.tool_calls);
    } else {
      console.log(msg);
    }
  }

  const inputs2 = {
    messages: [
      {
        role: "user",
        content: "Search for 'OpenAI'",
      },
    ],
  };

  const stream2 = await agent.stream(inputs2, {
    streamMode: "values",
  });

  for await (const { messages } of stream2) {
    const msg =
      messages && messages.length > 0
        ? messages[messages.length - 1]
        : undefined;
    if (msg?.content) {
      console.log(msg.content);
    } else if (msg?.tool_calls && msg.tool_calls.length > 0) {
      console.log(msg.tool_calls);
    } else {
      console.log(msg);
    }
  }
}

main();

在 Browserbase 上使用 - 远程无头浏览器

如果您想远程运行浏览器,可以使用 Browserbase 平台。 您需要将 BROWSERBASE_API_KEY 环境变量设置为您的 Browserbase API 密钥。
export BROWSERBASE_API_KEY="your-browserbase-api-key"
您还需要将 BROWSERBASE_PROJECT_ID 设置为您的 Browserbase 项目 ID。
export BROWSERBASE_PROJECT_ID="your-browserbase-project-id"
然后使用 BROWSERBASE 环境初始化 Stagehand 实例。
const stagehand = new Stagehand({
  env: "BROWSERBASE",
});

以编程方式连接这些文档到 Claude、VSCode 等,通过 MCP 获取实时答案。
© . This site is unofficial and not affiliated with LangChain, Inc.