0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

天気検索エージェントを実装してみた!

Posted at

はじめに

OpenAIで用意されているWeb検索ツール(web_search, web_search_preview)とは別にgpt-4o-search-previewを使用します。
天気を検索するエージェントを実装してみました。

実装

$ mkdir weather-search
$ cd weather-search
$ touch index.ts
$ touch .env
$ npm init -y
$ npm i openai zod commander
$ npm i -D @types/node typescript

.env

OPENAI_API_KEY=sk-*****

index.ts

import OpenAI from "openai";
import { Command } from "commander";
import z from "zod";
import { zodResponseFormat } from "openai/helpers/zod.mjs";

async function main() {
  const command = new Command();

  command
    .argument('<prompt>', 'Prompt (required)')
    .parse(process.argv);

  const WebSearchPreview = z.object({
    date: z.string().describe('日付'),
    weather: z.string().describe('天気'),
    temperature: z.object({
      max: z.number().describe('最高気温(摂氏)'),
      min: z.number().describe('最低気温(摂氏)'),
      current: z.number().describe('現在の気温')
    }),
    humidity: z.number().describe('現在の湿度(%)'),
    precipitation: z.number().describe('現在の降水確率(%)'),
    wind: z.object({
      direction: z.enum([
        "", "北北東", "北東", "東北東", "", "東南東",
        "南東", "南南東", "", "南南西", "南西", "西南西",
        "西", "西北西", "北西", "北北西"
      ]).describe('現在の風向き'),
      strength: z.number().describe('現在の風の強さ(m/s)')
    }),
    commentary: z.string().describe('解説'),
    link: z.string().describe('天気情報のURL')
  })

  const prompt = command.processedArgs[0];
  const instructions = [
    "あなたは天気を調査するエージェントです。",
    "正確に天気情報を取得してください。"
  ].join('\n');

  const client = new OpenAI();

  const completion = await client.chat.completions.create({
    model: "gpt-4o-search-preview",
    messages: [
      {
        "role": "system",
        "content": instructions
      },
      {
        "role": "user",
        "content": prompt
      }
    ],
    response_format: zodResponseFormat(WebSearchPreview, "web_search_preview")
  });

  const response = JSON.parse(completion.choices[0].message.content!);

  console.log("========== 検索結果 ==========");
  console.log(`${response.date} ${response.weather}`);
  console.log(`最高気温:${response.temperature.max}° 最低気温:${response.temperature.min}°`);
  console.log(`気温:${response.temperature.current}° 湿度:${response.humidity}%`);
  console.log(`降水確率:${response.precipitation}%`);
  console.log(`${response.wind.direction} ${response.wind.strength}m/s`);
  console.log("=== 解説 ===")
  console.log(response.commentary);
  console.log(`リンク: ${response.link}`);
}

main().catch(console.error);

実行コマンド

$ tsx --env-file .env index.ts 東京都渋谷区の17時の天気について教えてください。

実行結果

========== 検索結果 ==========
2025年9月7日 晴れ
最高気温:33° 最低気温:25°
気温:30° 湿度:61%
降水確率:0%
南 3m/s
=== 解説 ===
本日17時の東京都渋谷区の天気は晴れで、気温は30℃程度と予想されています。降水確率は0%で、風は南から3m/s程度吹く見込みです。
リンク: https://tenki.jp/forecast/3/16/4410/13113/1hour.html

さいごに

正確な情報がWeb検索から得られていないのでプロンプトや検索までの流れを変えて正確な情報が得られるようにしたいと思います。

0
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?