このクイックスタートでは、tree.py を作成して実行し、ディレクトリツリーを表示するコーディングアシスタントを構築します。エージェント、その会話、エージェントが作業するサンドボックスは、いずれも OpenAI が管理します。
前提条件
OpenAI Platform のプロジェクトでアプリケーション用の API キーを作成します。セッション操作用に api.agents.read と api.agents.write、モデルの推論用に api.responses.write の権限を付与し、次のようにキーを環境変数に設定します。
export OPENAI_API_KEY="your-api-key"
このキーはエージェントのサンドボックスの外で保管してください。サンドボックスの設定と制限については、OpenAI がホストするサンドボックスを参照してください。
リクエストには OpenAI-Beta: agents=v1 ヘッダーが必要です。OpenAI SDK はこのヘッダーを自動で追加します。cURL を使う場合は明示的に指定してください。
1. タスクの実行
使用する言語を選び、OpenAI SDK をインストールしてサンプルを実行します。SDK のサンプルでは beta.agents 名前空間を使用します。リクエストを送るとセッションが作成され、タスクが送信されます。進行状況はストリームで届きます。
Python SDK をインストールまたは更新します。
pip install --upgrade openaiサンプルを quickstart.py として保存します。
from openai import OpenAI
with OpenAI() as client:
with client.beta.agents.sessions.create(
agent={
"model": "gpt-6-astra",
"instructions": "Write clean code, run it, and report the actual output.",
},
environment={"type": "openai_hosted"},
input="Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",
stream=True,
).with_result_collection() as stream:
for event in stream:
print(event.to_json(indent=None), flush=True)
result = stream.get_final_result()
print(result.output_text)
session_id = result.session_idターミナルから実行します。
python quickstart.pyJavaScript SDK をインストールします。
npm install openaiサンプルを quickstart.mjs として保存します。
import OpenAI from "openai";
const client = new OpenAI();
const events = await client.beta.agents.sessions.create({
agent: {
model: "gpt-6-astra",
instructions: "Write clean code, run it, and report the actual output.",
},
environment: { type: "openai_hosted" },
input:
"Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",
stream: true,
});
events.withResultCollection();
try {
for await (const event of events) {
console.log(JSON.stringify(event));
}
const result = await events.finalResult();
console.log(result.output_text);
console.log("Session:", result.session_id);
} finally {
events.controller.abort();
}ターミナルから実行します。
node quickstart.mjs新しいディレクトリで Go モジュールを作成し、SDK をインストールします。
go mod init agents-quickstart
go get github.com/openai/openai-go/v3@latestサンプルを main.go として保存します。
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
ctx := context.Background()
client := openai.NewClient()
events := client.Beta.Agents.Sessions.NewStreaming(ctx, openai.BetaAgentSessionNewParams{
Agent: openai.BetaAgentSessionNewParamsAgent{
Model: openai.String("gpt-6-astra"),
Instructions: openai.String("Write clean code, run it, and report the actual output."),
},
Environment: openai.EnvironmentParamUnion{OfParamOpenAIHosted: &openai.EnvironmentParamOpenAIHosted{}},
Input: openai.BetaAgentSessionNewParamsInputUnion{
OfString: openai.String("Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output."),
},
})
defer events.Close()
openai.BetaAgentSessionWithResultCollection(events)
if events.Err() != nil {
panic(events.Err())
}
for events.Next() {
event := events.Current()
fmt.Println(event.RawJSON())
}
result, err := openai.BetaAgentSessionFinalResult(events)
if err != nil {
panic(err)
}
fmt.Println(result.OutputText())
sessionID := result.SessionID()
fmt.Println("Session:", sessionID)ターミナルから実行します。
go run .Maven プロジェクトの pom.xml に OpenAI SDK を追加します。
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.101.0</version>
</dependency>サンプルを src/main/java/AgentsApiSessionsStreamConversationExample.java として保存します。
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.core.ObjectMappers;
import com.openai.core.http.StreamResponse;
import com.openai.models.beta.agents.AgentSessionEvent;
import com.openai.models.beta.agents.EnvironmentParam;
import com.openai.models.beta.agents.sessions.SessionCreateParams;
import com.openai.services.beta.agents.AgentTurnResults;
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var json = ObjectMappers.jsonMapper();
try (StreamResponse<AgentSessionEvent> events =
client
.beta()
.agents()
.sessions()
.createStreaming(
SessionCreateParams.builder()
.agent(
SessionCreateParams.Agent.builder()
.model("gpt-6-astra")
.instructions("Write clean code, run it, and report the actual output.")
.build())
.environment(EnvironmentParam.OpenAIHosted.builder().build())
.input(
"Create tree.py, a Python script that prints a readable tree of the files"
+ " in the current directory. Run it and show me the output.")
.build())) {
AgentTurnResults.withResultCollection(events);
var iterator = events.stream().iterator();
while (iterator.hasNext()) {
var event = iterator.next();
System.out.println(json.writeValueAsString(event));
}
var result = AgentTurnResults.getFinalResult(events);
System.out.println(result.outputText());
String sessionId = result.sessionId();
System.out.println(sessionId);
}ターミナルから実行します。
mvn compile exec:java -Dexec.mainClass=AgentsApiSessionsStreamConversationExampleRuby SDK をインストールします。
gem install openaiサンプルを quickstart.rb として保存します。
require "openai"
require "json"
client = OpenAI::Client.new
events = client.beta.agents.sessions.create_streaming(
agent: {
model: "gpt-6-astra",
instructions: "Write clean code, run it, and report the actual output."
},
environment: { type: "openai_hosted" },
input: "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output."
)
begin
events.with_result_collection
events.each do |event|
puts JSON.generate(event.to_h)
end
result = events.get_final_result
puts result.output_text
session_id = result.session_id
puts "Session: #{session_id}"
ensure
events.close
endターミナルから実行します。
ruby quickstart.rbターミナルから cURL を実行します。SDK のインストールは不要です。
curl --no-buffer --fail-with-body https://api.openai.com/v1/agents/sessions \
-H "OpenAI-Beta: agents=v1" \
-H "Authorization: Bearer $OPENAI_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"agent": {
"model": "gpt-6-astra",
"instructions": "Write clean code, run it, and report the actual output."
},
"environment": { "type": "openai_hosted" },
"input": "Create tree.py, a Python script that prints a readable tree of the files in the current directory. Run it and show me the output.",
"stream": true
}'サンドボックスが不要な場合は、environment.type を none に設定します。これは、コマンドの実行やローカルファイルの操作を行わずに、質問に答えたり外部ツールを呼び出したりするエージェント向けの設定です。詳しい設定方法をご覧ください。
2. 進行状況の確認
ターミナルには、ストリームで届いたイベントが順次表示されます。SDK のサンプルは JSON を出力し、cURL は受信したイベントストリームをそのまま表示します。実行が成功すると、エージェントは tree.py を作成して実行し、そのファイルを含むディレクトリツリーを報告します。ほかに含まれるファイルや出力内容は、サンドボックスによって異なります。
イベント agent.session.turn.completed が表示されたら、エージェントが報告した実行結果を確認します。ターンが完了しても、すべてのツールが正常に実行されたとは限りません。イベント名の末尾が turn.failed、turn.cancelled、session.failed のいずれかであれば、失敗またはキャンセルを示します。agent.session.idle だけでは成功したかどうかは判断できません。ストリームが途中で切断された場合は、再試行する前にセッションとそこに保存された項目を取得します。
3. セッションの継続
イベントに含まれる session_id を保存します。この ID を使って追加の指示を送信します。たとえば、「tree.py にディレクトリツリーの深さの上限を指定するオプションを追加し、スクリプトを実行して出力を見せてください」と指示できます。最初のイベントを取りこぼさないよう、追加の指示を送信する前にイベントストリームを開いてください。
4. 後片付け
ほかのタスクにも使う場合はセッションを残しておきます。作業が終わったら、セッションを削除できます。削除する前に必要なファイルを保存してください。
サンプルの sess_123 を、保存したセッション ID に置き換えます。
# Replace the illustrative IDs and URLs below with your own resource values.
from openai import OpenAI
def delete_session(client: OpenAI, session_id: str):
return client.beta.agents.sessions.delete(session_id)
if __name__ == "__main__":
result = delete_session(OpenAI(), "sess_123")
print(result.to_json())// Replace the illustrative IDs and URLs below with your own resource values.
import OpenAI from "openai";
async function deleteSession(client, sessionId) {
return client.beta.agents.sessions.delete(sessionId);
}
const result = await deleteSession(new OpenAI(), "sess_123");
console.log(result);// Replace the illustrative IDs and URLs below with your own resource values.
package main
import (
"context"
"fmt"
"github.com/openai/openai-go/v3"
)
func deleteSession(ctx context.Context, client *openai.Client, sessionID string) (*openai.AgentSessionDeleted, error) {
return client.Beta.Agents.Sessions.Delete(ctx, sessionID)
}
func main() {
client := openai.NewClient()
result, err := deleteSession(context.Background(), &client, "sess_123")
if err != nil {
panic(err)
}
fmt.Println(result)
}// Replace the illustrative IDs and URLs below with your own resource values.
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.beta.agents.AgentSessionDeleted;
import com.openai.models.beta.agents.sessions.SessionDeleteParams;
public final class AgentsApiSessionsDeleteSessionExample {
public static AgentSessionDeleted deleteSession(OpenAIClient client, String sessionId) {
return client
.beta()
.agents()
.sessions()
.delete(SessionDeleteParams.builder().sessionId(sessionId).build());
}
public static void main(String[] args) {
var result = deleteSession(OpenAIOkHttpClient.fromEnv(), "sess_123");
System.out.println(result);
}
}# Replace the illustrative IDs and URLs below with your own resource values.
require "openai"
def delete_session(client, session_id)
client.beta.agents.sessions.delete(session_id)
end
puts delete_session(OpenAI::Client.new, "sess_123")curl -X DELETE "https://api.openai.com/v1/agents/sessions/sess_123" \
-H "OpenAI-Beta: agents=v1" \
-H "Authorization: Bearer $OPENAI_API_KEY"次のステップ
- サンプルアプリケーションをご覧ください。
- OpenAI がホストするサンドボックスの設定方法を確認してください。パッケージや入力ファイルの追加、ネットワークアクセスの制御、成果物のダウンロードができます。
- サブエージェントを使ったリリースノートの比較を試してください。
- ファイルと成果物の扱い方を確認してください。
- 環境を選ぶか、独自のサンドボックスを接続してください。