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,
) as events:
for event in events:
print(event.to_json(indent=None), flush=True)ターミナルから実行します。
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,
});
try {
for await (const event of events) {
console.log(JSON.stringify(event));
}
} 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()
if events.Err() != nil {
panic(events.Err())
}
for events.Next() {
event := events.Current()
fmt.Println(event.RawJSON())
}
if err := events.Err(); err != nil {
panic(err)
}ターミナルから実行します。
go run .Maven プロジェクトの pom.xml に OpenAI SDK を追加します。
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>4.58.0</version>
</dependency>サンプルを src/main/java/AgentsApiSessionsStreamConversationExample.java として保存します。
import com.fasterxml.jackson.databind.json.JsonMapper;
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
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;
OpenAIClient client = OpenAIOkHttpClient.fromEnv();
var json = new 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())) {
var iterator = events.stream().iterator();
while (iterator.hasNext()) {
var event = iterator.next();
System.out.println(json.writeValueAsString(event));
}
}ターミナルから実行します。
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.each do |event|
puts JSON.generate(event.to_h)
end
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 を保存します。これを使って、「Add a maximum-depth option to tree.py, run it, and show me the output.」といった追加の指示を送信します。初期のイベントを取りこぼさないように、追加の入力を送信する前にイベントストリームを開いてください。
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 がホストするサンドボックスを設定します。パッケージや入力ファイルの追加、ネットワークアクセスの制御、アーティファクトのダウンロードを行います。
- サブエージェントでリリースノートを比較します。
- ファイルとアーティファクトを操作します。
- 環境を選択するか、独自のサンドボックスを接続します。