코드 실행은 모델이 Python 코드를 생성하고 실행할 수 있도록 지원하는 도구입니다. 모델은 최종 출력을 도출할 때까지 코드 실행 결과를 반복적으로 학습할 수 있습니다.
코드 실행을 사용하여 코드 기반 추론의 이점을 활용하고 텍스트 출력을 생성하는 기능을 빌드할 수 있습니다. 예를 들어 코드 실행을 사용하여 방정식을 풀거나 텍스트를 처리할 수 있습니다. 코드 실행 환경에 포함된 라이브러리를 사용하여 더 전문적인 작업을 실행할 수도 있습니다.
모델에 제공하는 모든 도구와 마찬가지로 모델은 코드 실행을 사용할 시점을 결정합니다.
코드 실행과 함수 호출 비교
코드 실행과 함수 호출은 비슷한 특성을 지닙니다. 일반적으로 모델이 사용 사례를 처리할 수 있는 경우 코드 실행을 사용하는 것이 좋습니다. 코드 실행은 사용 설정만 하면 되므로 사용하기에 간편합니다.
다음은 코드 실행과 함수 호출의 추가적인 차이점입니다.
코드 실행 | 함수 호출 |
---|---|
모델이 Python 코드를 작성하고 실행하여 결과를 반환하도록 하려면 코드 실행을 사용하세요. | 로컬로 실행하려는 자체 함수가 이미 있는 경우 함수 호출을 사용하세요. |
코드 실행을 사용하면 모델이 고정되고 격리된 환경의 API 백엔드에서 코드를 실행할 수 있습니다. | 함수 호출을 사용하면 원하는 환경에서 모델이 요청하는 함수를 실행할 수 있습니다. |
코드 실행은 단일 요청으로 처리됩니다. 채팅 기능과 함께 코드 실행을 선택적으로 사용할 수 있지만 필수는 아닙니다. | 함수 호출에는 각 함수 호출에서 출력을 다시 보내기 위한 추가 요청이 필요합니다. 따라서 채팅 기능을 사용해야 합니다. |
지원되는 모델
gemini-2.5-pro
gemini-2.5-flash
gemini-2.5-flash-lite
gemini-2.0-flash-001
(및 자동 업데이트된 별칭gemini-2.0-flash
)gemini-2.0-flash-live-preview-04-09
코드 실행 사용
텍스트 전용 입력과 멀티모달 입력 모두에 코드 실행을 사용할 수 있지만 대답은 항상 텍스트 또는 코드만으로 제공됩니다.
시작하기 전에
Gemini API 제공업체를 클릭하여 이 페이지에서 제공업체별 콘텐츠와 코드를 확인합니다. |
아직 완료하지 않았다면 Firebase 프로젝트를 설정하고, 앱을 Firebase에 연결하고, SDK를 추가하고, 선택한 Gemini API 제공업체의 백엔드 서비스를 초기화하고, GenerativeModel
인스턴스를 만드는 방법을 설명하는 시작 가이드를 완료합니다.
프롬프트를 테스트하고 반복하며 생성된 코드 스니펫을 가져오려면 Google AI Studio를 사용하는 것이 좋습니다.
코드 실행 사용 설정
이 샘플을 사용해 보기 전에 이 가이드의 시작하기 전에 섹션을 완료하여 프로젝트와 앱을 설정하세요. 이 섹션에서는 선택한 Gemini API 제공업체의 버튼을 클릭하여 이 페이지에 제공업체별 콘텐츠가 표시되도록 합니다. |
GenerativeModel
인스턴스를 만들 때 모델이 대답을 생성하는 데 사용할 수 있는 도구로 CodeExecution
을 제공합니다. 이를 통해 모델이 Python 코드를 생성하고 실행할 수 있습니다.
Swift
import FirebaseAI
// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(
modelName: "GEMINI_MODEL_NAME",
// Provide code execution as a tool that the model can use to generate its response.
tools: [.codeExecution()]
)
let prompt = """
What is the sum of the first 50 prime numbers?
Generate and run code for the calculation, and make sure you get all 50.
"""
let response = try await model.generateContent(prompt)
guard let candidate = response.candidates.first else {
print("No candidates in response.")
return
}
for part in candidate.content.parts {
if let textPart = part as? TextPart {
print("Text = \(textPart.text)")
} else if let executableCode = part as? ExecutableCodePart {
print("Code = \(executableCode.code), Language = \(executableCode.language)")
} else if let executionResult = part as? CodeExecutionResultPart {
print("Outcome = \(executionResult.outcome), Result = \(executionResult.output ?? "no output")")
}
}
Kotlin
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "GEMINI_MODEL_NAME",
// Provide code execution as a tool that the model can use to generate its response.
tools = listOf(Tool.codeExecution())
)
val prompt = "What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50."
val response = model.generateContent(prompt)
response.candidates.first().content.parts.forEach {
if(it is TextPart) {
println("Text = ${it.text}")
}
if(it is ExecutableCodePart) {
println("Code = ${it.code}, Language = ${it.language}")
}
if(it is CodeExecutionResultPart) {
println("Outcome = ${it.outcome}, Result = ${it.output}")
}
}
Java
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("GEMINI_MODEL_NAME",
null,
null,
// Provide code execution as a tool that the model can use to generate its response.
List.of(Tool.codeExecution()));
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
String text = "What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50.";
Content prompt = new Content.Builder()
.addText(text)
.build();
ListenableFuture response = model.generateContent(prompt);
Futures.addCallback(response, new FutureCallback() {
@Override
public void onSuccess(GenerateContentResponse response) {
// Access the first candidate's content parts
List parts = response.getCandidates().get(0).getContent().getParts();
for (Part part : parts) {
if (part instanceof TextPart) {
TextPart textPart = (TextPart) part;
System.out.println("Text = " + textPart.getText());
} else if (part instanceof ExecutableCodePart) {
ExecutableCodePart codePart = (ExecutableCodePart) part;
System.out.println("Code = " + codePart.getCode() + ", Language = " + codePart.getLanguage());
} else if (part instanceof CodeExecutionResultPart) {
CodeExecutionResultPart resultPart = (CodeExecutionResultPart) part;
System.out.println("Outcome = " + resultPart.getOutcome() + ", Result = " + resultPart.getOutput());
}
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";
// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(
ai,
{
model: "GEMINI_MODEL_NAME",
// Provide code execution as a tool that the model can use to generate its response.
tools: [{ codeExecution: {} }]
}
);
const prompt = "What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50."
const result = await model.generateContent(prompt);
const response = await result.response;
const parts = response.candidates?.[0].content.parts;
if (parts) {
parts.forEach((part) => {
if (part.text) {
console.log(`Text: ${part.text}`);
} else if (part.executableCode) {
console.log(
`Code: ${part.executableCode.code}, Language: ${part.executableCode.language}`
);
} else if (part.codeExecutionResult) {
console.log(
`Outcome: ${part.codeExecutionResult.outcome}, Result: ${part.codeExecutionResult.output}`
);
}
});
}
Dart
Flutter 지원은 다음 출시에서 제공될 예정입니다.
Unity
Unity 지원은 다음 출시에서 제공될 예정입니다.
사용 사례 및 앱에 적합한 모델과 선택적으로 모델 위치를 선택하는 방법을 알아보세요.
채팅에서 코드 실행 사용
채팅의 일부로 코드 실행을 사용할 수도 있습니다.
Swift
import FirebaseAI
// Initialize the Gemini Developer API backend service
let ai = FirebaseAI.firebaseAI(backend: .googleAI())
// Create a `GenerativeModel` instance with a model that supports your use case
let model = ai.generativeModel(
modelName: "GEMINI_MODEL_NAME",
// Provide code execution as a tool that the model can use to generate its response.
tools: [.codeExecution()]
)
let prompt = """
What is the sum of the first 50 prime numbers?
Generate and run code for the calculation, and make sure you get all 50.
"""
let chat = model.startChat()
let response = try await chat.sendMessage(prompt)
guard let candidate = response.candidates.first else {
print("No candidates in response.")
return
}
for part in candidate.content.parts {
if let textPart = part as? TextPart {
print("Text = \(textPart.text)")
} else if let executableCode = part as? ExecutableCodePart {
print("Code = \(executableCode.code), Language = \(executableCode.language)")
} else if let executionResult = part as? CodeExecutionResultPart {
print("Outcome = \(executionResult.outcome), Result = \(executionResult.output ?? "no output")")
}
}
Kotlin
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
val model = Firebase.ai(backend = GenerativeBackend.googleAI()).generativeModel(
modelName = "GEMINI_MODEL_NAME",
// Provide code execution as a tool that the model can use to generate its response.
tools = listOf(Tool.codeExecution())
)
val prompt = "What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50."
val chat = model.startChat()
val response = chat.sendMessage(prompt)
response.candidates.first().content.parts.forEach {
if(it is TextPart) {
println("Text = ${it.text}")
}
if(it is ExecutableCodePart) {
println("Code = ${it.code}, Language = ${it.language}")
}
if(it is CodeExecutionResultPart) {
println("Outcome = ${it.outcome}, Result = ${it.output}")
}
}
Java
// Initialize the Gemini Developer API backend service
// Create a `GenerativeModel` instance with a model that supports your use case
GenerativeModel ai = FirebaseAI.getInstance(GenerativeBackend.googleAI())
.generativeModel("GEMINI_MODEL_NAME",
null,
null,
// Provide code execution as a tool that the model can use to generate its response.
List.of(Tool.codeExecution()));
// Use the GenerativeModelFutures Java compatibility layer which offers
// support for ListenableFuture and Publisher APIs
GenerativeModelFutures model = GenerativeModelFutures.from(ai);
String text = "What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50.";
Content prompt = new Content.Builder()
.addText(text)
.build();
ChatFutures chat = model.startChat();
ListenableFuture response = chat.sendMessage(prompt);
Futures.addCallback(response, new FutureCallback() {
@Override
public void onSuccess(GenerateContentResponse response) {
// Access the first candidate's content parts
List parts = response.getCandidates().get(0).getContent().getParts();
for (Part part : parts) {
if (part instanceof TextPart) {
TextPart textPart = (TextPart) part;
System.out.println("Text = " + textPart.getText());
} else if (part instanceof ExecutableCodePart) {
ExecutableCodePart codePart = (ExecutableCodePart) part;
System.out.println("Code = " + codePart.getCode() + ", Language = " + codePart.getLanguage());
} else if (part instanceof CodeExecutionResultPart) {
CodeExecutionResultPart resultPart = (CodeExecutionResultPart) part;
System.out.println("Outcome = " + resultPart.getOutcome() + ", Result = " + resultPart.getOutput());
}
}
}
@Override
public void onFailure(Throwable t) {
t.printStackTrace();
}
}, executor);
Web
import { initializeApp } from "firebase/app";
import { getAI, getGenerativeModel, GoogleAIBackend } from "firebase/ai";
// TODO(developer) Replace the following with your app's Firebase configuration
// See: https://firebase.google.com/docs/web/learn-more#config-object
const firebaseConfig = {
// ...
};
// Initialize FirebaseApp
const firebaseApp = initializeApp(firebaseConfig);
// Initialize the Gemini Developer API backend service
const ai = getAI(firebaseApp, { backend: new GoogleAIBackend() });
// Create a `GenerativeModel` instance with a model that supports your use case
const model = getGenerativeModel(
ai,
{
model: "GEMINI_MODEL_NAME",
// Provide code execution as a tool that the model can use to generate its response.
tools: [{ codeExecution: {} }]
}
);
const prompt = "What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50."
const chat = model.startChat()
const result = await chat.sendMessage(prompt);
const response = await result.response;
const parts = response.candidates?.[0].content.parts;
if (parts) {
parts.forEach((part) => {
if (part.text) {
console.log(`Text: ${part.text}`);
} else if (part.executableCode) {
console.log(
`Code: ${part.executableCode.code}, Language: ${part.executableCode.language}`
);
} else if (part.codeExecutionResult) {
console.log(
`Outcome: ${part.codeExecutionResult.outcome}, Result: ${part.codeExecutionResult.output}`
);
}
});
}
Dart
Flutter 지원은 다음 출시에서 제공될 예정입니다.
Unity
Unity 지원은 다음 출시에서 제공될 예정입니다.
사용 사례 및 앱에 적합한 모델과 선택적으로 모델 위치를 선택하는 방법을 알아보세요.
가격 책정
코드 실행을 사용 설정하고 모델의 도구로 제공하는 데에는 추가 비용이 발생하지 않습니다. 모델에서 코드 실행을 사용하기로 결정한 경우 사용 중인 Gemini 모델에 따라 입력 및 출력 토큰의 현재 요율로 비용이 청구됩니다.
다음 다이어그램은 코드 실행의 청구 모델을 보여줍니다.
모델이 코드 실행을 사용할 때 토큰 비용이 청구되는 방식은 다음과 같습니다.
원래 프롬프트는 한 번 청구됩니다. 이 토큰은 중간 토큰으로 라벨이 지정되며 입력 토큰으로 청구됩니다.
생성된 코드와 실행된 코드의 결과는 다음과 같이 청구됩니다.
코드 실행 중에 사용되는 경우 중간 토큰으로 라벨이 지정되며 입력 토큰으로 청구됩니다.
최종 대답의 일부로 포함되면 출력 토큰으로 청구됩니다.
최종 응답의 최종 요약은 출력 토큰으로 청구됩니다.
Gemini API에는 API 응답에 중간 토큰 수가 포함되므로 초기 프롬프트 이상으로 입력 토큰에 요금이 청구되는 이유를 알 수 있습니다.
생성된 코드에는 텍스트 및 멀티모달 출력(예: 이미지)이 모두 포함될 수 있습니다.
제한사항 및 권장사항
모델은 Python 코드만 생성하고 실행할 수 있습니다. 미디어 파일과 같은 다른 아티팩트는 반환할 수 없습니다.
코드 실행은 타임아웃되기 전까지 최대 30초 동안 실행될 수 있습니다.
일부 경우에 코드 실행을 사용 설정하면 모델 출력의 다른 영역(예: 스토리 작성)에서 성능이 저하될 수 있습니다.
코드 실행 도구는 파일 URI를 입력/출력으로 지원하지 않습니다. 하지만 코드 실행 도구는 파일 입력과 그래프 출력을 인라인 바이트로 지원합니다. 이러한 입력 및 출력 기능을 사용하면 CSV 및 텍스트 파일을 업로드하고, 파일에 관해 질문하고, 코드 실행 결과의 일부로 Matplotlib 그래프를 생성할 수 있습니다. 인라인 바이트에 지원되는 MIME 유형은
.cpp
,.csv
,.java
,.jpeg
,.js
,.png
,.py
,.ts
,.xml
입니다.
지원되는 라이브러리
코드 실행 환경에는 다음 라이브러리가 포함됩니다. 사용자의 고유 라이브러리는 설치할 수 없습니다.
Firebase AI Logic 사용 경험에 관한 의견 보내기