Gemini와 Vercel의 AI SDK로 시장 조사 에이전트 만들기

Gemini와 Vercel의 AI SDK로 시장 조사 에이전트 만들기

AI SDK by Vercel은 TypeScript로 AI 기반 애플리케이션·UI·에이전트를 빌드하는 강력한 오픈소스 라이브러리예요.

이 가이드는 AI SDK가 Google Generative AI Provider로 Gemini API와 연결하는 TypeScript 기반 Node.js 애플리케이션을 만들고 자동 시장 추세 분석을 수행하는 방법을 안내해요. 최종 앱은:

  1. Gemini와 Google Search로 현재 시장 추세를 조사해요.
  2. 조사에서 구조화된 데이터를 추출해 차트를 생성해요.
  3. 조사와 차트를 전문적인 HTML 보고서로 결합해 PDF로 저장해요.

출처: 원문

본문

전제 조건

이 가이드를 완료하려면 다음이 필요해요.

  • Gemini API 키. Google AI Studio에서 무료로 생성할 수 있어요.
  • Node.js 18 이상.
  • npm, pnpm, yarn 같은 패키지 매니저.

참고: 이 가이드는 Node.js 환경에 중점을 두지만, AI SDK는 Next.js 같은 브라우저 기반 프레임워크와도 완전히 호환돼요.

애플리케이션 설정

먼저 프로젝트용 새 디렉토리를 만들고 초기화해요.

mkdir market-trend-app
cd market-trend-app
npm init -y

(pnpm init 또는 yarn init -y도 가능.)

의존성 설치

다음으로 AI SDK, Google Generative AI provider, 기타 필요한 의존성을 설치해요.

npm install ai @ai-sdk/google zod
npm install -D @types/node tsx typescript && npx tsc --init

TypeScript 컴파일러 오류를 막으려면 생성된 tsconfig.json에서 다음 줄을 주석 처리하세요.

//"verbatimModuleSyntax": true,

이 앱은 차트 렌더링과 PDF 생성을 위해 서드파티 패키지 Puppeteer와 Chart.js도 사용해요.

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 키를 자동으로 찾아요.

export GOOGLE_GENERATIVE_AI_API_KEY="YOUR_API_KEY_HERE"

(Powershell: setx GOOGLE_GENERATIVE_AI_API_KEY "YOUR_API_KEY_HERE")

애플리케이션 만들기

이제 앱의 메인 파일을 만들게요. 프로젝트 디렉토리에 main.ts라는 새 파일을 만들어요. 이 파일에 로직을 단계별로 구성할 거예요.

빠른 테스트로 모든 것이 올바르게 설정됐는지 확인하려면 main.ts에 다음 코드를 추가해요. 이 기본 예제는 generateText를 사용해 Gemini에서 간단한 응답을 받아요.

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

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

  console.log(text);
}

main().catch(console.error);

복잡성을 더하기 전에 이 스크립트를 실행해 환경이 올바르게 구성됐는지 확인하세요. 터미널에서 다음 명령을 실행해요.

npx tsc && node main.js

(pnpm: pnpm tsx main.ts, yarn: yarn tsc && node main.js)

모든 것이 올바르게 설정됐다면 Gemini의 응답이 콘솔에 출력되는 걸 볼 수 있어요.

Google Search로 시장 조사 수행하기

최신 정보를 얻으려면 Gemini의 Google Search 도구를 활성화할 수 있어요. 이 도구가 활성화되면 모델이 웹을 검색해 프롬프트에 답하고 사용한 출처를 반환해요.

분석의 첫 단계를 수행하려면 main.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-3.8-flash"),
    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 스키마와 함께 사용해 정확한 데이터 구조를 정의해요.

또한 이 구조화된 데이터를 Chart.js가 이해할 수 있는 구성으로 변환하는 헬퍼 함수도 만들어요.

main.ts에 다음 코드를 추가해요. 새 import와 추가된 "Step 2"에 주목하세요.

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-3.8-flash"),
    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-3.8-flash"),
    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 보고서 작성에 대한 명확한 지침을 제공해요. 그런 다음 Puppeteer로 이 HTML을 렌더링해 PDF로 저장해요.

main.ts 파일에 마지막 puppeteer import와 "Step 3"을 추가해요.

// ... (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="https://cdn.jsdelivr.net/npm/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:

    ---
    <div style="width: 800px; height: 600px;">
      <canvas id="chart1"></canvas>
    </div>
    <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);

애플리케이션 실행

이제 애플리케이션을 실행할 준비가 됐어요. 터미널에서 다음 명령을 실행하세요.

npx tsc && node main.js

(pnpm: pnpm tsx main.ts, yarn: yarn tsc && node main.js)

스크립트가 각 단계를 실행하면서 터미널에서 로깅을 볼 수 있어요. 완료되면 프로젝트 디렉토리에 시장 분석을 담은 report.pdf 파일이 생성돼요.

아래에서 예제 PDF 보고서의 처음 두 페이지를 볼 수 있어요.

추가 리소스

Gemini와 AI SDK로 빌드하는 방법에 대한 더 많은 정보는 다음 리소스를 살펴보세요.

더 알아보기 (Learn more)