はじめに
この記事は、今まで Python版のみだった OpenAI Agents SDK の、TypeScript版を試してみた話です。
公式からは、以下の内容でポストがされていました。
また、以下のページの URL が書かれていました。
●OpenAI Agents SDK | OpenAI Agents SDK
https://openai.github.io/openai-agents-js/
上記ページは、日本語にも切り替えられるようです。
●OpenAI Agents SDK | OpenAI Agents SDK
https://openai.github.io/openai-agents-js/ja/
Python版のお試し
前に Python版の OpenAI Agents SDK は試したことがあり、以下の記事を書いていました。
●MCP を OpenAI Agents SDK で軽く試してみた時のメモ: OpenAI の SDK で エージェント + MCP - Qiita
https://qiita.com/youtoy/items/13f5038ef45ce6763926
●AIエージェント で MCP: OpenAI Agents SDK を使ったお試し【その2】 - Qiita
https://qiita.com/youtoy/items/5f4e477500c23c7dfd56
この時は MCP との組み合わせを試していました。
今回は Hello World を軽く試します。
Hello World を試す
それでは、以下の Hello World を試します。
下準備
下準備として、
npm i @openai/agents
また、OPENAI_API_KEY という名前の環境変数に、OpenAI の APIキーをセットしておきます。
お試し用のコード
とりあえず、サンプルにほんの少しだけ手を加えたもので試してみます。
import { Agent, run } from "@openai/agents";
const agent = new Agent({
name: "Assistant",
instructions: "You are a helpful assistant",
});
const result = await run(
agent,
"Write a haiku about recursion in programming in Japanese"
);
console.log(result.finalOutput);
出力結果は、以下のとおりです。
サンプルを試す
とりあえず Hello World を試せたので、以下にある他のサンプルも少し試します。
●openai/openai-agents-js: A lightweight, powerful framework for multi-agent workflows and voice agents
https://github.com/openai/openai-agents-js
Functions example を試してみます。
コード
先ほどの下準備をそのまま流用し、以下のコードを試します。元のサンプルを、少しだけ書きかえてみました。
import { z } from "zod";
import { Agent, run, tool } from "@openai/agents";
const getWeatherTool = tool({
name: "get_weather",
description: "Get the weather for a given city",
parameters: z.object({ city: z.string() }),
execute: async (input) => {
return `The weather in ${input.city} is sunny`;
},
});
const agent = new Agent({
name: "Data agent",
instructions: "You are a data agent",
tools: [getWeatherTool],
});
async function main() {
// ① 東京の天気の問い合わせ
const resultTokyo = await run(agent, "What is the weather in Tokyo?");
console.log("Tokyo:", resultTokyo.finalOutput);
// ② ニューヨークの天気の問い合わせ
const resultNY = await run(agent, "What is the weather in New York?");
console.log("New York:", resultNY.finalOutput);
}
main().catch(console.error);
試した結果は以下の通りで、想定通りの動作をしています。
おわりに
とりあえず、OpenAI Agents SDK の TypeScript版を軽く試してみました。
別途、以下のサンプルなどを元に、引き続きお試しができればと思います。
●openai-agents-js/examples at main · openai/openai-agents-js
https://github.com/openai/openai-agents-js/tree/main/examples
【追記】 次に試した内容
サンプルの 1つを元に、以下の内容を試しました!
●【Node.js】 OpenAI Agents SDK の TypeScript版で MCPサーバーのツールを使う - Qiita
https://qiita.com/youtoy/items/c2215b5bf2c903fc62bc