Gemini API 코드 실행 기능을 통해 모델은 Python 코드를 생성 및 실행하고 최종 출력을 도출할 때까지 결과를 반복적으로 학습합니다. 이 코드 실행 기능을 사용하면 코드 기반 추론의 이점을 활용하며 텍스트 출력을 생성하는 애플리케이션을 빌드할 수 있습니다. 예를 들어 방정식을 풀거나 텍스트를 처리하는 애플리케이션에서 코드 실행을 사용할 수 있습니다.
Gemini API는 함수 호출과 유사하게 코드 실행을 도구로 제공합니다. 코드 실행을 도구로 추가하면 모델은 이를 사용할 시점을 결정합니다.
지원되는 모델
제한사항
- 이 기능은 파일 I/O를 지원하지 않습니다.
- 코드 실행은 타임아웃되기 전까지 최대 30초 동안 실행될 수 있습니다.
예시 문법
curl
PROJECT_ID = myproject REGION = us-central1 MODEL_ID = gemini-2.0-flash-001 https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \ -d '{ "contents": [{ ... }], "tools": [{ "code_execution": {} }] }'
매개변수 목록
구현 세부정보는 예시를 참고하세요.
Python
코드 실행을 사용 설정하려면 요청에 코드 실행 tool
을 지정합니다.
CodeExecution
모델에서 생성된 코드를 실행하고 결과를 모델에 자동으로 반환하는 도구입니다. 이 도구의 입력과 출력인 ExecutableCode 및 CodeExecutionResult도 참조하세요.
Part
| 선택사항:
실행 목적으로 모델에서 생성된 코드입니다.
|
| 선택사항:
[ExecutableCode] 실행 결과입니다.
|
ExecutableCode
| 필수:
생성된 지원됨:
|
| 필수:
실행할 코드입니다.
|
CodeExecutionResult
| 필수:
코드 실행의 결과입니다. 가능한 결과:
|
| 필수:
코드 실행에 성공하면 |
예시
다음은 쿼리 및 함수 선언을 모델에 제출하는 방법을 보여주는 그림입니다.
기본 사용 사례
curl
PROJECT_ID = myproject REGION = us-central1 MODEL_ID = gemini-2.0-flash-001 curl -X POST \ -H "Authorization: Bearer $(gcloud auth print-access-token)" \ -H "Content-Type: application/json" \ https://${REGION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${REGION}/publishers/google/models/${MODEL_ID}:generateContent \ -d '{ "contents": [{ "role": "user", "parts": [{ "text": "Calculate 20th fibonacci number. Then find the nearest palindrome to it." }] }], "tools": [{'codeExecution': {}}], }'
Python
from google import genai from google.genai.types import Tool, ToolCodeExecution, GenerateContentConfig client = genai.Client() model_id = "gemini-2.0-flash-001" code_execution_tool = Tool( code_execution=ToolCodeExecution() ) response = client.models.generate_content( model=model_id, contents="Calculate 20th fibonacci number. Then find the nearest palindrome to it.", config=GenerateContentConfig( tools=[code_execution_tool], temperature=0, ), ) for part in response.candidates[0].content.parts: if part.executable_code: print(part.executable_code) if part.code_execution_result: print(part.code_execution_result) # Example response: # code='...' language='PYTHON' # outcome='OUTCOME_OK' output='The 20th Fibonacci number is: 6765\n' # code='...' language='PYTHON' # outcome='OUTCOME_OK' output='Lower Palindrome: 6666\nHigher Palindrome: 6776\nNearest Palindrome to 6765: 6776\n'
모델에서 코드 실행 사용 설정
기본 코드 실행을 사용 설정하려면 코드 실행을 참조하세요.
다음 단계
- Gemini API에 대해 자세히 알아보기
- 함수 호출에 대해 자세히 알아보기
- Gemini로 콘텐츠 생성 자세히 알아보기