ข้ามไปยังเนื้อหา
TH
รับคีย์ API
เรียกดูเอกสาร

คู่มือ

เพิ่มการค้นหาในแอปพลิเคชัน

สร้างรูปแบบการค้นหาการทํางานเก็บ API กุญแจบนแบ็คเอนต์ของคุณ และใช้ใหม่ในฟังก์ชันการค้นหาเดียวกัน ในเครื่องมือตัวแทน

ในหน้านี้

สิ่งที่คุณจะสร้าง

รูปแบบการค้นหาท้องถิ่นที่มีการจัดอันดับลิงก์ ชิ้นส่วนและการใช้เครดิต ต้องการ Node.js 22+ กุญแจกับ... google_search ได้รับอนุญาตและเครดิตที่มีอยู่ ไม่ npm ต้องการแพกเกจครับ ส่วนของตัวแทนทางเลือก จะทําการเรียกทํางานแบ็คเอนต์เดียวกันใหม่อีกครั้ง

บันทึกในสื่อค้นหาแบบ Flashdataวัตถุประสงค์
search.mjsเรียก FlashData จากแบ็คเอนต์ของเอกสาร แบ่งปันด้วยเครื่องมือฟอร์มและตัวแทน
server.mjsให้บริการหน้าเว็บท้องถิ่นและ GET /search จุดปลาย
index.htmlแสดงผลแหล่ง, ไม่แสดงผลลัพธ์และข้อผิดพลาด
Bash หรือ PowerShell สร้างโครงการ
node --version
mkdir flashdata-search-demo
cd flashdata-search-demo

ตั้งค่าของคุณ API กุญแจ

ใช้อีกครั้ง FLASHDATA_API_KEY ถ้าตั้งค่าเรียบร้อยแล้ว ไม่เช่นนั้นจะใช้ตัวกระตุ้นที่ซ่อนอยู่ด้านล่างในเทอร์มินัลที่จะเรียกใช้รหัส ตัวแทนสามารถบรรจุตัวแปรเดียวกัน จากร้านลับได้

ตั้งค่ากุญแจ
# Bash: paste the key into a hidden prompt, not into this command.
read -r -s -p "FlashData API key: " FLASHDATA_API_KEY
printf '\n'
export FLASHDATA_API_KEY

1. สร้างฟังก์ชันการค้นหา

บันทึกเป็น search.mjs ในโฟลเดอร์โครงการของคุณ รับสายหนึ่งกลับมาถึง 5 เว็บผลลัพธ์ URLs และการใช้งานที่แท้จริง ฟังก์ชันตรวจความถูกต้องของข้อมูลเข้า, รักษาลําดับผลลัพธ์ เอา URLs ที่ซ้ํากันออก และเก็บกุญแจไว้จากข้อมูลที่ส่งกลับมา เดอะ 500- การจํากัดคาร์เมนเตอร์คือตัวเลือกของแอพ

search.mjs
// search.mjs — server only; Node.js 22+
export async function searchWeb(query) {
  if (typeof query !== "string" || !query.trim() || query.length > 500) {
    throw Object.assign(new Error("Enter a query of 1–500 characters."), { status: 400 });
  }
  const apiKey = process.env.FLASHDATA_API_KEY;
  if (!apiKey) throw new Error("Set FLASHDATA_API_KEY on the server.");
  let response;
  try {
    response = await fetch("https://data.flashdata.dev/v1/queries/realtime", {
      method: "POST", redirect: "error", signal: AbortSignal.timeout(70000),
      headers: { "X-API-Key": apiKey, "Content-Type": "application/json" },
      body: JSON.stringify({ source: "google_search", query: query.trim(),
        params: { num: 5, gl: "us", hl: "en" } }),
    });
  } catch {
    throw new Error("Search outcome unknown. Check FlashData History before retrying.");
  }
  if (!response.ok) {
    throw Object.assign(new Error("Search failed: HTTP " + response.status), {
      status: response.status, retryAfter: response.headers.get("retry-after"),
    });
  }
  const data = await response.json();
  if (data.status !== "done" || !Array.isArray(data.results)) {
    throw new Error("Search did not finish. Check FlashData History.");
  }
  const seen = new Set();
  const sources = [];
  for (const [index, item] of (data.results[0]?.organic ?? []).entries()) {
    let url;
    try { url = new URL(item.link); } catch { continue; }
    if (!["https:", "http:"].includes(url.protocol) || seen.has(item.link)) continue;
    seen.add(item.link);
    sources.push({ rank: item.position ?? index + 1, title: item.title ?? item.link,
      url: item.link, snippet: item.snippet ?? "" });
  }
  return { query: query.trim(), sources, usage: data.usage,
    retrievedAt: new Date().toISOString() };
}

2. เพิ่มแบ็คเอนต์ภายใน

บันทึกเป็น server.mjs ข้าง search.mjs. GET /searchQ=. โทรหาฟังก์ชัน. GET / ทําหน้าที่ในรูปแบบที่คุณจะสร้างต่อไป เครื่องแม่ข่ายจะฟังเฉพาะเมื่อ 127.0.0.1

server.mjs
// server.mjs — local demo; keep your existing app's authentication in production.
import { createServer } from "node:http";
import { readFile } from "node:fs/promises";
import { searchWeb } from "./search.mjs";

createServer(async (req, res) => {
  const url = new URL(req.url, "http://127.0.0.1:8787");
  res.setHeader("Cache-Control", "no-store");
  try {
    if (req.method === "GET" && url.pathname === "/") {
      const html = await readFile(new URL("./index.html", import.meta.url));
      res.writeHead(200, { "Content-Type": "text/html; charset=utf-8" });
      return res.end(html);
    }
    if (req.method !== "GET" || url.pathname !== "/search") {
      res.writeHead(404); return res.end("Not found");
    }
    const result = await searchWeb(url.searchParams.get("q"));
    res.writeHead(200, { "Content-Type": "application/json" });
    res.end(JSON.stringify(result));
  } catch (error) {
    if (error.retryAfter) res.setHeader("Retry-After", error.retryAfter);
    res.writeHead(error.status ?? 502, { "Content-Type": "application/json" });
    res.end(JSON.stringify({ error: error.message }));
  }
}).listen(8787, "127.0.0.1", () => console.log("Open http://127.0.0.1:8787"));

3. แสดงผลในโปรแกรมของคุณ

บันทึกเป็น index.html ในโฟลเดอร์เดียวกัน ฟอร์มนี้ใช้เก็บการโหลด, ผลที่ว่างอยู่และข้อผิดพลาด มันเรียกแบ็คเอนต์ของคุณ และแทรกชิ้นส่วนเป็นข้อความ ดังนั้นไม่ API กุญแจหรือภายนอก HTML ถึงหน้านั้น

index.html
<!doctype html>
<html lang="en">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Web search</title>
<h1>Search the web</h1>
<form id="search">
  <label>Query <input name="q" required maxlength="500" value="battery recycling research"></label>
  <button>Search</button>
</form>
<p id="status" role="status"></p>
<ol id="results"></ol>
<script type="module">
const form = document.querySelector("#search");
const status = document.querySelector("#status");
const results = document.querySelector("#results");
form.addEventListener("submit", async (event) => {
  event.preventDefault();
  form.querySelector("button").disabled = true;
  results.replaceChildren(); status.textContent = "Searching…";
  try {
    const q = new FormData(form).get("q");
    const response = await fetch("/search?q=" + encodeURIComponent(q));
    const data = await response.json();
    if (!response.ok) {
      const retryAfter = response.headers.get("Retry-After");
      throw new Error(data.error + (retryAfter ? " · Retry-After: " + retryAfter : ""));
    }
    for (const source of data.sources) {
      const li = document.createElement("li");
      const link = document.createElement("a");
      link.href = source.url; link.textContent = source.title;
      const excerpt = document.createElement("p");
      excerpt.textContent = source.snippet;
      li.append(link, excerpt); results.append(li);
    }
    const credits = data.usage?.credits ?? "not reported";
    status.textContent = (data.sources.length
      ? data.sources.length + (data.sources.length === 1 ? " source" : " sources")
      : "No matching pages. Try a broader query.") + " · Credits used: " + credits;
  } catch (error) { status.textContent = error.message; }
  finally { form.querySelector("button").disabled = false; }
});
</script>
</html>

4. สืบค้นครั้งแรกของคุณ

ประมวลผลจาก iPadata-Demo ในเทอร์มินัลที่คุณตั้งค่ากุญแจ เปิด URL แล้วคลิกที่การค้นหาหนึ่งครั้ง การส่งแต่ละฉบับจะทําให้การสอบถามที่จ่ายได้ การเปิดหน้าหรือแก้ไขข้อมูลเข้าไม่ส่งผลอะไร หยุดเซิร์ฟเวอร์ภายในด้วย Ctrl+C เมื่อเสร็จสิ้นแล้ว

  1. ใส่ หัว เรื่อง ที่ เฉพาะ เช่น อัตรา การ กู้ แบตเตอรี่.
  2. คาดว่าจะมีชื่อเชื่อมโยง, ชิ้นส่วนและหน่วยกิตกลับมาใน usage.credits ผลลัพธ์ต่าง ๆ; ศูนย์แหล่งเป็นการค้นหาที่เสร็จสมบูรณ์แล้ว
ใน Fashadata- Directory-Demo
node server.mjs
เปิดในเบราว์เซอร์ของคุณ
http://127.0.0.1:8787

ผลที่โปรแกรมของคุณได้รับ

รูปร่างที่มีชีวิตชีวา; URLs และการใช้ด้านล่างนี้เป็นการเปรียบเทียบ การค้นหาจะคืนค่ากลับมาเป็นชิ้นส่วนและที่อยู่เชื่อมโยง ใช้โปรแกรมอ่านหน้า เมื่อคุณสมบัติของคุณต้องการข้อความเต็มหน้า

GET /search?q=...
{
  "query": "battery recycling research",
  "sources": [
    {
      "rank": 1,
      "title": "Example source",
      "url": "https://example.org/research",
      "snippet": "A returned search excerpt."
    }
  ],
  "usage": {
    "credits": 0.02
  },
  "retrievedAt": "2026-11-04T00:00:00.000Z"
}

ใช้การค้นหาในเครื่องมือตัวแทน

ตัวเลือก: บันทึก search-tool.mjs ข้าง search.mjs. นักวิ่งยอมรับเฉพาะ search_web และคําร้องขอ สร้างนักวิ่งหนึ่งตัวต่องาน และเก็บมันข้ามเส้นทางของภารกิจนั้น maxCalls การพยายามจํากัดการค้นหา รวมถึงความพยายามที่ล้มเหลวด้วย มัน ไม่ ได้ กําหนด จํากัด การ ใช้ จ่าย เครดิต.

flashdata-search-demo/search-tool.mjs
// search-tool.mjs — one runner per task, reused across its model turns.
import { searchWeb } from "./search.mjs";

export const searchTool = {
  name: "search_web",
  description: "Find ranked web URLs and snippets for a focused query.",
  inputSchema: {
    type: "object", additionalProperties: false,
    properties: { query: { type: "string", minLength: 1, maxLength: 500 } },
    required: ["query"],
  },
};
export function createSearchToolRunner({ maxCalls = 2 } = {}) {
  if (!Number.isSafeInteger(maxCalls) || maxCalls < 1) {
    throw new Error("maxCalls must be a positive integer.");
  }
  let attempts = 0;
  return async function runTool(name, args) {
    if (name !== searchTool.name) throw new Error("Unknown tool: " + name);
    if (!args || typeof args !== "object" || Array.isArray(args) ||
        Object.keys(args).some(key => key !== "query") ||
        typeof args.query !== "string" || !args.query.trim() || args.query.length > 500) {
      throw new Error("Expected only query: a string of 1–500 characters.");
    }
    if (attempts >= maxCalls) throw new Error("Search call limit reached for this task.");
    attempts++; // Reserve before awaiting; a failed attempt still counts.
    return searchWeb(args.query);
  };
}

ลองเครื่องมือโดยตรง

บันทึก tool-demo.mjs ใน Fashdata-Demo แล้วเรียกคําสั่งด้านล่างนี้จากโฟลเดอร์ดังกล่าวด้วยตัวเดียวกัน API กุญแจ การตรวจสอบทางเลือกนี้ทําให้อีกหนึ่ง FlashData สอบถามโดยไม่โทรหานางแบบ คาด JSON ด้วยการสอบถาม แหล่งที่มา การใช้และการใช้ retrievedAt-ผลเดียวกับรูปร่าง

flashdata-search-demo/tool-demo.mjs
// tool-demo.mjs — one direct tool call; no model-provider dependency.
import { createSearchToolRunner, searchTool } from "./search-tool.mjs";

if (process.argv.length !== 3) {
  console.error('Usage: node tool-demo.mjs "your search query"');
  process.exit(1);
}
const runTool = createSearchToolRunner({ maxCalls: 1 });
const result = await runTool(searchTool.name, { query: process.argv[2] });
console.log(JSON.stringify(result, null, 2));
ประมวลผลหนึ่งครั้งจาก fashdata-Demo
node tool-demo.mjs "battery recycling research"

เชื่อมต่อมันกับโมเดลของคุณ

การสาธิตฟังก์ชันเครื่องมือ กรอบของคุณจะให้การเชื่อมต่อแบบและวนข้อความ ค้นหาจากที่อยู่เชื่อมโยงและส่วน ต่าง ๆ ของเอกสาร ที่ได้เลือกไว้ ก่อนที่จะใช้เนื้อหาเต็มในการตอบ สําหรับงานที่จําหน่ายหรือทําต่อ ให้พยายามนับและให้ผลกับงาน ID

  1. ลงทะเบียน searchTool.nameคําบรรยายและ inputSchema โดยใช้รูปแบบการป้องกันเครื่องมือของคุณ เก็บมันไว้ API กุญแจในสภาพแวดล้อมของแบ็คเอนต์
  2. เมื่อเริ่มงาน ให้เรียก createSearchToolRunner({ maxCalls: 2 }). สําหรับการเรียกเครื่องมือแต่ละ, วิเคราะห์ JSON อาร์กิวเมนต์และส่งชื่อ และ script วัตถุให้กับนักวิ่งเดียวกัน ปฏิเสธค่าใช้งานไม่ได้ JSON ก่อนส่ง
  3. คืน JSON ผลของโมเดลเป็นเครื่องมือผลลัพธ์ด้วยการเรียกเดิม ID. รักษา sources[].url เพื่อการอ้างอิง หากการประมวลผลล้มเหลว หรือไปถึงจุดเกินขีดจํากัด ให้กลับค่าผิดพลาด; อย่าสร้างตัวดําเนินการใหม่เพื่อลองอีกครั้ง

การจัดการความล้มเหลวและส่งมัน

สําหรับการใช้งานย้าย /search อยู่เบื้องหลังการเซ็นในใบสมัครของคุณ เก็บมันไว้ API กุญแจในการปรับแต่งของแม่ข่าย จะยังคงการใช้งานกับการร้องขอ และแปลงเนื้อหาภายนอกเป็นข้อความ Realtime เหมาะกับรูปแบบโต้ตอบนี้; ใช้ Asinc สําหรับการทํางานเบื้องหลัง

สถานการณ์พฤติกรรมของ App
ERR_MODULE_NOT_FOUND / ENOENTเก็บแฟ้มทั้งหมดไว้ในโปรแกรม flashdata-Demo และประมวลผลจากโฟลเดอร์นั้น บันทึก index.html ก่อนจะเปิดหน้านี้
EADDRINUSEมีพอร์ต 8787 ไม่ว่าง หยุดกระบวนการสาธิตก่อนหน้านี้ของคุณก่อนที่จะเริ่มใหม่
จํากัดการเรียกค้นหาภารกิจที่ใช้ความพยายามที่อนุญาต จบ ด้วย หลัก ฐาน ที่ รวบ รวม มา หรือ รายงาน ข้อ จํากัด นั้น; การ สร้าง นัก วิ่ง คน ใหม่ จะ ทํา ให้ จํานวน ของ ผู้ นับ กลับ มา อีก.
ผลการค้นหา:แสดงสถานะว่าง และให้ผู้ใช้ทําการปรับปรุงคําค้น อย่าพยายามอัตโนมัติ
401 / 403 / 402โปรดตรวจสอบกุญแจของแม่ข่าย google_search อนุมัติและบัญชีเครดิต
429รอ Retry-After เมื่อมีการใช้งาน; จํากัดการร้องขอต่อผู้ใช้ก่อนจะเรียก FlashData.
หมดเวลา/ เครือข่ายผิดพลาดแสดงผลลัพธ์ที่ไม่แน่นอน Inspect History ก่อนที่จะส่งคําค้นที่ต้องจ่ายเหมือนกันอีกครั้ง