AI SDK โดย Vercel เป็นไลบรารีโอเพนซอร์สที่มีประสิทธิภาพสำหรับ การสร้างแอปพลิเคชัน อินเทอร์เฟซผู้ใช้ และเอเจนต์ที่ทำงานด้วยระบบ AI ใน TypeScript
คู่มือนี้จะแนะนำวิธีสร้างแอปพลิเคชัน Node.js ด้วย TypeScript ที่ใช้ AI SDK เพื่อเชื่อมต่อกับ Gemini API ผ่านผู้ให้บริการ Generative AI ของ Google และทำการวิเคราะห์แนวโน้มตลาดโดยอัตโนมัติ แอปพลิเคชันขั้นสุดท้ายจะทำสิ่งต่อไปนี้
- ใช้ Gemini กับ Google Search เพื่อค้นคว้าเทรนด์ตลาดปัจจุบัน
- ดึงข้อมูลที่มีโครงสร้างจากการวิจัยเพื่อสร้างแผนภูมิ
- รวมการวิจัยและแผนภูมิไว้ในรายงาน HTML แบบมืออาชีพ แล้วบันทึกเป็น PDF
ข้อกำหนดเบื้องต้น
คุณจะต้องมีสิ่งต่อไปนี้จึงจะทำตามคู่มือนี้ได้
- คีย์ Gemini API คุณสร้างได้ฟรีใน Google AI Studio
- Node.js เวอร์ชัน 18 ขึ้นไป
- เครื่องมือจัดการแพ็กเกจ เช่น
npm
,pnpm
หรือyarn
ตั้งค่าแอปพลิเคชัน
ก่อนอื่นให้สร้างไดเรกทอรีใหม่สำหรับโปรเจ็กต์และเริ่มต้นใช้งาน
npm
mkdir market-trend-app
cd market-trend-app
npm init -y
pnpm
mkdir market-trend-app
cd market-trend-app
pnpm init
ไหมพรม
mkdir market-trend-app
cd market-trend-app
yarn init -y
ติดตั้งการอ้างอิง
จากนั้นติดตั้ง AI SDK, ผู้ให้บริการ Generative AI ของ Google และการอ้างอิงอื่นๆ ที่จำเป็น
npm
npm install ai @ai-sdk/google zod
npm install -D @types/node tsx typescript && npx tsc --init
หากต้องการป้องกันข้อผิดพลาดของคอมไพเลอร์ TypeScript ให้แสดงความคิดเห็นในบรรทัดต่อไปนี้ในtsconfig.json
ที่สร้างขึ้น
//"verbatimModuleSyntax": true,
pnpm
pnpm add ai @ai-sdk/google zod
pnpm add -D @types/node tsx typescript
ไหมพรม
yarn add ai @ai-sdk/google zod
yarn add -D @types/node tsx typescript && yarn tsc --init
หากต้องการป้องกันข้อผิดพลาดของคอมไพเลอร์ TypeScript ให้แสดงความคิดเห็นในบรรทัดต่อไปนี้ในtsconfig.json
ที่สร้างขึ้น
//"verbatimModuleSyntax": true,
แอปพลิเคชันนี้จะใช้แพ็กเกจของบุคคลที่สาม Puppeteer และ Chart.js ในการแสดงผลแผนภูมิและ สร้าง PDF ด้วย
npm
npm install puppeteer chart.js
npm install -D @types/chart.js
pnpm
pnpm add puppeteer chart.js
pnpm add -D @types/chart.js
ไหมพรม
yarn add puppeteer chart.js
yarn add -D @types/chart.js
แพ็กเกจ puppeteer
ต้องเรียกใช้สคริปต์เพื่อดาวน์โหลดเบราว์เซอร์ Chromium
โปรแกรมจัดการแพ็กเกจอาจขออนุมัติ ดังนั้นโปรดอนุมัติสคริปต์เมื่อได้รับแจ้ง
กำหนดค่าคีย์ API
ตั้งค่าGOOGLE_GENERATIVE_AI_API_KEY
ตัวแปรสภาพแวดล้อมด้วยคีย์ Gemini API
ผู้ให้บริการ Generative AI ของ Google จะค้นหาคีย์ API ในตัวแปรสภาพแวดล้อมนี้โดยอัตโนมัติ
MacOS/Linux
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
ตัวอย่างพื้นฐานนี้ใช้ Gemini 2.5 Flash และ generateText
เพื่อรับคำตอบอย่างง่ายจาก Gemini
import { google } from "@ai-sdk/google";
import { generateText } from "ai";
async function main() {
const { text } = await generateText({
model: google("gemini-2.5-flash"),
prompt: 'What is plant-based milk?',
});
console.log(text);
}
main().catch(console.error);
ก่อนเพิ่มความซับซ้อน ลองเรียกใช้สคริปต์นี้เพื่อยืนยันว่าได้กำหนดค่า สภาพแวดล้อมอย่างถูกต้องแล้ว เรียกใช้คำสั่งต่อไปนี้ในเทอร์มินัล
npm
npx tsc && node main.js
pnpm
pnpm tsx main.ts
ไหมพรม
yarn tsc && node main.js
หากตั้งค่าทุกอย่างถูกต้อง คุณจะเห็นคำตอบของ Gemini พิมพ์ลงใน คอนโซล
ทำการวิจัยตลาดด้วย Google Search
หากต้องการดูข้อมูลล่าสุด คุณสามารถเปิดใช้เครื่องมือ Google Search สำหรับ Gemini ได้ เมื่อเครื่องมือนี้ ทำงาน โมเดลจะค้นหาเว็บเพื่อตอบพรอมต์และแสดง แหล่งข้อมูลที่ใช้
แทนที่เนื้อหาของ 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-2.5-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);
ดึงข้อมูลแผนภูมิ
จากนั้นมาประมวลผลข้อความการวิจัยเพื่อดึงข้อมูลที่มีโครงสร้างที่เหมาะสำหรับ
แผนภูมิ ใช้ฟังก์ชัน generateObject
ของ AI SDK พร้อมกับzod
สคีมาเพื่อกำหนดโครงสร้างข้อมูลที่แน่นอน
นอกจากนี้ ให้สร้างฟังก์ชันช่วยเพื่อแปลงข้อมูลที่มีโครงสร้างนี้เป็น
การกำหนดค่าที่ Chart.js
เข้าใจได้
เพิ่มโค้ดต่อไปนี้ลงใน main.ts
โปรดสังเกตการนําเข้าใหม่และ "ขั้นตอนที่ 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-2.5-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-2.5-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
เพิ่มpuppeteer
การนำเข้าขั้นสุดท้ายและ "ขั้นตอนที่ 3" ลงในไฟล์ main.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-2.5-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);
เรียกใช้แอปพลิเคชัน
ตอนนี้คุณพร้อมที่จะเรียกใช้แอปพลิเคชันแล้ว เรียกใช้คำสั่งต่อไปนี้ใน เทอร์มินัล
npm
npx tsc && node main.js
pnpm
pnpm tsx main.ts
ไหมพรม
yarn tsc && node main.js
คุณจะเห็นการบันทึกในเทอร์มินัลขณะที่สคริปต์ดำเนินการแต่ละขั้นตอน
เมื่อเสร็จสมบูรณ์แล้ว ระบบจะสร้างไฟล์ report.pdf
ที่มีข้อมูลการวิเคราะห์ตลาดในไดเรกทอรีโปรเจ็กต์
ด้านล่างนี้ คุณจะเห็น 2 หน้าแรกของรายงาน PDF ตัวอย่าง
แหล่งข้อมูลเพิ่มเติม
ดูข้อมูลเพิ่มเติมเกี่ยวกับการสร้างด้วย Gemini และ AI SDK ได้จากแหล่งข้อมูลต่อไปนี้