Gemini 네이티브 형식
curl --request POST \
--url https://api.gravitex.ai/v1beta/models/{model}:generateContent \
--header 'Content-Type: application/json' \
--data '
{
"contents": [
{}
],
"generationConfig": {},
"systemInstruction": {},
"safetySettings": [
{}
],
"tools": [
{}
],
"toolConfig": {},
"cachedContent": "<string>"
}
'import requests
url = "https://api.gravitex.ai/v1beta/models/{model}:generateContent"
payload = {
"contents": [{}],
"generationConfig": {},
"systemInstruction": {},
"safetySettings": [{}],
"tools": [{}],
"toolConfig": {},
"cachedContent": "<string>"
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
contents: [{}],
generationConfig: {},
systemInstruction: {},
safetySettings: [{}],
tools: [{}],
toolConfig: {},
cachedContent: '<string>'
})
};
fetch('https://api.gravitex.ai/v1beta/models/{model}:generateContent', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.gravitex.ai/v1beta/models/{model}:generateContent",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'contents' => [
[
]
],
'generationConfig' => [
],
'systemInstruction' => [
],
'safetySettings' => [
[
]
],
'tools' => [
[
]
],
'toolConfig' => [
],
'cachedContent' => '<string>'
]),
CURLOPT_HTTPHEADER => [
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.gravitex.ai/v1beta/models/{model}:generateContent"
payload := strings.NewReader("{\n \"contents\": [\n {}\n ],\n \"generationConfig\": {},\n \"systemInstruction\": {},\n \"safetySettings\": [\n {}\n ],\n \"tools\": [\n {}\n ],\n \"toolConfig\": {},\n \"cachedContent\": \"<string>\"\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.gravitex.ai/v1beta/models/{model}:generateContent")
.header("Content-Type", "application/json")
.body("{\n \"contents\": [\n {}\n ],\n \"generationConfig\": {},\n \"systemInstruction\": {},\n \"safetySettings\": [\n {}\n ],\n \"tools\": [\n {}\n ],\n \"toolConfig\": {},\n \"cachedContent\": \"<string>\"\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.gravitex.ai/v1beta/models/{model}:generateContent")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{\n \"contents\": [\n {}\n ],\n \"generationConfig\": {},\n \"systemInstruction\": {},\n \"safetySettings\": [\n {}\n ],\n \"tools\": [\n {}\n ],\n \"toolConfig\": {},\n \"cachedContent\": \"<string>\"\n}"
response = http.request(request)
puts response.read_body{
"candidates": [
{
"content": {
"parts": [{"text": "Response text"}],
"role": "model"
},
"finishReason": "STOP",
"index": 0,
"safetyRatings": []
}
],
"usageMetadata": {
"promptTokenCount": 10,
"candidatesTokenCount": 20,
"totalTokenCount": 30,
"thoughtsTokenCount": 0,
"cachedContentTokenCount": 0
},
"modelVersion": "gemini-2.5-pro",
"createTime": "2025-01-01T00:00:00Z"
}
대화 및 텍스트
Gemini 네이티브 형식
Google Gemini 네이티브 형식으로 GravitexAI 호출
POST
/
v1beta
/
models
/
{model}
:generateContent
Gemini 네이티브 형식
curl --request POST \
--url https://api.gravitex.ai/v1beta/models/{model}:generateContent \
--header 'Content-Type: application/json' \
--data '
{
"contents": [
{}
],
"generationConfig": {},
"systemInstruction": {},
"safetySettings": [
{}
],
"tools": [
{}
],
"toolConfig": {},
"cachedContent": "<string>"
}
'import requests
url = "https://api.gravitex.ai/v1beta/models/{model}:generateContent"
payload = {
"contents": [{}],
"generationConfig": {},
"systemInstruction": {},
"safetySettings": [{}],
"tools": [{}],
"toolConfig": {},
"cachedContent": "<string>"
}
headers = {"Content-Type": "application/json"}
response = requests.post(url, json=payload, headers=headers)
print(response.text)const options = {
method: 'POST',
headers: {'Content-Type': 'application/json'},
body: JSON.stringify({
contents: [{}],
generationConfig: {},
systemInstruction: {},
safetySettings: [{}],
tools: [{}],
toolConfig: {},
cachedContent: '<string>'
})
};
fetch('https://api.gravitex.ai/v1beta/models/{model}:generateContent', options)
.then(res => res.json())
.then(res => console.log(res))
.catch(err => console.error(err));<?php
$curl = curl_init();
curl_setopt_array($curl, [
CURLOPT_URL => "https://api.gravitex.ai/v1beta/models/{model}:generateContent",
CURLOPT_RETURNTRANSFER => true,
CURLOPT_ENCODING => "",
CURLOPT_MAXREDIRS => 10,
CURLOPT_TIMEOUT => 30,
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
CURLOPT_CUSTOMREQUEST => "POST",
CURLOPT_POSTFIELDS => json_encode([
'contents' => [
[
]
],
'generationConfig' => [
],
'systemInstruction' => [
],
'safetySettings' => [
[
]
],
'tools' => [
[
]
],
'toolConfig' => [
],
'cachedContent' => '<string>'
]),
CURLOPT_HTTPHEADER => [
"Content-Type: application/json"
],
]);
$response = curl_exec($curl);
$err = curl_error($curl);
curl_close($curl);
if ($err) {
echo "cURL Error #:" . $err;
} else {
echo $response;
}package main
import (
"fmt"
"strings"
"net/http"
"io"
)
func main() {
url := "https://api.gravitex.ai/v1beta/models/{model}:generateContent"
payload := strings.NewReader("{\n \"contents\": [\n {}\n ],\n \"generationConfig\": {},\n \"systemInstruction\": {},\n \"safetySettings\": [\n {}\n ],\n \"tools\": [\n {}\n ],\n \"toolConfig\": {},\n \"cachedContent\": \"<string>\"\n}")
req, _ := http.NewRequest("POST", url, payload)
req.Header.Add("Content-Type", "application/json")
res, _ := http.DefaultClient.Do(req)
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
fmt.Println(string(body))
}HttpResponse<String> response = Unirest.post("https://api.gravitex.ai/v1beta/models/{model}:generateContent")
.header("Content-Type", "application/json")
.body("{\n \"contents\": [\n {}\n ],\n \"generationConfig\": {},\n \"systemInstruction\": {},\n \"safetySettings\": [\n {}\n ],\n \"tools\": [\n {}\n ],\n \"toolConfig\": {},\n \"cachedContent\": \"<string>\"\n}")
.asString();require 'uri'
require 'net/http'
url = URI("https://api.gravitex.ai/v1beta/models/{model}:generateContent")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request.body = "{\n \"contents\": [\n {}\n ],\n \"generationConfig\": {},\n \"systemInstruction\": {},\n \"safetySettings\": [\n {}\n ],\n \"tools\": [\n {}\n ],\n \"toolConfig\": {},\n \"cachedContent\": \"<string>\"\n}"
response = http.request(request)
puts response.read_body{
"candidates": [
{
"content": {
"parts": [{"text": "Response text"}],
"role": "model"
},
"finishReason": "STOP",
"index": 0,
"safetyRatings": []
}
],
"usageMetadata": {
"promptTokenCount": 10,
"candidatesTokenCount": 20,
"totalTokenCount": 30,
"thoughtsTokenCount": 0,
"cachedContentTokenCount": 0
},
"modelVersion": "gemini-2.5-pro",
"createTime": "2025-01-01T00:00:00Z"
}
소개
Gemini Native API는 Google Gemini의 요청 및 응답 형식을 사용합니다. Google 공식 클라이언트(예:google-generativeai SDK) 또는 Gemini 데이터 구조를 직접 다루어야 할 때 적합합니다. API는 Gemini 사양을 따르며 사고 모드, 멀티모달 입력, 도구 호출, Google Search(Grounding), 컨텍스트 캐싱, 이미지 생성 등 전체 기능을 지원합니다.
OpenAI 호환 클라이언트(예: OpenAI SDK)로 Gemini를 사용하는 경우 Gemini OpenAI 형식(Chat)을 참조하세요. 다른 모델은 OpenAI Chat Completions를 사용하세요.
OpenAI 형식과의 차이
| 항목 | Gemini Native | OpenAI 호환 (/v1/chat/completions) |
|---|---|---|
| 메시지 구조 | contents[].parts[] (text / inlineData / fileData) | messages[].content |
| 역할 | user / model | user / assistant / system |
| 시스템 프롬프트 | systemInstruction.parts | role=system인 messages |
| 스트리밍 | streamGenerateContent?alt=sse | stream: true |
| 사고 모드 | generationConfig.thinkingConfig 또는 모델 접미사 | 모델 접미사(예: -thinking) |
API 엔드포인트
| 기능 | Method | Path |
|---|---|---|
| 텍스트 생성(비스트리밍) | POST | /v1beta/models/{model}:generateContent |
| 텍스트 생성(스트리밍) | POST | /v1beta/models/{model}:streamGenerateContent?alt=sse |
| 단일 Embedding | POST | /v1beta/models/{model}:embedContent |
| 일괄 Embedding | POST | /v1beta/models/{model}:batchEmbedContents |
{model}을 실제 모델 ID(예: gemini-2.5-pro, gemini-3-pro-preview)로 바꿉니다.
인증
다음 중 하나를 사용할 수 있습니다:string
Bearer 토큰:
Bearer sk-xxxxxxxxxx (권장, 다른 GravitexAI 엔드포인트와 동일)string
Google 스타일 API 키:
x-goog-api-key: sk-xxxxxxxxxx?key=sk-xxxxxxxxxx.
요청 매개변수
generateContent / streamGenerateContent
array
필수
대화 내용 목록. 각 항목은
role(user 또는 model)과 parts를 가집니다. 각 part는 {"text": "..."}, {"inlineData": {"mimeType": "...", "data": "base64..."}}, 또는 {"fileData": {"mimeType": "...", "fileUri": "gs://..."}}일 수 있습니다.object
생성 설정.
temperature: 0–2, 무작위성topP: nucleus 샘플링topK: top-K 샘플링maxOutputTokens: 최대 출력 토큰 수stopSequences: 중지 시퀀스responseMimeType: 예:text/plainresponseModalities: 예:["TEXT"]또는["IMAGE"]thinkingConfig: 사고 모드(아래 참조)imageConfig: 이미지 생성 설정(아래 참조)
object
시스템 지시:
{"parts": [{"text": "..."}]}.array
안전 수준, 예:
[{"category": "HARM_CATEGORY_HARASSMENT", "threshold": "OFF"}].array
도구 선언(function calling), 고급 기능 참조.
object
도구 설정, 예:
functionCallingConfig.mode: AUTO / ANY / NONE.string
API가 반환한 컨텍스트 캐싱 ID; 캐시된 컨텍스트 재사용에 사용.
응답 형식
비스트리밍generateContent는 JSON을 반환합니다:
{
"candidates": [
{
"content": {
"parts": [{"text": "Response text"}],
"role": "model"
},
"finishReason": "STOP",
"index": 0,
"safetyRatings": []
}
],
"usageMetadata": {
"promptTokenCount": 10,
"candidatesTokenCount": 20,
"totalTokenCount": 30,
"thoughtsTokenCount": 0,
"cachedContentTokenCount": 0
},
"modelVersion": "gemini-2.5-pro",
"createTime": "2025-01-01T00:00:00Z"
}
data: 로 시작하며 JSON 조각(예: candidates[].content.parts)을 포함합니다.
기본 예시
- cURL (non-streaming)
- cURL (streaming)
- Python (google-generativeai)
- Node.js
curl -X POST "https://api.gravitex.ai/v1beta/models/gemini-2.5-pro:generateContent" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-xxxxxxxxxx" \
-d '{
"contents": [
{"role": "user", "parts": [{"text": "Describe AI in one sentence"}]}
],
"generationConfig": {
"temperature": 0.7,
"maxOutputTokens": 1024
}
}'
curl -N -X POST "https://api.gravitex.ai/v1beta/models/gemini-2.5-pro:streamGenerateContent?alt=sse" \
-H "Content-Type: application/json" \
-H "Authorization: Bearer sk-xxxxxxxxxx" \
-d '{
"contents": [
{"role": "user", "parts": [{"text": "Describe AI in one sentence"}]}
],
"generationConfig": {"maxOutputTokens": 1024}
}'
import google.generativeai as genai
genai.configure(
api_key="sk-xxxxxxxxxx",
transport="rest",
client_options={"api_endpoint": "https://api.gravitex.ai"}
)
model = genai.GenerativeModel("gemini-2.5-pro")
response = model.generate_content("Describe AI in one sentence")
print(response.text)
const { GoogleGenerativeAI } = require("@google/generative-ai");
const genAI = new GoogleGenerativeAI("sk-xxxxxxxxxx");
genAI.apiKey = "sk-xxxxxxxxxx";
// If the SDK supports a custom baseUrl, set it to https://api.gravitex.ai
const model = genAI.getGenerativeModel({ model: "gemini-2.5-pro" });
const result = await model.generateContent("Describe AI in one sentence");
const text = result.response.text();
console.log(text);
기본적으로
google-generativeai는 Google API를 호출합니다. GravitexAI를 사용하려면 client_options 또는 환경 변수를 통해 api_endpoint를 https://api.gravitex.ai로 설정하세요. 자세한 내용은 SDK 문서를 참조하세요.고급 기능
사고 모드
세 가지 방식으로 지원됩니다:- generationConfig.thinkingConfig (Gemini 2.5 Pro):
thinkingBudget(토큰 수) 사용 - thinkingConfig.thinkingLevel (Gemini 3 Pro):
LOW/HIGH사용 - 모델 접미사:
-thinking,-thinking-8192,-nothinking,-thinking-low,-thinking-high
- thinkingBudget (2.5 Pro)
- thinkingLevel (3 Pro)
{
"contents": [{"role": "user", "parts": [{"text": "Give a geometry problem and solve it step by step"}]}],
"generationConfig": {
"maxOutputTokens": 8192,
"thinkingConfig": {
"includeThoughts": true,
"thinkingBudget": 8192
}
}
}
{
"contents": [{"role": "user", "parts": [{"text": "Give a geometry problem and solve it step by step"}]}],
"generationConfig": {
"maxOutputTokens": 8192,
"thinkingConfig": {
"includeThoughts": true,
"thinkingLevel": "HIGH"
}
}
}
멀티모달 입력
contents[].parts에서 텍스트와 미디어를 혼합할 수 있습니다:
{
"contents": [
{
"role": "user",
"parts": [
{"text": "Describe this image"},
{
"inlineData": {
"mimeType": "image/jpeg",
"data": "/9j/4AAQSkZJRg..."
}
}
]
}
]
}
- 이미지: base64
data가 있는inlineData, 또는fileUri(예:gs://...)가 있는fileData - 오디오:
audio/mp3등의mimeType이 있는inlineData
도구 호출(Function Calling)
{
"contents": [{"role": "user", "parts": [{"text": "What is the weather in Shanghai today?"}]}],
"tools": [
{
"functionDeclarations": [
{
"name": "get_weather",
"description": "Get weather for a city",
"parameters": {
"type": "object",
"properties": {
"location": {"type": "string"}
},
"required": ["location"]
}
}
]
}
],
"toolConfig": {
"functionCallingConfig": {
"mode": "AUTO",
"allowedFunctionNames": []
}
}
}
functionCall part를 반환할 수 있습니다. 다음 contents에 해당 functionResponse를 포함하여 다시 요청하세요.
Google Search(Grounding)
활성화하면 모델이 실시간 웹 검색을 사용하여 답변을 개선할 수 있습니다(예: 날씨, 뉴스).tools에 googleSearch를 추가하세요:
{
"contents": [{"role": "user", "parts": [{"text": "What is the weather in Beijing today?"}]}],
"tools": [
{
"googleSearch": {}
}
],
"toolConfig": {
"functionCallingConfig": {
"mode": "AUTO"
}
}
}
tools 배열에 googleSearch: {}와 functionDeclarations를 별도 요소로 포함하세요. 응답에 검색 메타데이터(예: groundingMetadata)가 포함될 수 있습니다.
스트리밍
사용:POST /v1beta/models/{model}:streamGenerateContent?alt=sse. 요청 본문은 generateContent와 동일합니다. 응답은 SSE이며, 각 data: 줄이 JSON 청크입니다.
컨텍스트 캐싱
첫 요청에는cachedContent를 포함하지 않습니다. 서버가 캐시 ID를 반환하면 이후 요청에서 다음과 같이 전송할 수 있습니다:
{
"cachedContent": "cached-content-id",
"contents": [{"role": "user", "parts": [{"text": "Continue from the context above"}]}]
}
이미지 생성(예: Gemini 2.5 Flash)
모델이 이미지 출력을 지원할 때generationConfig에서 설정:
{
"contents": [{"role": "user", "parts": [{"text": "Draw a cat"}]}],
"generationConfig": {
"responseModalities": ["IMAGE"],
"imageConfig": {
"aspectRatio": "1:1",
"imageSize": "1K",
"imageOutputOptions": {"mimeType": "image/png"}
}
}
}
candidates[].content.parts에 inlineData(예: base64 이미지)가 포함될 수 있습니다.
Embedding API
단일: embedContent
엔드포인트:POST https://api.gravitex.ai/v1beta/models/{model}:embedContent
요청 본문 예시:
{
"model": "text-embedding-004",
"content": {
"parts": [{"text": "Text to embed"}]
}
}
model을 넣습니다: /v1beta/models/text-embedding-004:embedContent, 본문에는 content만 포함.
일괄: batchEmbedContents
엔드포인트:POST https://api.gravitex.ai/v1beta/models/{model}:batchEmbedContents
요청 본문 예시:
{
"requests": [
{"content": {"parts": [{"text": "First text"}]}},
{"content": {"parts": [{"text": "Second text"}]}}
]
}
오류 처리
오류는 HTTP 상태 코드와 JSON 본문으로 반환됩니다:{
"error": {
"code": 400,
"message": "Invalid request: ...",
"status": "INVALID_ARGUMENT"
}
}
| Status | Meaning |
|---|---|
| 400 | 잘못된 요청(예: contents 누락, 지원되지 않는 매개변수) |
| 401 | 인증 실패(유효하지 않거나 누락된 API 키) |
| 404 | 모델을 찾을 수 없거나 경로 오류 |
| 429 | 속도 제한; 나중에 재시도 |
| 500 | 서버 오류 |
error.message를 파싱하고 재시도 또는 사용자 메시지를 적절히 처리하세요.
OpenAI 형식과의 비교
| 항목 | Gemini Native | OpenAI (/v1/chat/completions) |
|---|---|---|
| 기본 경로 | /v1beta/models/{model}:generateContent | /v1/chat/completions |
| 인증 | Authorization: Bearer sk-xxx 또는 x-goog-api-key | Authorization: Bearer sk-xxx |
| 메시지 형식 | contents[].parts[] (text/inlineData/fileData) | messages[].content (문자열 또는 배열) |
| 시스템 프롬프트 | systemInstruction.parts | role: "system"인 messages |
| 스트리밍 | streamGenerateContent?alt=sse | stream: true |
| 사고 | thinkingConfig 또는 모델 접미사 | 모델 접미사(예: -thinking) |
| 도구 | tools[].functionDeclarations | tools[].function (OpenAI 형식) |
| 일반적인 클라이언트 | Google SDK, 커스텀 HTTP 클라이언트 | OpenAI SDK, OpenAI 호환 클라이언트 |
thinkingConfig, 네이티브 멀티모달 parts)가 필요할 때 네이티브 엔드포인트를 사용하세요. OpenAI 생태계 내에서 작업하려면 /v1/chat/completions를 사용하세요.