Interactions API는 Gemini Enterprise Agent Platform에서 Gemini 모델과 자율 에이전트를 사용하여 생성형 AI 애플리케이션을 빌드할 수 있는 통합된 스테이트풀(Stateful) 인터페이스를 제공합니다. Interactions API를 사용하여 세션 스토리지와 멀티턴 대화를 관리하고, 실시간 대답을 스트리밍하고, 구조화된 출력을 적용하고, 기본 제공 도구와 그라운딩을 호출하고, 함수 호출을 실행하고, 장기 실행 백그라운드 작업을 조정합니다.
이 가이드에서는 Google 생성형 AI SDK를 설치하고, 클라이언트를 인증하고, 일반적인 상호작용 워크플로를 구현하는 방법을 보여줍니다. 상호작용 수명 주기에 대한 개념적 세부정보는 Interactions API 개요를 참조하세요.
시작하기 전에
Interactions API에 요청을 보내기 전에 Google Cloud프로젝트와 개발 환경을 설정하세요.
-
In the Google Cloud console, on the project selector page, select or create a Google Cloud project.
Roles required to select or create a project
- Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
-
Create a project: To create a project, you need the Project Creator role
(
roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.createpermission. Learn how to grant roles.
-
Verify that billing is enabled for your Google Cloud project.
Enable the Agent Platform API, if it is not already enabled.
Roles required to enable APIs
To enable APIs, you need the
serviceusage.services.enablepermission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.-
Make sure that you have the following role or roles on the project: Agent Platform User (
roles/aiplatform.user)Check for the roles
-
In the Google Cloud console, go to the IAM page.
Go to IAM - Select the project.
-
In the Principal column, find all rows that identify you or a group that you're included in. To learn which groups you're included in, contact your administrator.
- For all rows that specify or include you, check the Role column to see whether the list of roles includes the required roles.
Grant the roles
-
In the Google Cloud console, go to the IAM page.
Go to IAM - Select the project.
- Click Grant access.
-
In the New principals field, enter your user identifier. This is typically the identifier for a user in a workforce identity pool. For details, see Represent workforce pool users in IAM policies, or contact your administrator.
- Click Select a role, then search for the role.
- To grant additional roles, click Add another role and add each additional role.
- Click Save.
-
주요 개념
Interactions API가 상태와 응답을 관리하는 방법을 이해하려면 다음 개념을 검토하세요.
Interaction: Interactions API는 핵심 리소스인Interaction를 중심으로 합니다.Interaction는 대화 또는 작업의 완전한 차례를 나타내며, 모델 사고, 도구 호출, 최종 출력의 연대순을 추적합니다. 프롬프트-대답 상호작용과 복잡한 다단계 에이전트 워크플로를 위한 통합 엔벨로프를 제공합니다.스테이트풀(Stateful) 보관: 상호작용은 기본적으로 서버 측에 저장됩니다(Python의 경우
store=True, TypeScript/JavaScript의 경우store: true). 저장된 상호작용은 7일 동안 유지되며 그 이후에는 자동으로 삭제됩니다.store=False을 설정하면 스테이트리스 모드가 선택되어 서버 측 보관이 사용 중지되고 제로 데이터 보관(ZDR)을 준수합니다. 스테이트리스 모드는previous_interaction_id체이닝 및 비동기 실행(background=True)도 사용 중지합니다.응답 도우미: Google 생성형 AI SDK 버전
2.3.0이상에서는 상호작용 응답에interaction.output_text,interaction.output_image,interaction.output_audio를 비롯한 편의 속성을 제공합니다.interaction.output_text를 사용하여 단계 배열(예:interaction.steps[-1].content[0].text)에 수동으로 색인을 생성하는 대신 텍스트 응답을 읽습니다.
요구사항
Interactions API와 통합하기 전에 환경과 요청이 다음 요구사항을 충족하는지 확인하세요.
SDK 버전 지원: 지원되는 Google 생성형 AI SDK 라이브러리 중 하나를 사용합니다.
지원되는 모델: 지원되는 Gemini 3 이상 모델을 사용합니다. 이전 모델 계열은 이 API를 지원하지 않습니다. 지원되는 모델의 전체 목록은 지원되는 모델 및 최신 모델 버전으로 마이그레이션을 참조하세요.
대화 범위 파라미터:
tools,system_instruction,generation_config와 같은 구성 파라미터는 현재 대화에만 적용됩니다. 워크플로에서 멀티턴 대화 전반에 걸쳐 이러한 파라미터가 필요한 경우 각 후속 상호작용 차례에서 이러한 파라미터를 전달합니다.Gemini 4 Argon의 긴 디코딩:
gemini-4-argon또는gemini-4-argon-cyber-permissive에서 65,536개 토큰(최대 1,048,576개 토큰에서 입력 토큰을 뺀 값)을 초과하는 싱글턴 출력을 생성하려면v1beta1엔드포인트에서 자동 Google 생성형 AI SDK 연속(Python의 경우google-genai >= 2.34.0, TypeScript/JavaScript의 경우@google/genai >= 2.32.0, Go의 경우>= 1.77.0, Java의 경우>= 1.80.0),background=True또는continuation_token를 사용합니다. 코드 샘플 및 연속 규칙은 Gemini 4 Argon 개발자 가이드의 긴 디코딩을 참고하세요.
Google 생성형 AI SDK 설치
원하는 언어의 Google 생성형 AI SDK를 설치하거나 업그레이드합니다.
Python
pip install --upgrade "google-genai>=2.3.0"
TypeScript / JavaScript
npm install "@google/genai>=2.3.0"
Go
go get google.golang.org/genai
자바
<dependencies>
<dependency>
<groupId>com.google.genai</groupId>
<artifactId>google-genai</artifactId>
<version>1.78.0</version>
</dependency>
</dependencies>
고객 인증하기
다음 인증 방법 중 하나를 사용하여 Agent Platform의 Interactions API에 연결할 수 있습니다.
애플리케이션 기본 사용자 인증 정보(ADC)를 사용하여 Google Cloud 프로젝트로 연결
Google Cloud에서 엔터프라이즈 워크로드 및 프로덕션 배포에 이 인증 방법을 사용합니다. 애플리케이션 기본 사용자 인증 정보(ADC)로 인증하려면 다음 속성으로 클라이언트를 초기화합니다.
enterprise=Trueproject="PROJECT_ID"location="global"
아직 로컬 사용자 인증 정보를 구성하지 않은 경우 gcloud auth application-default login를 실행합니다.
다음 코드 샘플에서 PROJECT_ID를Google Cloud 프로젝트 ID로 바꿉니다.
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Explain serverless computing in one sentence.",
)
print(interaction.output_text)
TypeScript / JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Explain serverless computing in one sentence.",
});
console.log(interaction.output_text);
REST
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": [{
"type": "user_input",
"content": [{
"type": "text",
"text": "Explain serverless computing in one sentence."
}]
}]
}'
익스프레스 모드를 사용하여 연결(API 키)
빠른 프로토타입 제작, 경량 스크립트 또는 API 키로 인증하는 환경에 이 인증 방법을 사용합니다. 클라이언트를 초기화할 때 또는 x-goog-api-key HTTP 헤더에서 API 키를 전달합니다.
다음 코드 샘플에서 API_KEY를 API 키로 바꾸고 PROJECT_ID를 Google Cloud 프로젝트 ID로 바꿉니다.
Python
from google import genai
client = genai.Client(
enterprise=True,
api_key="API_KEY",
)
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Explain serverless computing in one sentence.",
)
print(interaction.output_text)
TypeScript / JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
apiKey: "API_KEY",
});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Explain serverless computing in one sentence.",
});
console.log(interaction.output_text);
REST
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "x-goog-api-key: API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": [{
"type": "user_input",
"content": [{
"type": "text",
"text": "Explain serverless computing in one sentence."
}]
}]
}'
일반적인 상호작용 워크플로
클라이언트를 구성한 후에는 interactions.create 메서드를 사용하여 세션 스토리지 및 멀티턴 대화를 관리하고, 출력 토큰을 실시간으로 스트리밍하고, 스키마 검증 JSON을 생성하고, 기본 제공 도구 및 그라운딩을 호출하고, 외부 함수를 호출하고, 자율 에이전트를 실행할 수 있습니다.
세션 저장소 및 대화 상태 관리
Interactions API는 서버 측 스테이트풀(Stateful) 스토리지(store=True, 기본값)와 클라이언트 관리 스테이트리스(Stateless) 실행(store=False)을 모두 지원합니다. 다음 표에서는 스테이트풀(Stateful) 및 스테이트리스(Stateless) 상호작용 모드를 비교합니다.
| 기능 | 스테이트풀(Stateful) 모드(store=true, 기본값) |
스테이트리스 모드(store=false) |
|---|---|---|
| 서버 측 지속성 | 입력, 중간 단계, 출력을 서버에 7일 동안 저장합니다. | 제로 데이터 보관(ZDR) 워크플로를 지원하기 위해 서버 측 상호작용 스토리지를 사용 중지합니다. |
| 멀티턴 컨텍스트 |
previous_interaction_id에서 이전 상호작용 id를 전달하여 차례를 연결합니다.
|
각 차례마다 input에서 이전 대화 steps의 전체 배열을 전달해야 합니다. previous_interaction_id를 전달하면 400 Bad
Request 오류가 반환됩니다.
|
백그라운드 실행(background=true)
|
장기 실행 모델 및 에이전트 상호작용에 지원됩니다. | 지원되지 않음. 비동기 백그라운드 실행에는 서버 측 상태 지속성이 필요합니다. |
| 세션 수명 주기 메서드 |
상호작용 검색(get), 나열(list), 취소(cancel), 삭제(delete)를 지원합니다.
|
동기 또는 스트리밍 응답이 완료된 후에는 검색할 수 없습니다. |
| 저장 데이터 암호화 |
Google-owned and Google-managed encryption key또는 us 및 eu 멀티 리전의 고객 관리 암호화 키(CMEK)를 사용하여 기본적으로 암호화됩니다.
|
상호작용 상태는 저장되지 않습니다. |
스테이트풀(Stateful) 멀티턴 대화 실행
기본적으로 Interactions API는 서버에 대화 상태를 저장합니다(Python의 경우 store=True, TypeScript/JavaScript의 경우 store: true). 기존 대화를 계속하려면 이전 상호작용의 id를 previous_interaction_id 매개변수에 전달합니다. 에이전트 플랫폼은 저장된 대화 컨텍스트를 검색하고, 새 차례를 추가하고, 캐시된 프리픽스 토큰을 재사용합니다.
엔드포인트 간에 상호작용을 연결할 때는 다음 위치 규칙을 준수하세요.
동일한 위치: 동일한 위치 내에서 상호작용을 연결할 수 있습니다(예:
global에서global,us에서us,eu에서eu).여러 위치 간: 여러 엔드포인트 위치 간의 연결(
global와us또는eu간 또는us와eu간)은 지원되지 않습니다. 각 엔드포인트는 상호작용 상태를 격리된 스토리지에 저장하므로 다른 위치에서 생성된 상호작용 ID를 참조하면404 Not Found오류가 반환됩니다.
다음 예시에서 PROJECT_ID를 Google Cloud프로젝트 ID로 바꿉니다.
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
# Turn 1: Start a stateful conversation (store=True by default)
turn1 = client.interactions.create(
model="gemini-3.8-flash",
input="Hi! My name is John. I am working on AI agents.",
store=True,
)
print(f"Turn 1: {turn1.output_text}")
# Turn 2: Reference the stored conversation state using previous_interaction_id
turn2 = client.interactions.create(
model="gemini-3.8-flash",
input="What is my name?",
previous_interaction_id=turn1.id,
)
print(f"Turn 2: {turn2.output_text}")
TypeScript / JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
// Turn 1: Start a stateful conversation (store: true by default)
const turn1 = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Hi! My name is John. I am working on AI agents.",
store: true,
});
console.log(`Turn 1: ${turn1.output_text}`);
// Turn 2: Reference the stored conversation state using previous_interaction_id
const turn2 = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "What is my name?",
previous_interaction_id: turn1.id,
});
console.log(`Turn 2: ${turn2.output_text}`);
자바
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
Client client =
Client.builder()
.enterprise(true)
.project("PROJECT_ID")
.location("global")
.build();
// Turn 1: Start a stateful conversation (store is true by default)
CreateModelInteraction req1 =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Hi! My name is John. I am working on AI agents."))
.store(true)
.build();
Interaction turn1 =
client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().orElseThrow();
System.out.println("Turn 1: " + turn1.outputText().orElse(""));
// Turn 2: Reference the stored conversation state using previousInteractionId
CreateModelInteraction req2 =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.previousInteractionId(turn1.id().orElseThrow())
.input(InteractionsInput.of("What is my name?"))
.build();
Interaction turn2 =
client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().orElseThrow();
System.out.println("Turn 2: " + turn2.outputText().orElse(""));
REST
# Turn 1: Start a stateful conversation
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"store": true,
"input": "Hi! My name is John. I am working on AI agents."
}'
# Turn 2: Pass the interaction ID from Turn 1 in previous_interaction_id
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"previous_interaction_id": "PREVIOUS_INTERACTION_ID",
"input": "What is my name?"
}'
스테이트리스(Stateless) 멀티턴 대화 실행
워크로드에 데이터 보관 제로(ZDR)가 필요한 경우 모든 요청에서 store=False(TypeScript/JavaScript의 경우 store: false, REST의 경우 "store": false)를 명시적으로 설정합니다.
스테이트리스 모드에서는 Step 객체(user_input, thought, function_call, function_result, model_output) 목록을 유지하고 각 차례에 input에서 누적된 steps 배열을 전송하여 클라이언트에서 대화 기록을 관리합니다.
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
history = [
{
"type": "user_input",
"content": [{"type": "text", "text": "Hi! My name is John."}],
}
]
# Turn 1: Stateless request (store=False)
turn1 = client.interactions.create(
model="gemini-3.8-flash",
input=history,
store=False,
)
print(f"Turn 1: {turn1.output_text}")
# Append the model's generated steps and the next user turn to local history
history.extend(turn1.steps)
history.append(
{
"type": "user_input",
"content": [{"type": "text", "text": "What is my name?"}],
}
)
# Turn 2: Send the full step history with store=False
turn2 = client.interactions.create(
model="gemini-3.8-flash",
input=history,
store=False,
)
print(f"Turn 2: {turn2.output_text}")
TypeScript / JavaScript
import { GoogleGenAI, Step } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
const history: Step[] = [
{
type: "user_input",
content: [{ type: "text", text: "Hi! My name is John." }],
},
];
// Turn 1: Stateless request (store: false)
const turn1 = await ai.interactions.create({
model: "gemini-3.8-flash",
input: history,
store: false,
});
console.log(`Turn 1: ${turn1.output_text}`);
// Append the model's generated steps and the next user turn to local history
if (turn1.steps) {
history.push(...turn1.steps);
}
history.push({
type: "user_input",
content: [{ type: "text", text: "What is my name?" }],
});
// Turn 2: Send the full step history with store: false
const turn2 = await ai.interactions.create({
model: "gemini-3.8-flash",
input: history,
store: false,
});
console.log(`Turn 2: ${turn2.output_text}`);
자바
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.UserInputContent;
import com.google.genai.gaos.models.interactions.UserInputStep;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.ArrayList;
import java.util.List;
Client client =
Client.builder()
.enterprise(true)
.project("PROJECT_ID")
.location("global")
.build();
List<Step> history = new ArrayList<>();
history.add(
Step.of(
UserInputStep.builder()
.content(
List.of(
UserInputContent.of(
TextContent.builder().text("Hi! My name is John.").build())))
.build()));
// Turn 1: Stateless request (store(false))
CreateModelInteraction req1 =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.ofSteps(history))
.store(false)
.build();
Interaction turn1 =
client.interactions.create(CreateInteractionRequestBody.of(req1)).interaction().orElseThrow();
System.out.println("Turn 1: " + turn1.outputText().orElse(""));
// Append the model's generated steps and the next user turn to local history
turn1.steps().ifPresent(history::addAll);
history.add(
Step.of(
UserInputStep.builder()
.content(
List.of(
UserInputContent.of(
TextContent.builder().text("What is my name?").build())))
.build()));
// Turn 2: Send the full step history with store(false)
CreateModelInteraction req2 =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.ofSteps(history))
.store(false)
.build();
Interaction turn2 =
client.interactions.create(CreateInteractionRequestBody.of(req2)).interaction().orElseThrow();
System.out.println("Turn 2: " + turn2.outputText().orElse(""));
REST
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"store": false,
"input": [
{
"type": "user_input",
"content": [{"type": "text", "text": "Hi! My name is John."}]
},
{
"type": "model_output",
"content": [{"type": "text", "text": "Hello John! How can I help you today?"}]
},
{
"type": "user_input",
"content": [{"type": "text", "text": "What is my name?"}]
}
]
}'
보관 및 세션 수명 주기
저장된 상호작용(store=True)은 다음 보관 및 분기 규칙을 따릅니다.
7일 TTL(수명): 저장된 각 상호작용은
created타임스탬프부터 7일 동안 유지되며 7일 TTL이 만료되면 자동으로 삭제됩니다.독립적인 상위 및 하위 스토리지:
previous_interaction_id를 사용하여 새 대화를 연결하면 에이전트 플랫폼이 상위 대화 기록을 새 상호작용 레코드에 복사합니다. 각 차례는 대화 기록의 자체 사본을 저장하므로 이전 차례를 만료하거나 삭제하면 다음과 같은 결과가 발생합니다.이후 차례에서 계속 성공: 차례 2(
interaction_2)가 이미 생성된 후 차례 1(interaction_1)이 만료되거나 삭제된 경우에도interaction_2자체가 만료되거나 삭제될 때까지previous_interaction_id=interaction_2.id를 사용하여 차례 3을 만들 수 있습니다.만료되거나 삭제된 차례에서 분기 실패:
previous_interaction_id에서 만료되거나 삭제된 상호작용 ID를 직접 참조하는 새 상호작용을 만들려고 하면400 Bad Request(Previous Interaction ID not found) 오류가 반환됩니다.
저장된 상호작용 검색, 나열, 취소, 삭제
다음 메서드를 사용하여 수명 주기 전반에 걸쳐 저장된 상호작용을 검사하고 관리할 수 있습니다.
상호작용 검색(
interactions.get):user_input단계, 중간thought및 도구 단계,model_output단계를 포함하여id로 전체Interaction리소스를 가져옵니다. 진행 중인 상호작용을 스트리밍하거나 재개하려면stream=True(및 선택사항인last_event_id)를 설정합니다.상호작용 나열(
interactions.list):page_size(기본값10, 최대500) 및page_token를 사용하여 REST를 통해 프로젝트에 저장된 상호작용 ID를 쿼리합니다.InteractionMetadata리소스 목록을 반환합니다.진행 중인 상호작용 취소(
interactions.cancel):in_progress또는requires_action상태에 있는 비동기 백그라운드 상호작용(background=True)을 중지하고 상태를cancelled로 전환합니다. 취소 전에 생성된 토큰에 대한 요금이 청구됩니다.저장된 상호작용 삭제(
interactions.delete): 7일 TTL이 만료되기 전에 저장된 상호작용을 영구적으로 삭제합니다. 터미널 상태(completed,failed또는cancelled)의 상호작용만 삭제할 수 있습니다. 상호작용이 백그라운드에서 계속 실행 중인 경우 삭제하기 전에 취소하세요.
다음 예시에서 PROJECT_ID를 Google Cloud프로젝트 ID로 바꾸고 INTERACTION_ID를 대상 상호작용 ID로 바꿉니다.
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
# Retrieve a stored interaction by ID
interaction = client.interactions.get(id="INTERACTION_ID")
print(f"Status: {interaction.status}")
# Cancel an in-progress background interaction
cancelled = client.interactions.cancel(id="INTERACTION_ID")
print(f"After cancel: {cancelled.status}")
# Delete a completed, failed, or cancelled interaction before its 7-day TTL
client.interactions.delete(id="INTERACTION_ID")
print("Interaction deleted.")
TypeScript / JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
// Retrieve a stored interaction by ID
const interaction = await ai.interactions.get("INTERACTION_ID");
console.log(`Status: ${interaction.status}`);
// Cancel an in-progress background interaction
const cancelled = await ai.interactions.cancel("INTERACTION_ID");
console.log(`After cancel: ${cancelled.status}`);
// Delete a completed, failed, or cancelled interaction before its 7-day TTL
await ai.interactions.delete("INTERACTION_ID");
console.log("Interaction deleted.");
자바
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionStatus;
import com.google.genai.gaos.models.operations.CancelInteractionByIdResponse;
import com.google.genai.gaos.models.operations.GetInteractionByIdRequest;
import com.google.genai.gaos.models.operations.GetInteractionByIdResponse;
Client client =
Client.builder()
.enterprise(true)
.project("PROJECT_ID")
.location("global")
.build();
String interactionId = "INTERACTION_ID";
// Retrieve a stored interaction by ID
GetInteractionByIdResponse getResponse =
client.interactions.get(new GetInteractionByIdRequest(interactionId));
Interaction interaction = getResponse.interaction().orElseThrow();
System.out.println("Status: " + interaction.status().map(InteractionStatus::value).orElse(""));
// Cancel an in-progress background interaction
CancelInteractionByIdResponse cancelResponse = client.interactions.cancel(interactionId);
Interaction cancelled = cancelResponse.interaction().orElseThrow();
System.out.println("After cancel: " + cancelled.status().map(InteractionStatus::value).orElse(""));
// Delete a completed, failed, or cancelled interaction before its 7-day TTL
client.interactions.delete(interactionId);
System.out.println("Interaction deleted.");
REST
# Retrieve a stored interaction by ID
curl -X GET "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions/INTERACTION_ID" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"
# List stored interactions (up to 500 per page)
curl -X GET "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions?page_size=10" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"
# Cancel an in-progress background interaction
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions/INTERACTION_ID/cancel" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"
# Delete a completed, failed, or cancelled interaction
curl -X DELETE "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions/INTERACTION_ID" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)"
스테이트풀(Stateful) 스토리지 할당량 및 한도
모델 토큰 및 요청 비율 제한 외에도 스테이트풀(Stateful) 상호작용(store=True)에는 다음과 같은 프로젝트 수준 스토리지 및 동시 실행 한도가 적용됩니다.
| 할당량 또는 시스템 한도 | 기본 한도(프로젝트당) | 설명 |
|---|---|---|
| 일일 스테이트풀(Stateful) 상호작용 생성 처리량 | 일 240 GiB회 |
store=true를 사용하는 interactions.create 요청에서 하루에 서버 측 스토리지에 기록되는 상호작용 데이터의 최대 총량입니다. |
| 일일 스테이트풀(Stateful) 상호작용 검색 처리량 | 일 480 GiB회 |
interactions.get 요청과 previous_interaction_id를 사용하여 이전 차례를 로드하는 멀티턴 요청에서 하루에 읽는 저장된 상호작용 데이터의 최대 총 볼륨입니다. |
| 동시 스테이트풀(Stateful) 상호작용 | 동시 상호작용 500개 |
프로젝트에서 동시에 실행되는 활성 스테이트풀(Stateful) 상호작용의 최대 개수입니다. |
Agent Platform에서 할당량을 보고 관리하는 방법에 대한 자세한 내용은 할당량 및 시스템 한도를 참조하세요.
실시간으로 응답 스트리밍
대화형 애플리케이션의 인식 지연 시간을 줄이기 위해 모델 응답이 생성될 때 스트리밍할 수 있습니다. interactions.create를 호출할 때 stream=True(TypeScript/JavaScript의 경우 stream: true)를 설정하여 서버 전송 이벤트의 반복 가능한 스트림을 수신합니다. step.delta 이벤트를 필터링하여 증분 텍스트 청크가 도착하는 대로 렌더링합니다.
Python
response = client.interactions.create(
model="gemini-3.8-flash",
input="Write a short poem about debugging.",
stream=True,
)
for event in response:
if event.event_type == "step.delta" and hasattr(event.delta, "text"):
print(event.delta.text, end="", flush=True)
print()
TypeScript / JavaScript
const responseStream = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Write a short poem about debugging.",
stream: true,
});
for await (const event of responseStream) {
if (event.event_type === "step.delta" && event.delta && "text" in event.delta) {
process.stdout.write(event.delta.text);
}
}
console.log();
구조화된 출력 생성
애플리케이션에 예측 가능하고 기계 가독형 형식의 응답이 필요한 경우 특정 JSON 스키마와 일치하도록 모델 출력을 제한할 수 있습니다. Python의 Pydantic 모델 JSON 스키마 또는 TypeScript/JavaScript의 Type 스키마 객체와 같은 타겟 스키마를 다형성 response_format 파라미터에 직접 전달합니다.
Python
from pydantic import BaseModel, Field
class Book(BaseModel):
title: str = Field(description="The title of the book")
author: str = Field(description="The book's author")
year_published: int
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Recommend one famous sci-fi book.",
response_format=Book.model_json_schema(),
)
# The output text is valid JSON matching the Book schema
print(interaction.output_text)
TypeScript / JavaScript
import { Type } from "@google/genai";
const BookSchema = {
type: Type.OBJECT,
properties: {
title: { type: Type.STRING, description: "The title of the book" },
author: { type: Type.STRING, description: "The book's author" },
yearPublished: { type: Type.INTEGER },
},
required: ["title", "author", "yearPublished"],
};
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Recommend one famous sci-fi book.",
response_format: BookSchema,
});
console.log(interaction.output_text);
함수 호출(도구 사용) 사용
함수 호출을 사용하면 모델이 최종 대답을 작성하기 전에 커스텀 함수 또는 외부 API의 실행을 요청하여 정보를 수집할 수 있습니다. 스테이트풀(Stateful) 상호작용 워크플로에서 함수 호출은 2턴 패턴을 따릅니다.
도구 선언 및 전달: 초기 요청의
tools매개변수에 함수 선언을 제공합니다.실행 및 결과 반환:
function_call단계의 응답 단계(interaction.steps)를 검사하고, 모델에서 제공한arguments를 사용하여 로컬 함수를 실행하고,call_id및previous_interaction_id로 연결된function_result항목이 포함된 후속 상호작용을 전송합니다.
Python
# Define a declarative function tool schema
stock_tool = {
"type": "function",
"name": "get_stock_price",
"description": "Gets the stock price for a given ticker symbol.",
"parameters": {
"type": "object",
"properties": {
"ticker": {"type": "string", "description": "The stock ticker symbol"}
},
"required": ["ticker"],
},
}
def get_stock_price(ticker: str) -> float:
"""Executes the local tool function."""
if ticker.upper() == "GOOG":
return 175.50
return 100.0
# Turn 1: Pass the tool declaration to the model
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="What is the stock price of GOOG?",
tools=[stock_tool],
)
# Inspect the interaction steps for function call requests
for step in interaction.steps:
if step.type == "function_call" and step.name == "get_stock_price":
ticker_arg = step.arguments.get("ticker")
price = get_stock_price(ticker_arg)
# Turn 2: Submit the function execution result to the conversation
final_turn = client.interactions.create(
model="gemini-3.8-flash",
input=[{
"type": "function_result",
"call_id": step.id,
"result": {"price": price},
}],
previous_interaction_id=interaction.id,
)
print(final_turn.output_text)
TypeScript / JavaScript
// Define a declarative function tool schema
const stockTool = {
type: "function",
name: "getStockPrice",
description: "Gets the stock price for a given ticker symbol.",
parameters: {
type: "object",
properties: {
ticker: { type: "string", description: "The stock ticker symbol" },
},
required: ["ticker"],
},
};
function getStockPrice({ ticker }: { ticker: string }): number {
if (ticker.toUpperCase() === "GOOG") return 175.50;
return 100.00;
}
// Turn 1: Pass the tool declaration to the model
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "What is the stock price of GOOG?",
tools: [stockTool],
});
// Inspect the interaction steps for function call requests
for (const step of interaction.steps ?? []) {
if (step.type === "function_call" && step.name === "getStockPrice") {
const tickerArg = step.arguments.ticker as string;
const price = getStockPrice({ ticker: tickerArg });
// Turn 2: Submit the function execution result to the conversation
const finalTurn = await ai.interactions.create({
model: "gemini-3.8-flash",
input: [{
type: "function_result",
call_id: step.id,
result: { price },
}],
previous_interaction_id: interaction.id,
});
console.log(finalTurn.output_text);
}
}
기본 제공 도구 사용
Interactions API는 클라이언트 측 함수 호출 외에도 Gemini 3 모델을 위한 기본 제공 서버 측 도구를 지원합니다. tools 파라미터에서 기본 제공 도구를 사용 설정하면 Agent Platform은 단일 interactions.create 호출 중에 서버에서 도구를 실행하고 interaction.steps에서 도구 호출(*_call) 및 출력(*_result) 단계를 기록합니다.
Interactions API는 다음과 같은 기본 제공 도구를 지원합니다.
코드 실행(
{"type": "code_execution"}): 샌드박스 환경에서 Python 코드를 생성하고 실행하여 계산, 데이터 분석, 코드 기반 추론을 수행합니다. 지원되는 라이브러리, 결제, 제한사항은 코드 실행을 참조하세요.URL 컨텍스트(
{"type": "url_context"}): 프롬프트에 포함된 공개 웹 URL에서 콘텐츠를 검색하고 분석합니다. 색인 캐시, 실시간 가져오기, URL 컨텍스트와 검색 결합에 대한 자세한 내용은 URL 컨텍스트를 참조하세요.Google 검색을 사용한 그라운딩(
{"type": "google_search"}): 실시간 웹 정보에서 모델 응답을 그라운딩하고 인라인 인용을 반환합니다. Google 검색을 사용한 대답 그라운딩을 참조하세요.컴퓨터 사용(
{"type": "computer_use"}): 브라우저 및 사용자 인터페이스 자동화 워크플로를 사용 설정합니다. 구성 및 안전 제어는 컴퓨터 사용을 참고하세요.
Python 코드 실행
코드 실행을 사용 설정하려면 tools 목록에 {"type": "code_execution"}을 포함하세요. 반환된 interaction.steps 배열에는 code_execution_call 단계(arguments.code 및 arguments.language 포함), code_execution_result 단계(result 및 is_error 포함), 최종 model_output 단계가 포함됩니다.
다음 예시에서 PROJECT_ID를 Google Cloud프로젝트 ID로 바꿉니다.
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Calculate the 50th Fibonacci number and find its closest prime.",
tools=[{"type": "code_execution"}],
)
for step in interaction.steps:
if step.type == "code_execution_call":
print(f"Generated code:\n{step.arguments.code}")
elif step.type == "code_execution_result":
print(f"Execution result:\n{step.result}")
elif step.type == "model_output":
for content in step.content:
if content.type == "text":
print(content.text)
TypeScript / JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Calculate the 50th Fibonacci number and find its closest prime.",
tools: [{ type: "code_execution" }],
});
for (const step of interaction.steps ?? []) {
if (step.type === "code_execution_call") {
console.log(`Generated code:\n${step.arguments?.code}`);
} else if (step.type === "code_execution_result") {
console.log(`Execution result:\n${step.result}`);
} else if (step.type === "model_output") {
for (const content of step.content ?? []) {
if (content.type === "text") {
console.log(content.text);
}
}
}
}
자바
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CodeExecution;
import com.google.genai.gaos.models.interactions.CodeExecutionCallStep;
import com.google.genai.gaos.models.interactions.CodeExecutionResultStep;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;
Client client =
Client.builder()
.enterprise(true)
.project("PROJECT_ID")
.location("global")
.build();
CreateModelInteraction request =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(
InteractionsInput.of(
"Calculate the 50th Fibonacci number and find its closest prime."))
.tools(List.of(CodeExecution.builder().build()))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(request)).interaction().orElseThrow();
for (Step step : interaction.steps().orElse(List.of())) {
if (step instanceof CodeExecutionCallStep callStep) {
callStep
.arguments()
.flatMap(args -> args.code())
.ifPresent(code -> System.out.println("Generated code:\n" + code));
} else if (step instanceof CodeExecutionResultStep resultStep) {
resultStep
.result()
.ifPresent(res -> System.out.println("Execution result:\n" + res));
}
}
System.out.println(interaction.outputText().orElse(""));
REST
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": "Calculate the 50th Fibonacci number and find its closest prime.",
"tools": [{"type": "code_execution"}]
}'
URL 컨텍스트로 웹페이지 콘텐츠 검색
모델이 프롬프트에서 참조된 웹페이지를 가져오고 분석할 수 있도록 하려면 tools 목록에 {"type": "url_context"}을 포함하세요. API는 url_context_call 및 url_context_result 단계에서 가져온 URL을 기록하고 model_output에서 생성된 텍스트에 url_citation 주석을 연결합니다.
다음 예시에서 PROJECT_ID를 Google Cloud프로젝트 ID로 바꾸고 YOUR_URL_1 및 YOUR_URL_2를 비교할 공개 URL로 바꿉니다.
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Compare the key findings from YOUR_URL_1 and YOUR_URL_2.",
tools=[{"type": "url_context"}],
)
print(interaction.output_text)
TypeScript / JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Compare the key findings from YOUR_URL_1 and YOUR_URL_2.",
tools: [{ type: "url_context" }],
});
console.log(interaction.output_text);
자바
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.URLContext;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;
Client client =
Client.builder()
.enterprise(true)
.project("PROJECT_ID")
.location("global")
.build();
CreateModelInteraction request =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(
InteractionsInput.of(
"Compare the key findings from YOUR_URL_1 and YOUR_URL_2."))
.tools(List.of(URLContext.builder().build()))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(request)).interaction().orElseThrow();
System.out.println(interaction.outputText().orElse(""));
REST
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": "Compare the key findings from YOUR_URL_1 and YOUR_URL_2.",
"tools": [{"type": "url_context"}]
}'
Google 검색으로 대답 그라운딩
그라운딩은 Gemini 모델을 검증 가능한 외부 소스에 연결하여 할루시네이션을 줄이고 인용과 함께 최신 답변을 제공합니다. Agent Platform의 그라운딩 옵션에 대한 개요는 그라운딩 개요, Google 검색을 사용한 그라운딩, 엔터프라이즈용 웹 그라운딩을 참조하세요.
tools 목록에 {"type": "google_search"}를 전달하여 Google 검색을 사용한 그라운딩을 사용 설정하면 Interactions API가 interaction.steps 타임라인에서 직접 검색 및 기여 분석 데이터를 반환합니다.
google_search_call: 모델에서 실행한 검색어가 포함됩니다(step.arguments.queries).google_search_result: 사용자 인터페이스에서 추천 검색어를 렌더링하는 데 사용되는 HTML/CSS 스니펫인 추천 검색어(result[].search_suggestions)가 포함되어 있습니다. 소스 URL과 제목이 있는 웹 리소스는model_output텍스트 블록에 인라인url_citation주석으로 제공됩니다.인라인
url_citation주석:model_output단계 내의 각text콘텐츠 블록(TextContent)에는annotations배열이 포함될 수 있습니다. 각url_citation주석은 소스title및url와 함께 응답 텍스트의 문자 또는 바이트 범위(start_index및end_index)를 식별합니다.
다음 예시에서 PROJECT_ID를 Google Cloud프로젝트 ID로 바꿉니다.
Python
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
interaction = client.interactions.create(
model="gemini-3.8-flash",
input="Who won the 2026 Super Bowl?",
tools=[{"type": "google_search"}],
)
print(interaction.output_text)
# Parse inline url_citation annotations from model_output steps
print("\nSources:")
for step in interaction.steps:
if step.type == "model_output" and step.content:
for content in step.content:
if content.type == "text" and getattr(content, "annotations", None):
for annotation in content.annotations:
if annotation.type == "url_citation":
span = content.text[annotation.start_index:annotation.end_index]
print(f"- [{annotation.title}]({annotation.url}) (cited text: {span!r})")
TypeScript / JavaScript
import { GoogleGenAI } from "@google/genai";
const ai = new GoogleGenAI({
enterprise: true,
project: "PROJECT_ID",
location: "global",
});
const interaction = await ai.interactions.create({
model: "gemini-3.8-flash",
input: "Who won the 2026 Super Bowl?",
tools: [{ type: "google_search" }],
});
console.log(interaction.output_text);
// Parse inline url_citation annotations from model_output steps
console.log("\nSources:");
for (const step of interaction.steps ?? []) {
if (step.type === "model_output") {
for (const content of step.content ?? []) {
if (content.type === "text" && content.annotations) {
for (const annotation of content.annotations) {
if (annotation.type === "url_citation") {
const span = content.text.slice(
annotation.start_index,
annotation.end_index,
);
console.log(
`- [${annotation.title}](${annotation.url}) (cited text: "${span}")`,
);
}
}
}
}
}
}
자바
import com.google.genai.Client;
import com.google.genai.gaos.models.interactions.Annotation;
import com.google.genai.gaos.models.interactions.Content;
import com.google.genai.gaos.models.interactions.CreateModelInteraction;
import com.google.genai.gaos.models.interactions.GoogleSearch;
import com.google.genai.gaos.models.interactions.Interaction;
import com.google.genai.gaos.models.interactions.InteractionsInput;
import com.google.genai.gaos.models.interactions.Model;
import com.google.genai.gaos.models.interactions.ModelOutputStep;
import com.google.genai.gaos.models.interactions.Step;
import com.google.genai.gaos.models.interactions.TextContent;
import com.google.genai.gaos.models.interactions.URLCitation;
import com.google.genai.gaos.models.operations.CreateInteractionRequestBody;
import java.util.List;
Client client =
Client.builder()
.enterprise(true)
.project("PROJECT_ID")
.location("global")
.build();
CreateModelInteraction request =
CreateModelInteraction.builder()
.model(Model.of("gemini-3.8-flash"))
.input(InteractionsInput.of("Who won the 2026 Super Bowl?"))
.tools(List.of(GoogleSearch.builder().build()))
.build();
Interaction interaction =
client.interactions.create(CreateInteractionRequestBody.of(request)).interaction().orElseThrow();
System.out.println(interaction.outputText().orElse(""));
// Parse inline URLCitation annotations from ModelOutputStep blocks
System.out.println("\nSources:");
for (Step step : interaction.steps().orElse(List.of())) {
if (step instanceof ModelOutputStep outputStep) {
for (Content content : outputStep.content().orElse(List.of())) {
if (content instanceof TextContent textContent) {
for (Annotation annotation : textContent.annotations().orElse(List.of())) {
if (annotation instanceof URLCitation citation) {
System.out.printf(
"- %s: %s (span: %d..%d)%n",
citation.title().orElse(""),
citation.url().orElse(""),
citation.startIndex().orElse(0L),
citation.endIndex().orElse(0L));
}
}
}
}
}
}
REST
# Request
curl -X POST "https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/global/interactions" \
-H "Authorization: Bearer $(gcloud auth application-default print-access-token)" \
-H "Content-Type: application/json" \
-d '{
"model": "gemini-3.8-flash",
"input": "Who won the 2026 Super Bowl?",
"tools": [{"type": "google_search"}]
}'
응답에는 인라인 url_citation 주석이 있는 google_search_call, google_search_result, model_output 단계가 포함됩니다.
{
"id": "v1_ChdPU0F4YWFtNkFwS2kxZThQZ05lbXdROA",
"model": "gemini-3.8-flash",
"status": "completed",
"steps": [
{
"type": "google_search_call",
"id": "search_call_1",
"arguments": {
"queries": ["2026 Super Bowl winner"]
}
},
{
"type": "google_search_result",
"call_id": "search_call_1",
"result": [
{
"search_suggestions": "<!-- HTML and CSS for search suggestions -->"
}
]
},
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "The Seattle Seahawks won Super Bowl LX on February 8, 2026.",
"annotations": [
{
"type": "url_citation",
"start_index": 0,
"end_index": 59,
"title": "Super Bowl LX",
"url": "https://example.com/super-bowl-lx"
}
]
}
]
}
]
}
에이전트 및 장기 실행 백그라운드 작업 실행
Interactions API를 사용하면 기반 모델 외에도 agent 매개변수를 사용하여 특수 자율 에이전트를 호출할 수 있습니다.
antigravity-preview-05-2026: 안전한 샌드박스 Linux 환경에서 코드 실행, 파일 관리, 웹브라우징을 지원하는 범용 관리형 에이전트입니다. 자세한 내용은 에이전트와 상호작용을 참조하세요.deep-research-preview-04-2026: 다단계 웹 조사 작업을 계획 및 실행하고 여러 소스의 결과를 종합하여 포괄적인 보고서를 작성하는 Gemini Deep Research 에이전트입니다. 자세한 내용은 Gemini Deep Research 에이전트 사용을 참조하세요.- 커스텀 에이전트:
client.agents.create()로 구성되고 프로비저닝된 커스텀 에이전트 리소스입니다.
에이전트 워크플로는 완료하는 데 몇 분 정도 걸리는 경우가 많으므로 background=True를 설정하여 백그라운드에서 비동기식으로 실행합니다. API는 interaction.status가 completed로 전환될 때까지 client.interactions.get()를 사용하여 폴링할 수 있는 id가 포함된 Interaction 객체를 즉시 반환합니다.
이 샘플을 사용해 보기 전에 PROJECT_ID를Google Cloud 프로젝트 ID로 바꿉니다.
import time
from google import genai
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
interaction = client.interactions.create(
input="Analyze competitive positioning for solar energy providers.",
agent="deep-research-preview-04-2026",
background=True,
)
print(f"Research started: {interaction.id}")
while True:
interaction = client.interactions.get(interaction.id)
if interaction.status == "completed":
print(interaction.output_text)
break
elif interaction.status in ("failed", "cancelled"):
print(f"Research ended with status: {interaction.status}")
break
time.sleep(10)
업로드된 Cloud Storage 파일에 액세스
Interactions API를 사용하여 업로드된 Cloud Storage 파일에 액세스할 수 있습니다. 다음 예시에서 PROJECT_ID를Google Cloud 프로젝트 ID로 바꿉니다.
from google import genai
# Credentials must belong to an identity with storage.objects.get permissions
client = genai.Client(
enterprise=True,
project="PROJECT_ID",
location="global",
)
interaction = client.interactions.create(
model="gemini-3.8-flash",
input=[
{
"type": "user_input",
"content": [
{"type": "text", "text": "Summarize the attached document:"},
{
"type": "document",
"uri": "gs://my-secure-bucket/quarterly_report.pdf",
"mime_type": "application/pdf",
},
],
}
],
)
print(interaction.output_text)
Cloud Storage URI(예: gs://bucket-name/path/to/file)를 Interactions API에 전달할 때 요청은 호출 프로젝트의 에이전트 플랫폼 서비스 에이전트(service-PROJECT_NUMBER@gcp-sa-aiplatform.)가 Cloud Storage에서 객체를 가져오기 전에 호출자의 사용자 인증 정보를 사용하여 읽기 액세스 권한을 확인합니다.
상호작용 요청에서 Cloud Storage 파일을 전달하려면 호출 주 구성원(사용자 계정, 서비스 계정 또는 제휴 ID)이 참조된 모든 객체에 대해 storage.objects.get 권한을 보유해야 합니다. 교차 프로젝트 Cloud Storage 버킷 또는 커스텀 IAM 정책이 있는 Cloud Storage 버킷의 경우 호출 주 구성원과 호출 프로젝트의 서비스 에이전트 모두에 읽기 액세스 권한을 부여합니다.
각 표준 Gemini 모델 상호작용 요청은 최대 100개의 고유한 Cloud Storage(gs://) URI(파일당 최대 2GiB - 500KiB)를 지원합니다. previous_interaction_id를 사용하여 스테이트풀(Stateful) 차례를 연결하면 Agent Platform은 대화 기록과 현재 차례에서 고유한 gs:// URI를 누적하여 계산합니다. 관리형 에이전트 상호작용(model 대신 agent를 설정하는 요청), Gemini Omni 모델, Lyria 3 모델은 이 100개 URI 한도에서 제외됩니다.
Cloud Storage 파일에 액세스하기 위한 IAM 역할 구성
storage.objects.get 권한이 포함된 표준 사전 정의된 역할 중 하나를 부여합니다.
스토리지 객체 뷰어(
roles/storage.objectViewer): 객체에 대한 읽기 액세스 권한(권장)스토리지 객체 사용자(
roles/storage.objectUser): 객체에 대한 읽기 및 쓰기 액세스 권한입니다.
Google Cloud CLI를 사용하여 사용자 계정에 액세스 권한을 부여하려면 다음 명령어를 사용합니다.
gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
--member="user:user-email@example.com" \
--role="roles/storage.objectViewer"
특정 호출 서비스 계정에 액세스 권한을 부여하려면 다음 명령어를 사용합니다.
gcloud storage buckets add-iam-policy-binding gs://BUCKET_NAME \
--member="serviceAccount:sa-name@PROJECT_ID." \
--role="roles/storage.objectViewer"
Cloud Storage 파일 액세스 문제 해결
호출 주 구성원에게 충분한 권한이 없으면 Interactions API는 다음과 유사한 403 Forbidden 오류를 반환합니다.
Access error:
PERMISSION_DENIED - 403 Forbidden: Calling principal lacks
storage.objects.get on one or more Cloud Storage URIs.
이 문제를 해결하려면 Cloud Storage 버킷 또는 객체에 대한 스토리지 객체 뷰어 역할(roles/storage.objectViewer)을 인증된 호출자(교차 프로젝트 또는 커스텀 IAM Cloud Storage 버킷의 경우 호출 프로젝트의 에이전트 플랫폼 서비스 에이전트)에게 부여합니다.
지정된 객체가 없거나 버킷 권한으로 인해 호출자가 객체의 존재 여부를 확인할 수 없는 경우 Interactions API는 다음과 유사한 404 Not Found 오류를 반환합니다.
Access error:
NOT_FOUND - 404 Not Found: The object does not exist, or bucket
permissions prevent revealing object existence.
이 문제를 해결하려면 Cloud Storage URI가 올바른지 확인하고 인증된 호출자에게 버킷에 대한 읽기 액세스 권한이 있는지 확인합니다.
모델 상호작용 요청이 현재 차례와 연결된 previous_interaction_id 기록에서 100개가 넘는 고유한 Cloud Storage URI를 참조하는 경우 Interactions API는 다음과 유사한 400 Bad Request 오류를 반환합니다.
INVALID_ARGUMENT - 400 Bad Request: Request references 101 distinct gs:// URIs, which exceeds the maximum of 100.
이 문제를 해결하려면 다음 중 한 가지를 따르세요.
- 이전 차례의 파일이 더 이상 필요하지 않으면
previous_interaction_id없이 새 상호작용을 시작합니다. - 요청 페이로드 한도(동기식 또는 스트리밍 요청의 경우 압축된 256MiB,
service_tier가deferred로 설정되고background및store가true로 설정된 경우 압축되지 않은 9.75MiB) 내에서 더 작은 문서를 결합하거나 추가 파일을 인라인으로 전달합니다. - 모달리티별 모델 항목 한도(이미지 및 PDF 합쳐서 3,000개, 오디오 파일 1,000개, 동영상 10개 또는 일반 텍스트 파일을 포함하는 경우 최대 6,500개 파일)까지
gs://URI를 참조하는 요청에는generateContent를 사용합니다.
CMEK로 상호작용 데이터 암호화
스테이트풀(Stateful) 상호작용(Python의 store=True 또는 TypeScript/JavaScript의 store: true)은 상호작용 데이터를 최대 7일 동안 저장합니다.Google-owned and Google-managed encryption key대신 자체 암호화 키로 해당 데이터를 보호하려면 서빙 프로필을 사용합니다. 서빙 프로필은 Cloud Key Management Service 키를 프로젝트, 위치, API 범위에 연결합니다. 서빙 프로필이 있는 동안 Agent Platform은 저장된 상호작용 데이터를 자동으로 암호화하므로 상호작용 요청 형식이 변경되지 않습니다.
Interactions API의 서빙 프로필 CMEK는 us 및 eu 멀티 리전에서 지원됩니다. global 리전은 지원되지 않습니다.
Interactions API에 CMEK를 설정하려면 다음을 수행합니다.
- 프로젝트에서 Cloud KMS API 및 Agent Platform API를 사용 설정합니다. 시작하기 전에를 참조하세요.
us또는eu멀티 리전에서 Cloud KMS 키를 만듭니다. 키링 및 키 만들기를 참조하세요.- Gemini Enterprise Agent Platform 서비스 에이전트에 키에 대한
roles/cloudkms.cryptoKeyEncrypterDecrypter역할을 부여합니다. Agent Platform 권한 부여를 참조하세요. scope를INTERACTIONS_API로,cmekConfig.encryptionSpec.kmsKeyName를 키로 설정하는 동일한 멀티 리전(us또는eu)에 서빙 프로필을 만듭니다.curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ "https://aiplatform.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/servingProfiles?servingProfileId=SERVING_PROFILE_ID" \ -d '{ "displayName": "Interactions API CMEK profile", "description": "CMEK for Interactions API", "scope": "INTERACTIONS_API", "cmekConfig": { "encryptionSpec": { "kmsKeyName": "projects/KMS_PROJECT_ID/locations/LOCATION/keyRings/KEY_RING_NAME/cryptoKeys/KEY_NAME" } } }'장기 실행 만들기 작업이 완료될 때까지 기다립니다(
"done": true). 서빙 프로필 관리, 업데이트, 삭제에 대한 자세한 내용은 서빙 프로필 만들기를 참조하세요.상호작용 요청을 서빙 프로필과 동일한
us또는eu멀티 리전으로 전송합니다.global엔드포인트에서 서빙 프로필 CMEK를 사용할 수 없습니다.- Google 생성형 AI SDK:
location="us"또는location="eu"(TypeScript/JavaScript의 경우location: "us"또는location: "eu")를 사용하여 클라이언트를 초기화합니다. - REST: 멀티 리전 엔드포인트
https://aiplatform.LOCATION.rep.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/interactions에 요청을 보냅니다. 여기서 LOCATION은us또는eu입니다.
키를 사용 중지하거나 서비스 에이전트의 액세스 권한을 취소하면 저장된 상호작용을 만들거나 읽는 요청이
FAILED_PRECONDITION오류와 함께 실패합니다.- Google 생성형 AI SDK:
고급 REST 워크플로
셸 기반 자동화, CI/CD 파이프라인 또는 Python 또는 TypeScript/JavaScript 런타임이 없는 환경의 경우 curl를 사용하여 HTTP를 통해 Interactions API를 직접 호출할 수 있습니다.
REST 엔드포인트
다음 Interactions API 엔드포인트에 POST 요청을 보냅니다.
POST https://aiplatform.googleapis.com/v1/projects/PROJECT_ID/locations/LOCATION/interactions
요청에서 다음 변수를 바꿉니다.
- PROJECT_ID: Google Cloud 프로젝트 ID입니다.
- LOCATION:
global로 설정합니다(또는 데이터 레지던시 또는 CMEK의 경우 멀티 리전 호스트https://aiplatform.LOCATION.rep.googleapis.com를 사용하여us또는eu).
환경 변수 및 인증 설정
다음 섹션에서 curl 예시를 실행하기 전에 프로젝트 ID, 대상 모델 또는 에이전트 ID, 애플리케이션 기본 사용자 인증 정보에서 생성된 OAuth 2.0 액세스 토큰을 내보냅니다.
PROJECT_ID="PROJECT_ID"
MODEL_ID="gemini-3.8-flash"
AGENT_ID="deep-research-preview-04-2026"
ACCESS_TOKEN=$(gcloud auth print-access-token)
동기 응답 형식
동기식 POST 요청은 고유한 상호작용 id, 실행 status, 대화 steps, 토큰 usage 메타데이터가 포함된 JSON interaction 객체를 반환합니다.
{
"id": "your-interaction-id",
"status": "completed",
"steps": [
{
"type": "model_output",
"content": [
{
"type": "text",
"text": "Serverless computing is a cloud execution model where the cloud provider dynamically manages the allocation and provisioning of servers, charging customers based on actual usage rather than pre-purchased capacity."
}
]
}
],
"usage": {
"total_tokens": 24751,
"total_input_tokens": 23894,
"total_output_tokens": 857
},
"created": "2026-05-08T10:44:43Z",
"updated": "2026-05-08T10:44:43Z",
"environment_id": "your-environment-id",
"object": "interaction"
}
멀티턴 스테이트풀(Stateful) 상호작용 계속하기
REST를 통해 저장된 대화를 계속하려면 이전 응답의 id를 JSON 요청 본문의 previous_interaction_id 필드에 전달합니다.
이 샘플을 사용해 보기 전에 PREVIOUS_INTERACTION_ID를 이전 상호작용에서 반환된 id로 바꿉니다.
curl -X POST "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"model": "'"${MODEL_ID}"'",
"store": true,
"previous_interaction_id": "PREVIOUS_INTERACTION_ID",
"input": [{
"type": "user_input",
"content": [{
"type": "text",
"text": "Can you elaborate on that?"
}]
}]
}'
서버 전송 이벤트로 출력 스트리밍
REST를 통해 증분 업데이트를 스트리밍하려면 JSON 요청 본문에 "stream": true를 포함합니다.
curl -X POST "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"model": "'"${MODEL_ID}"'",
"stream": true,
"input": [{
"type": "user_input",
"content": [{
"type": "text",
"text": "Write a long story about space travel."
}]
}]
}'
"stream": true가 설정되면 서버는 Transfer-Encoding: chunked 및 Content-Type: text/event-stream(서버 전송 이벤트)로 응답합니다. 스트림의 각 이벤트에는 event_type 및 단계 델타 콘텐츠가 포함된 JSON 페이로드가 포함된 data: 프리픽스가 포함됩니다. curl는 상호작용이 완료될 때까지 HTTP 연결을 자동으로 열어 두고 수신 청크를 실시간으로 stdout에 씁니다.
백그라운드에서 관리형 에이전트 실행
REST를 통해 비동기식으로 장기 실행 관리형 에이전트 태스크를 시작하려면 대상 agent를 지정하고 "background": true를 설정하고 "environment": "remote"를 구성합니다.
curl -X POST "https://aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/global/interactions" \
-H "Authorization: Bearer ${ACCESS_TOKEN}" \
-H "Content-Type: application/json" \
-d '{
"agent": "'"${AGENT_ID}"'",
"environment": "remote",
"background": true,
"input": [{
"type": "user_input",
"content": [{
"type": "text",
"text": "Analyze competitive positioning for commercial solar energy providers."
}]
}]
}'
다음 단계
Interactions API, 기본 제공 도구, 그라운딩에 대해 자세히 알아보려면 다음 리소스를 살펴보세요.
Interactions API 개요에서 주요 개념에 대해 자세히 알아보세요.
Interactions API 참조에서 요청 및 응답 스키마를 살펴보세요.
코드 실행, URL 컨텍스트, Google 검색을 사용한 그라운딩에 대해 자세히 알아보세요.
관리형 에이전트와 상호작용하고 Gemini Deep Research 에이전트를 사용하는 방법을 알아보세요.