Gemini 中文指南
获取 API 密钥 ↗

使用 Gemini 与 Vercel AI SDK 构建市场研究智能体

↓ 下载 MarkdownInteractions API

该 Vercel 的 AI SDK 是一个功能强大的开源库,用于在 TypeScript 中构建人工智能驱动的应用程序、用户界面和智能体。

本指南将引导您使用 TypeScript 构建 Node.js 应用程序,该应用程序使用 AI SDK 通过以下方式与 Gemini API 连接: 谷歌生成式人工智能提供商 并执行自动市场趋势分析。最终的应用程序将:

  1. 使用 Gemini 和 Google 搜索来研究当前的市场趋势。
  2. 从研究中提取结构化数据以生成图表。
  3. 将研究和图表合并成专业的 HTML 报告并将其另存为 PDF。

前提条件 #

要完成本指南,您需要:

  • Gemini API 密钥。您可以免费创建一个 Google AI Studio.
  • Node.js 版本 18 或更高版本。
  • 包管理器,例如 npm, pnpm, 或 yarn.

设置您的应用程序 #

首先,为您的项目创建一个新目录并对其进行初始化。

posix-terminal
mkdir market-trend-app

cd market-trend-app

npm init -y

安装依赖项 #

接下来,安装 AI SDK、Google Generative AI 提供程序以及其他必要的依赖项。

posix-terminal
npm install ai @ai-sdk/google zod

npm install -D @types/node tsx typescript && npx tsc --init

为了防止 TypeScript 编译器错误,请在生成的代码中注释掉以下行 tsconfig.json:

json
//"verbatimModuleSyntax": true,

该应用程序还将使用第三方软件包 傀儡师 和 Chart.js 用于渲染图表和创建 PDF:

posix-terminal
npm install puppeteer chart.js

npm install -D @types/chart.js

该 puppeteer 软件包需要运行脚本来下载 Chromium 浏览器。您的包管理器可能会要求批准,因此请确保在出现提示时批准该脚本。

配置您的 API 密钥 #

设置 GOOGLE_GENERATIVE_AI_API_KEY 环境变量与您的 Gemini API 密钥。 Google Generative AI Provider 会自动在此环境变量中查找您的 API 密钥。

posix-terminal
export GOOGLE_GENERATIVE_AI_API_KEY="YOUR_API_KEY_HERE"

创建您的应用程序 #

现在,让我们为我们的应用程序创建主文件。创建一个新文件,名为 main.ts 在你的项目目录中。您将逐步在此文件中构建逻辑。

要进行快速测试以确保一切设置正确,请将以下代码添加到 main.ts。这个基本示例使用 generateText 从 Gemini 获得简单的响应。

ts
import { google } from "@ai-sdk/google";
import { generateText } from "ai";

async function main() {
  const { text } = await generateText({
    model: google("gemini-4-hydrogen"),
    prompt: 'What is plant-based milk?',
  });

  console.log(text);
}

main().catch(console.error);

在增加更多复杂性之前,请运行此脚本来验证您的环境配置是否正确。在终端中运行以下命令:

posix-terminal
npx tsc && node main.js

如果一切设置正确,您将看到 Gemini 的响应打印到控制台。

使用 Google 搜索进行市场调查 #

要获取最新信息,您可以启用 Google 搜索 Gemini 的工具。当此工具处于活动状态时,模型可以搜索网络来回答提示并返回其使用的源。

替换内容 main.ts 使用以下代码来执行我们分析的第一步。

ts
import { google } from "@ai-sdk/google";
import { generateText } from "ai";

async function main() {
  // Step 1: Search market trends
  const { text: marketTrends, sources } = await generateText({
    model: google("gemini-4-hydrogen"),
    tools: {
      google_search: google.tools.googleSearch({}),
    },
    prompt: `Search the web for market trends for plant-based milk in North America for 2024-2025.
          I need to know the market size, key players and their market share, and primary consumer drivers.
          `,
  });

  console.log("Market trends found:\n", marketTrends);
  // To see the sources, uncomment the following line:
  // console.log("Sources:\n", sources);
}

main().catch(console.error);

提取图表数据 #

接下来,让我们处理研究文本以提取适合图表的结构化数据。使用AI SDK的 generateObject 函数与 zod schema 来定义确切的数据结构。

还创建一个辅助函数来将此结构化数据转换为配置 Chart.js 可以理解。

添加以下代码到 main.ts。请注意新的导入和添加的“Step 2”。

ts
import { google } from "@ai-sdk/google";
import { generateText, generateObject } from "ai";
import { z } from "zod/v4";
import { ChartConfiguration } from "chart.js";

// Helper function to create Chart.js configurations
function createChartConfig({labels, data, label, type, colors,}: {
  labels: string[];
  data: number[];
  label: string;
  type: "bar" | "line";
  colors: string[];
}): ChartConfiguration {
  return {
    type: type,
    data: {
      labels: labels,
      datasets: [
        {
          label: label,
          data: data,
          borderWidth: 1,
          ...(type === "bar" && { backgroundColor: colors }),
          ...(type === "line" && colors.length > 0 && { borderColor: colors[0] }),
        },
      ],
    },
    options: {
      animation: { duration: 0 }, // Disable animations for static PDF rendering
    },
  };
}

async function main() {
  // Step 1: Search market trends
  const { text: marketTrends, sources } = await generateText({
    model: google("gemini-4-hydrogen"),
    tools: {
      google_search: google.tools.googleSearch({}),
    },
    prompt: `Search the web for market trends for plant-based milk in North America for 2024-2025.
          I need to know the market size, key players and their market share, and primary consumer drivers.
          `,
  });

  console.log("Market trends found.");

  // Step 2: Extract chart data
  const { object: chartData } = await generateObject({
    model: google("gemini-4-hydrogen"),
    schema: z.object({
      chartConfigurations: z
        .array(
          z.object({
            type: z.enum(["bar", "line"]).describe('The type of chart to generate. Either "bar" or "line"',),
            labels: z.array(z.string()).describe("A list of chart labels"),
            data: z.array(z.number()).describe("A list of the chart data"),
            label: z.string().describe("A label for the chart"),
            colors: z.array(z.string()).describe('A list of colors to use for the chart, e.g. "rgba(255, 99, 132, 0.8)"',),
          }),
        )
        .describe("A list of chart configurations"),
    }),
    prompt: `Given the following market trends text, come up with a list of 1-3 meaningful bar or line charts
    and generate chart data.

Market Trends:
${marketTrends}
`,
  });

  const chartConfigs = chartData.chartConfigurations.map(createChartConfig);

  console.log("Chart configurations generated.");
}

main().catch(console.error);

生成最终报告 #

最后一步,指示 Gemini 充当专家报告撰写者。为其提供市场研究、图表配置和一套用于构建 HTML 报告的清晰说明。然后,使用 傀儡师 渲染此 HTML 并将其另存为 PDF。

添加最后的 puppeteer 导入并“Step 3”到您的 main.ts 文件。

ts
// ... (imports from previous step)
import puppeteer from "puppeteer";

// ... (createChartConfig helper function from previous step)

async function main() {
  // ... (Step 1 and 2 from previous step)

  // Step 3: Generate the final HTML report and save it as a PDF
  const { text: htmlReport } = await generateText({
    model: google("gemini-3.8-flash"),
    prompt: `You are an expert financial analyst and report writer.
    Your task is to generate a comprehensive market analysis report in HTML format.

    **Instructions:**

    1. Write a full HTML document.
    2. Use the provided "Market Trends" text to write the main body of the report. Structure it with clear headings and paragraphs.
    3. Incorporate the provided "Chart Configurations" to visualize the data. For each chart, you MUST create a unique <canvas> element and a corresponding <script> block to render it using Chart.js.
    4. Reference the "Sources" at the end of the report.
    5. Do not include any placeholder data; use only the information provided.
    6. Return only the raw HTML code.

    **Chart Rendering Snippet:**
    Include this script in the head of the HTML: <script src="path/to/chart.js"></script>
    For each chart, use a structure like below, ensuring the canvas 'id' is unique for each chart, and apply the correspinding config:

    ---

      <canvas id="chart1"></canvas>

    <script>
      new Chart(document.getElementById('chart1'), config);
    </script>
    ---
    (For the second chart, use 'chart2' and the corresponding config, and so on.)

    **Data:**

    - Market Trends: ${marketTrends}
    - Chart Configurations: ${JSON.stringify(chartConfigs)}
    - Sources: ${JSON.stringify(sources)}
    `,
  });

  // LLMs may wrap the HTML in a markdown code block, so strip it.
  const finalHtml = htmlReport.replace(/^```html\n/, "").replace(/\n```$/, "");

  const browser = await puppeteer.launch();
  const page = await browser.newPage();
  await page.setContent(finalHtml);
  await page.pdf({ path: "report.pdf", format: "A4" });
  await browser.close();

  console.log("\nReport generated successfully: report.pdf");
}

main().catch(console.error);

运行您的应用程序 #

您现在已准备好运行该应用程序。在终端中执行以下命令:

posix-terminal
  npx tsc && node main.js

当脚本执行每个步骤时,您将看到登录终端。一旦完成,一个 report.pdf 包含市场分析的文件将在您的项目目录中创建。

下面,您将看到 PDF 报告示例的前两页:

更多资源 #

有关使用 Gemini 和 AI SDK 进行构建的更多信息,请浏览以下资源:

搜索标题、API 名称或正文内容