Agents API 빠른 시작
Agents API 빠른 시작 (Agents API quickstart)
tree.py를 작성하고 실행해서 디렉터리 트리를 보여 주는 코딩 어시스턴트를 만들어 볼게요. OpenAI가 에이전트, 대화, 그리고 에이전트가 작업하는 샌드박스를 관리해요.
출처: 문서
본문
전제 조건 (Prerequisites)
OpenAI 플랫폼 프로젝트에서 애플리케이션 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. 과제 실행하기 (Run a task)
언어를 선택하고, OpenAI SDK를 설치한 뒤 예시를 실행해 보세요. SDK 예시는 beta.agents 네임스페이스를 사용해요. 이 요청은 세션을 만들고, 과제를 제출하고, 진행 상황을 스트리밍해요.
Python
Python SDK를 설치하거나 업데이트하세요:
pip install --upgrade openai
예시를 quickstart.py로 저장하세요:
tree.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.py
JavaScript
JavaScript SDK를 설치하세요:
npm install openai
예시를 quickstart.mjs로 저장하세요:
tree.py 만들고 실행하기
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
새 디렉터리에서 Go 모듈을 만들고 SDK를 설치하세요:
go mod init agents-quickstart
go get github.com/openai/openai-go/v3@latest
예시를 main.go로 저장하세요:
tree.py 만들고 실행하기
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 .
Java
Maven 프로젝트의 pom.xml에 OpenAI SDK를 추가하세요:
<dependency>
<groupId>com.openai</groupId>
<artifactId>openai-java</artifactId>
<version>${apiReferencePackageVersions.java}</version>
</dependency>
예시를 src/main/java/AgentsApiSessionsStreamConversationExample.java로 저장하세요:
tree.py 만들고 실행하기
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=AgentsApiSessionsStreamConversationExample
Ruby
Ruby SDK를 설치하세요:
gem install openai
예시를 quickstart.rb로 저장하세요:
tree.py 만들고 실행하기
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
터미널에서 cURL을 사용하세요. SDK 설치는 필요 없어요:
tree.py 만들고 실행하기
curl --no-buffer --fail-with-body https://api.openai.com/v1/agents/sessions \
-H "OpenAI-Beta: agents=v1" \
-H "Authorization: Bearer ***" \
-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. 진행 상황 따라가기 (Follow progress)
터미널에 스트리밍된 이벤트가 표시돼요. SDK 예시는 JSON을 출력하고, cURL은 원시 이벤트 스트림을 보여 줘요. 성공적으로 실행되면 에이전트가 tree.py를 만들고, 실행하고, 그 파일이 포함된 디렉터리 트리를 보고해요. 다른 파일과 출력은 샌드박스에 따라 달라져요.
agent.session.turn.completed를 찾은 다음 에이전트가 보고한 실행 결과를 확인하세요. 턴이 완료됐다고 해서 모든 도구가 성공한 건 아니에요. turn.failed, turn.cancelled, session.failed로 끝나는 이벤트는 실패나 취소를 나타내고, agent.session.idle만으로는 성공을 뜻하지 않아요. 스트림이 일찍 끊기면 재시도 전에 세션과 저장된 아이템을 검색하세요.
3. 세션 이어가기 (Continue the session)
이벤트에서 session_id를 저장하세요. 그 값을 사용해 "tree.py에 최대 깊이 옵션을 추가하고, 실행해서 출력을 보여 줘" 같은 후속 입력을 보내세요. 후속 입력을 보내기 전에 이벤트 스트림을 열어서 초기 이벤트를 놓치지 마세요.
4. 정리하기 (Clean up)
더 많은 과제를 위해 세션을 유지하거나, 작업이 끝나면 삭제하세요. 먼저 필요한 파일을 저장하세요.
예시의 예시용 sess_123 값은 저장한 세션 ID로 바꾸세요.
Python
세션 삭제하기
# 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())
JavaScript
세션 삭제하기
// 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);
Go
세션 삭제하기
// 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)
}
Java
세션 삭제하기
// 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);
}
}
Ruby
세션 삭제하기
# 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
세션 삭제하기
curl -X DELETE "https://api.openai.com/v1/agents/sessions/sess_123" \
-H "OpenAI-Beta: agents=v1" \
-H "Authorization: Bearer ***"
다음 단계 (Next steps)
- 예시 애플리케이션 둘러보기.
- OpenAI 호스팅 샌드박스 구성하기: 패키지와 입력 파일 추가, 네트워크 접근 제어, 아티팩트 다운로드.
- 서브에이전트로 릴리스 노트 비교하기.
- 파일과 아티팩트 다루기.
- 환경 선택하기, 또는 자체 샌드박스 연결하기.
더 알아보기 (Learn more)
- Agents API 개요에서 핵심 개념과 관리형 하네스가 제공하는 기능을 확인하세요.
- 세션 가이드에서 스트림 복구와 후속 입력 방법을 더 알아보세요.