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?

ChatGPTのResponse APIでWeb検索をする基本形

Posted at

OpenAIの新しい responses API をGoogle Apps Script(GAS)から叩いて、Web検索を自動で行わせる処理を試しました。

Web検索を「勝手に」やってくれる

  • tool_choice: 'auto' を指定するだけで、必要に応じて検索してくれる
  • 車に関する質問を投げるだけで、最新の情報を反映した回答が返ってくる(例:ランドクルーザー250のリフトアップ費用など)
  • GASから簡単にリクエスト可能。OpenAI APIキーがあればすぐ使える

テストした質問

const messages = [
  {
    role: 'system',
    content: '整備士風に「〜っす」「〜っすね」で語尾を揃えてください。車種やパーツ情報はWebで検索して回答してください。'
  },
  {
    role: 'user',
    content: 'ランクル250をリフトアップするといくらかかりますか?'
  }
];

基本形(GASの場合)

function testCallWithMessages() {
  const messages = [
    {
      role: 'system',
      content: '整備士風に「〜っす」「〜っすね」で語尾を揃えてください。車種やパーツ情報はWebで検索して回答してください。'
    },
    {
      role: 'user',
      content: 'ランドクルーザー250の燃費は?'
    }
  ];
  const result = callOpenAIResponsesAPI(messages);
}

function callOpenAIResponsesAPI(messages) {

  const apiKey = PropertiesService.getScriptProperties().getProperty('OPENAI_API_KEY');

  const url = 'https://api.openai.com/v1/responses';
  const payload = {
    model: 'gpt-4o-mini',
    input: messages,
    tool_choice: 'auto',
    tools: [{ type: 'web_search' }],
    stream: false,
    store: true
  };

  const options = {
    method: 'post',
    contentType: 'application/json',
    headers: {
      Authorization: 'Bearer ' + apiKey
    },
    payload: JSON.stringify(payload),
    muteHttpExceptions: true
  };

  const response = UrlFetchApp.fetch(url, options);
  const responseText = response.getContentText();

  try {
    const parsed = JSON.parse(responseText);
    const messageItem = Array.isArray(parsed.output)
      ? parsed.output.find(item => item.type === 'message')
      : null;
    const outputText = messageItem?.content?.find(c => c.type === 'output_text')?.text
      || '❗ テキストが取れませんでした';
    Logger.log('📄 出力: %s', outputText);
    return parsed;
  } catch (e) {
    throw new Error('JSON解析失敗っす: ' + e.message);
  }
}

現状調べてわかっていること(OpenAI Response API 検証)

tool_choice と tools の動作仕様

  • tool_choice: 'auto' → メッセージの内容によって検索するか自動判定される
  • tool_choice: 'required' にすると、毎回ツールを実行する
    • tools を1つ(例: web_search)だけにすると、指定されたツールのみを強制的に実行

roleごとの挙動検証(Web検索あり)

検証内容

  • role: user に検索内容を入れる → 正しくWeb検索し、正しい回答
  • role: assistant に検索内容を入れる → Web検索していそうだが、回答が誤っている

systemメッセージのルール適用について

設定

  • role: system に「回答に必ず絵文字を含める」と記載
  • model:gpt-4o-mini

挙動

  • Web検索を伴う質問 → 絵文字が出ない
  • Web検索を伴わない質問 → 絵文字が正しく含まれる

考察

  • 検索結果を重視する際、systemルールが弱まる(無視される?)

現状のまとめ

口調などはweb検索をしても回答で反映されるが、絵文字は反映されない。
modelを変更しても回答は変わらなかった。

絵文字を必ず入れたい場合はひと手間必要そう。
例えば
web検索専用のメソッドを用意する。
上記の検索結果をweb検索をしないメソッドtool_choice:noneに渡してrole:systemで絵文字を指定する。

これで一応できる気がしているが、必ずweb検索をしてしまう。= 検索の金額が毎回発生。

web検索をするかしないかを判断するなにかフラグがあればよいのかなと思ってしまうが見当たらない。

現状はここまで。

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?