Files API를 사용하여 미디어 파일을 업로드하고 상호작용할 수 있습니다. Files API를 사용하면 프로젝트당 최대 20GB의 파일을 저장할 수 있으며 파일당 최대 크기는 2GB입니다. 파일은 48시간 동안 저장됩니다. 이 기간에는 API를 사용하여 파일의 메타데이터를 가져올 수 있지만 파일을 다운로드할 수는 없습니다. Files API는 Gemini API를 사용할 수 있는 모든 지역에서 무료로 사용할 수 있습니다.
이 가이드에서는 Files API를 사용하여 미디어 파일을 사용하는 방법을 설명합니다. 기본 작업은 오디오 파일, 이미지, 동영상, 문서, 기타 지원되는 파일 형식에서 동일합니다.
파일 업로드
Files API를 사용하여 미디어 파일을 업로드할 수 있습니다. 총 요청 크기 (파일, 텍스트 프롬프트, 시스템 안내 등 포함)가 20MB를 초과하는 경우 항상 Files API를 사용하세요.
다음 코드는 파일을 업로드한 다음 generateContent
호출에서 이 파일을 사용합니다.
Python
from google import genai
client = genai.Client(api_key="GOOGLE_API_KEY")
myfile = client.files.upload(file="path/to/sample.mp3")
response = client.models.generate_content(
model="gemini-2.0-flash", contents=["Describe this audio clip", myfile]
)
print(response.text)
자바스크립트
import {
GoogleGenAI,
createUserContent,
createPartFromUri,
} from "@google/genai";
const ai = new GoogleGenAI({ apiKey: "GOOGLE_API_KEY" });
async function main() {
const myfile = await ai.files.upload({
file: "path/to/sample.mp3",
config: { mimeType: "audio/mpeg" },
});
const response = await ai.models.generateContent({
model: "gemini-2.0-flash",
contents: createUserContent([
createPartFromUri(myfile.uri, myfile.mimeType),
"Describe this audio clip",
]),
});
console.log(response.text);
}
await main();
Go
file, err := client.UploadFileFromPath(ctx, "path/to/sample.mp3", nil)
if err != nil {
log.Fatal(err)
}
defer client.DeleteFile(ctx, file.Name)
model := client.GenerativeModel("gemini-2.0-flash")
resp, err := model.GenerateContent(ctx,
genai.FileData{URI: file.URI},
genai.Text("Describe this audio clip"))
if err != nil {
log.Fatal(err)
}
printResponse(resp)
REST
AUDIO_PATH="path/to/sample.mp3"
MIME_TYPE=$(file -b --mime-type "${AUDIO_PATH}")
NUM_BYTES=$(wc -c < "${AUDIO_PATH}")
DISPLAY_NAME=AUDIO
tmp_header_file=upload-header.tmp
# Initial resumable request defining metadata.
# The upload url is in the response headers dump them to a file.
curl "${BASE_URL}/upload/v1beta/files?key=${GOOGLE_API_KEY}" \
-D upload-header.tmp \
-H "X-Goog-Upload-Protocol: resumable" \
-H "X-Goog-Upload-Command: start" \
-H "X-Goog-Upload-Header-Content-Length: ${NUM_BYTES}" \
-H "X-Goog-Upload-Header-Content-Type: ${MIME_TYPE}" \
-H "Content-Type: application/json" \
-d "{'file': {'display_name': '${DISPLAY_NAME}'}}" 2> /dev/null
upload_url=$(grep -i "x-goog-upload-url: " "${tmp_header_file}" | cut -d" " -f2 | tr -d "\r")
rm "${tmp_header_file}"
# Upload the actual bytes.
curl "${upload_url}" \
-H "Content-Length: ${NUM_BYTES}" \
-H "X-Goog-Upload-Offset: 0" \
-H "X-Goog-Upload-Command: upload, finalize" \
--data-binary "@${AUDIO_PATH}" 2> /dev/null > file_info.json
file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri
# Now generate content using that file
curl "https://generativelanguage.googleapis.com/v1beta/models/gemini-2.0-flash:generateContent?key=$GOOGLE_API_KEY" \
-H 'Content-Type: application/json' \
-X POST \
-d '{
"contents": [{
"parts":[
{"text": "Describe this audio clip"},
{"file_data":{"mime_type": "${MIME_TYPE}", "file_uri": '$file_uri'}}]
}]
}' 2> /dev/null > response.json
cat response.json
echo
jq ".candidates[].content.parts[].text" response.json
파일 메타데이터 가져오기
API가 업로드된 파일을 성공적으로 저장했는지 확인하고 files.get
를 호출하여 메타데이터를 가져올 수 있습니다.
Python
myfile = client.files.upload(file='path/to/sample.mp3')
file_name = myfile.name
myfile = client.files.get(name=file_name)
print(myfile)
자바스크립트
const myfile = await ai.files.upload({
file: "path/to/sample.mp3",
config: { mimeType: "audio/mpeg" },
});
const fileName = myfile.name;
const fetchedFile = await ai.files.get({ name: fileName });
console.log(fetchedFile);
Go
file, err := client.UploadFileFromPath(ctx, "path/to/sample.mp3", nil)
if err != nil {
log.Fatal(err)
}
gotFile, err := client.GetFile(ctx, file.Name)
if err != nil {
log.Fatal(err)
}
fmt.Println("Got file:", gotFile.Name)
REST
# file_info.json was created in the upload example
name=$(jq ".file.name" file_info.json)
# Get the file of interest to check state
curl https://generativelanguage.googleapis.com/v1beta/files/$name > file_info.json
# Print some information about the file you got
name=$(jq ".file.name" file_info.json)
echo name=$name
file_uri=$(jq ".file.uri" file_info.json)
echo file_uri=$file_uri
업로드된 파일 목록
Files API를 사용하여 여러 파일을 업로드할 수 있습니다. 다음 코드는 업로드된 모든 파일의 목록을 가져옵니다.
Python
print('My files:')
for f in client.files.list():
print(' ', f.name)
자바스크립트
const listResponse = await ai.files.list({ config: { pageSize: 10 } });
for await (const file of listResponse) {
console.log(file.name);
}
Go
iter := client.ListFiles(ctx)
for {
ifile, err := iter.Next()
if err == iterator.Done {
break
}
if err != nil {
log.Fatal(err)
}
fmt.Println(ifile.Name)
}
REST
echo "My files: "
curl "https://generativelanguage.googleapis.com/v1beta/files?key=$GOOGLE_API_KEY"
업로드된 파일 삭제하기
파일은 48시간 후에 자동으로 삭제됩니다. 업로드된 파일을 수동으로 삭제할 수도 있습니다.
Python
myfile = client.files.upload(file='path/to/sample.mp3')
client.files.delete(name=myfile.name)
자바스크립트
const myfile = await ai.files.upload({
file: "path/to/sample.mp3",
config: { mimeType: "audio/mpeg" },
});
const fileName = myfile.name;
await ai.files.delete({ name: fileName });
Go
file, err := client.UploadFileFromPath(ctx, "path/to/sample.mp3", nil)
if err != nil {
log.Fatal(err)
}
client.DeleteFile(ctx, file.Name)
REST
curl --request "DELETE" https://generativelanguage.googleapis.com/v1beta/files/$name?key=$GOOGLE_API_KEY
다음 단계
이 가이드에서는 Files API를 사용하여 파일을 사용하는 방법을 보여줍니다. 파일로 프롬프트하는 방법에 관한 자세한 내용은 파일 프롬프트 전략을 참고하세요.