0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Tavily Search による API経由での検索を JavaScript SDK で試す

Last updated at Posted at 2025-04-20

はじめに

とあるきっかけから、情報検索の API に関する技術情報をざっくり見ていました。

その中で見かけた以下の記事に書かれていた「Tavily」が気になったので、JavaScript SDK で試してみたという話の記事です。

●うさぎでもわかるLLM検索APIサービス比較 2025年最新版
 https://zenn.dev/taku_sid/articles/20250418_search_api_comparison

image.png

無料枠もあり、アカウント作成もメールアドレスだけで行えそうだったので Tavily を試しました。

Tavily のページ

Tavily の公式ページは以下となるようです。

https://tavily.com/
image.png

トップには「Connect Your LLM to the Web」「Empowering your AI applications with real-time, accurate search results tailored for LLMs and RAG.」という文言が書かれています。

さらに下へ進むと、特徴や Python・Node.js を使った場合の実装例などが掲載されています。

image.png

image.png

さらなる調査・お試し

さらに情報を見ていく

さらに情報を見ていきます。

登録・無料の枠

以下を見ると、クレジットカードの登録などなしでアカウントを作成でき、また毎月1000回分の無料枠があるようです。

image.png

自分もアカウント作成を試しましたが、メールアドレスを登録してパスワードを設定するだけ、という感じでした。

公式ドキュメント

公式ドキュメントは以下です。

●Welcome - Tavily Docs
 https://docs.tavily.com/welcome

image.png

クイックスタートは後で実際に試してみます。

Tavily の機能

さらに見ていくと、「Search」「Extract」の 2つの仕組みがあるようでした。
今回の自分の目的だと「Search」のほうになるかと思います。

●Tavily Search - Tavily Docs
 https://docs.tavily.com/documentation/api-reference/endpoint/search

●Tavily Extract - Tavily Docs
 https://docs.tavily.com/documentation/api-reference/endpoint/extract

プレイグラウンド

また、以下のプレイグラウンドが便利そうでした。

この後に出てくる SDK を使った API 利用で、特定のパラメータを設定したコードを GUI から作れるようです。

image.png

実際に試してみる

実際に JavaScript SDK を使って試してみます。
公式のクイックスタートを見てみると、以下が JavaScript用のもののようです。

●Quickstart - Tavily Docs
 https://docs.tavily.com/sdk/javascript/quick-start

image.png

Tavily の APIキー

この後の内容を進めるために、アカウント作成・APIキーの取得はすませておきます。

image.png

Tavily の SDK・サンプルコード

Tavily の JavaScript SDK とサンプルコードを確認してみます。
先ほどのクイックスタートのページや、以下の npm のページなどに掲載されています。

●@tavily/core - npm
 https://www.npmjs.com/package/@tavily/core

●tavily-ai/tavily-js: Official TypeScript/JavaScript library for Tavily.
 https://github.com/tavily-ai/tavily-js

「Search」に関して、具体的には以下の通りです。

const { tavily } = require("@tavily/core");

const tvly = tavily({ apiKey: "tvly-YOUR_API_KEY" });
const response = await tvly.search("Who is Leo Messi?");

console.log(response);

Tavily Search を試す

Tavily Search での検索をやってみます。

以下でパッケージをインストールします。

npm i @tavily/core

また、コードは以下のとおりです。

APIキーの読み込みには、Node.js の標準機能(process.loadEnvFile())を用いた環境変数用のファイル読みこみを使っています。また、受信した内容をテキストファイルに保存する処理も足しました。

import { tavily } from "@tavily/core";
import { writeFile } from "fs/promises";

process.loadEnvFile("./development.env");

const tvly = tavily({ apiKey: process.env.TAVILY_API_KEY });
const response = await tvly.search("生成AIの最新のモデルは?");

console.log(response);

const text =
  typeof response === "string" ? response : JSON.stringify(response, null, 2);

await writeFile("output.txt", text, "utf-8");
console.log("→ output.txt に書き込み完了");

環境変数で APIキーを扱うためのファイルとして、以下を用意します。

development.env
TAVILY_API_KEY=【TavilyのAPIキー】

そして nodeコマンドで上記のコマンドを実行したところ、以下の結果を得られました。

image.png

生成AI のまとめ・モデルの比較記事が取得できているようでした。

フォーマットに関して、公式ドキュメントのリファレンス内で「Response format」「Results」に書かれた内容と合致していました。

image.png

image.png

Tavily Search をさらに試す

もう少し試してみます。

公式ドキュメントのリファレンス内で Parameters の部分に書いてあるオプションをいくつかつけて試してみます。

image.png

image.png

具体的には、以下を使ってみることにしました。

  • searchDepth
    • string: "basic(デフォルト値)" または "advanced"
      • "advanced" 検索は、クエリに対して最も関連性の高い情報源やコンテンツの抜粋を取得し、"basic" 検索は各情報源から一般的なコンテンツを抜粋
  • topic
    • string: "general(デフォルト値)" または "news"
  • days
    • number: デフォルト値 7
      • 検索対象としてさかのぼる日数(topic が news の場合のみ利用可能)
  • maxResults
    • number: 0 〜 20(デフォルト値 5)
      • 得る結果の最大数

また、今回は使わないですが以下も気になりました。

  • includeAnswer
    • boolean or string: "basic"(または true)か "advanced" か "false(デフォルト値)"
      • 検索結果に基づいて LLM が生成したクエリへの回答を含めるかどうかで、「basic」回答は迅速だが詳細は少なめ、「advanced」のほうが回答がより詳しくなる
  • includeRawContent
    • boolean: デフォルト false
      • 各検索結果のクリーンアップ・パースした HTML のコンテンツを含めるかどうか
  • includeDomains
    • Array: デフォルト []
      • 検索結果に含めるドメインのリスト
  • excludeDomains
    • Array: デフォルト []
      • 検索結果から除外するドメインのリスト

上で書いていたプレイグラウンドも活用して、以下のコードを作成しました。
(※ プレイグラウンドで生成したコードだと、クエリーの部分を query="" と書くやり方が提示されましたが、エラーになったので query= の部分は除きました)

import { tavily } from "@tavily/core";
import { writeFile } from "fs/promises";

process.loadEnvFile("./development.env");

const tvly = tavily({ apiKey: process.env.TAVILY_API_KEY });
const response = await tvly.search(
  "OpenAI・Googleの生成AIの最新モデル・機能に関する日本語の記事",
  {
    topic: "news",
    searchDepth: "advanced",
    maxResults: 4,
    includeAnswer: "advanced",
    days: 10,
  }
);

console.log(response);

const text =
  typeof response === "string" ? response : JSON.stringify(response, null, 2);

await writeFile("output_n.txt", text, "utf-8");
console.log("→ output_n.txt に書き込み完了");

そして、以下の結果が得られました。

当初、クエリーで日本語の記事と指定しなかった場合は英語の記事が返ってきたので、日本語の記事という条件をつけてみたのですが、英語の記事が返ってきました(その場合は、ドメイン指定などを使ったほうが良いかも?)。

{
  "query": "OpenAI・Googleの生成AIの最新モデル・機能に関する日本語の記事",
  "responseTime": 10.52,
  "images": [],
  "results": [
    {
      "title": "OpenAI announces 'o3' and 'o4-mini,' which it calls 'the most advanced inference model in the company's history,' enabling 'Thinking with images' to be used to think using images as well as text - GIGAZINE",
      "url": "https://gigazine.net/gsc_news/en/20250417-openai-o3-o4-mini-released/",
      "content": "This article, originally posted in Japanese on 11:06 Apr 17, 2025, may contains some machine-translated parts.\nIf you would like to suggest a corrected translation, please click here.\nOpenAI has announced the release of new AI inference models, 'o3' and 'o4-mini'. OpenAI calls o3 'OpenAI's most advanced inference model ever', and claims that it outperforms previous models in benchmarks that measure mathematics, coding, reasoning, science, and visual understanding abilities. [...] 18](https://analytics.twitter.com/1/i/adsct?bci=4&dv=UTC%26en-US%26Google%20Inc.%26Linux%20x86_64%26255%26800%26600%264%2624%26800%26600%260%26na&eci=3&event=%7B%7D&event_id=fc951401-bea3-4195-8d71-3a506bcb66df&integration=gtm&p_id=Twitter&p_user_id=0&pl_id=f7512057-a6a6-4d98-b8ac-6f7c8a494636&tw_document_href=https%3A%2F%2Fgigazine.net%2Fgsc_news%2Fen%2F20250417-openai-o3-o4-mini-released%2F&tw_iframe_status=0&txn_id=nzcyp&type=javascript&version=2.3.31) [...] ![Image 17](https://t.co/1/i/adsct?bci=4&dv=UTC%26en-US%26Google%20Inc.%26Linux%20x86_64%26255%26800%26600%264%2624%26800%26600%260%26na&eci=3&event=%7B%7D&event_id=fc951401-bea3-4195-8d71-3a506bcb66df&integration=gtm&p_id=Twitter&p_user_id=0&pl_id=f7512057-a6a6-4d98-b8ac-6f7c8a494636&tw_document_href=https%3A%2F%2Fgigazine.net%2Fgsc_news%2Fen%2F20250417-openai-o3-o4-mini-released%2F&tw_iframe_status=0&txn_id=nzcyp&type=javascript&version=2.3.31)![Image",
      "rawContent": null,
      "score": 0.7311551,
      "publishedDate": "Thu, 17 Apr 2025 02:30:19 GMT"
    },
    {
      "title": "OpenAI’s new GPT-4.1 AI models focus on coding - TechCrunch",
      "url": "https://techcrunch.com/2025/04/14/openais-new-gpt-4-1-models-focus-on-coding/",
      "content": "Published Time: 2025-04-14T17:00:00+00:00\nOpenAI's new GPT-4.1 AI models focus on coding | TechCrunch\nOpenAI's new GPT-4.1 AI models focus on coding | TechCrunch\n===============\nTechCrunch Desktop Logo\nTechCrunch Mobile Logo\nLatest\nStartups\nVenture\nApple\nSecurity\nAI\nApps\nEvents\nPodcasts\nNewsletters\nSign In\nSearch\nSubmit\nSite Search Toggle\nMega Menu Toggle\nTopics\nLatest\nAI\nAmazon\nApps\nBiotech & Health\nClimate\nCloud Computing\nCommerce\nCrypto\nEnterprise\nEVs\nFintech\nFundraising\nGadgets\nGaming\nGoogle [...] OpenAI on Monday launched a new family of models called GPT-4.1. Yes, “4.1” — as if the company’s nomenclature wasn’t confusing enough already.\nThere’s GPT-4.1, GPT-4.1 mini, and GPT-4.1 nano, all of which OpenAI says “excel” at coding and instruction following. Available through OpenAI’s API but not ChatGPT, the multimodal models have a 1-million-token context window, meaning they can take in roughly 750,000 words in one go (longer than “War and Peace”). [...] GPT-4.1 arrives as OpenAI rivals like Google and Anthropic ratchet up efforts to build sophisticated programming models. Google’s recently released Gemini 2.5 Pro, which also has a 1-million-token context window, ranks highly on popular coding benchmarks. So do Anthropic’s Claude 3.7 Sonnet and Chinese AI startup DeepSeek’s upgraded V3.",
      "rawContent": null,
      "score": 0.58777803,
      "publishedDate": "Mon, 14 Apr 2025 17:00:00 GMT"
    },
    {
      "title": "OpenAI gets ready to launch GPT-4.1 - The Verge",
      "url": "https://www.theverge.com/news/646458/openai-gpt-4-1-ai-model",
      "content": "OpenAI gets ready to launch GPT-4.1\nOpenAI is getting ready to launch a collection of new models and features.\nOpenAI is getting ready to launch a collection of new models and features.\nby\nTom Warren\nOpenAI is getting ready to unveil a number of new AI models, sources familiar with the company’s plans tell The Verge. Among the new AI models will be a release of what I’m expecting will be branded GPT-4.1, which one source describes as a revamped version of OpenAI’s GPT-4o multimodal model.",
      "rawContent": null,
      "score": 0.5852203,
      "publishedDate": "Thu, 10 Apr 2025 15:45:32 GMT"
    },
    {
      "title": "OpenAI’s latest AI models have a new safeguard to prevent biorisks - TechCrunch",
      "url": "https://techcrunch.com/2025/04/16/openais-latest-ai-models-have-a-new-safeguard-to-prevent-biorisks/",
      "content": "Maxwell Zeff\n2:12 PM PDT · April 16, 2025\nOpenAI says that it deployed a new system to monitor its latest AI reasoning models, o3 and o4-mini, for prompts related to biological and chemical threats. The system aims to prevent the models from offering advice that could instruct someone on carrying out potentially harmful attacks, according to OpenAI’s safety report. [...] Published Time: 2025-04-16T21:12:28+00:00\nOpenAI's latest AI models have a new safeguard to prevent biorisks | TechCrunch\nOpenAI's latest AI models have a new safeguard to prevent biorisks | TechCrunch\n===============\nSkip to content\nTechCrunch Desktop Logo\nTechCrunch Mobile Logo\nLatest\nStartups\nVenture\nApple\nSecurity\nAI\nApps\nEvents\nPodcasts\nNewsletters\nSign In\nSearch\nSubmit\nSite Search Toggle\nMega Menu Toggle\nTopics\nLatest\nAI\nAmazon\nApps\nBiotech & Health\nClimate\nCloud Computing\nCommerce\nCrypto [...] Figma sent a cease-and-desist letter to Lovable over the term ‘Dev Mode’\nJulie Bort\nAnthropic forms a new team to grow its AWS business\nKyle Wiggers\nNotorious image board 4chan hacked and internal data leaked\nLorenzo Franceschi-Bicchierai\nAmanda Silberling\nNotion releases an AI-powered email client for Gmail\nRebecca Szkutak\nHertz says customers’ personal data and driver’s licenses stolen in data breach\nZack Whittaker\nLoading the next article\nError loading the next article\nX\nLinkedIn\nFacebook",
      "rawContent": null,
      "score": 0.5654673,
      "publishedDate": "Wed, 16 Apr 2025 21:12:28 GMT"
    }
  ],
  "answer": "OpenAIは最新の推論モデル「o3」と「o4-mini」をリリースしました。o3は「OpenAI史上最も高度な推論モデル」と呼ばれ、数学、コーディング、推論、科学、視覚理解能力を測定するベンチマークで以前のモデルを上回る性能を示しています。これらのモデルは「画像を使って考える」機能を持ち、テキストだけでなく画像も用いて思考できます。また、OpenAIはGPT-4.1、GPT-4.1 mini、GPT-4.1 nanoという新しいモデルファミリーも発表しました。これらはコーディングと指示に従う能力に優れており、100万トークンのコンテキストウィンドウを持ちます。さらに、OpenAIは最新のAI推論モデルに生物学的・化学的脅威に関連するプロンプトを監視する新システムを導入し、潜在的に有害な攻撃の指示を防ぐ安全対策を講じています。これらの開発は、GoogleやAnthropicなどのライバル企業が高度なプログラミングモデルの構築を加速させる中で行われています。"
}

おわりに

今回、Tavily Search による API経由での検索を、JavaScript SDK を使って試しました。少し試しただけですが、良い感じに情報を得られていたように思います。

今後、また別の内容で試してみたり、以下のベストプラクティスを見てみたりできればと思っています。

●Best Practices for Search - Tavily Docs
 https://docs.tavily.com/documentation/best-practices/best-practices-search

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?