Caching

Ruajtja në memorje e kontekstit ju lejon të ruani dhe ripërdorni token-e hyrës të parallogaritur që dëshironi të përdorni në mënyrë të përsëritur, për shembull kur bëni pyetje të ndryshme në lidhje me të njëjtin skedar mediatik. Kjo mund të çojë në kursime në kosto dhe shpejtësi, varësisht nga përdorimi. Për një hyrje të detajuar, shihni udhëzuesin e Ruajtjes në Memorje të Kontekstit .

Metoda: cachedContents.create

Krijon burimin CachedContent.

Pika e Fundit

posto https: / /generativelanguage.googleapis.com /v1beta /cachedContents

Trupi i kërkesës

Trupi i kërkesës përmban një instancë të CachedContent .

Fushat
contents[] object ( Content )

Opsionale. Vetëm hyrje. E pandryshueshme. Përmbajtja në memorien e përkohshme.

tools[] object ( Tool )

Opsionale. Vetëm hyrje. I pandryshueshëm. Një listë Tools që modeli mund të përdorë për të gjeneruar përgjigjen tjetër.

Union type expiration
Specifikon se kur do të skadojë ky burim. expiration mund të jetë vetëm një nga të mëposhtmet:
Vargu expireTime string ( Timestamp format)

Vula kohore në UTC e kohës kur ky burim konsiderohet i skaduar. Kjo jepet gjithmonë në dalje, pavarësisht se çfarë është dërguar në hyrje.

Përdor RFC 3339, ku rezultati i gjeneruar do të jetë gjithmonë i normalizuar sipas Z-së dhe do të përdorë 0, 3, 6 ose 9 shifra thyesore. Pranohen edhe zhvendosje të tjera përveç "Z". Shembuj: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" ose "2014-10-02T15:01:23+05:30" .

vargu ttl string ( Duration format)

Vetëm hyrje. TTL e re për këtë burim, vetëm hyrje.

Një kohëzgjatje në sekonda me deri në nëntë shifra thyesore, që mbaron me ' s '. Shembull: "3.5s" .

string displayName

Opsionale. I pandryshueshëm. Emri i shfaqjes kuptimplotë i gjeneruar nga përdoruesi i përmbajtjes së ruajtur në memorien e përkohshme. Maksimumi 128 karaktere Unicode.

string model

E detyrueshme. I pandryshueshëm. Emri i Model që do të përdoret për përmbajtjen e ruajtur në memorje. Formati: models/{model}

objekti systemInstruction object ( Content )

Opsionale. Vetëm hyrje. I pandryshueshëm. Zhvilluesi vendosi udhëzimet e sistemit. Aktualisht vetëm tekst.

objekti toolConfig object ( ToolConfig )

Opsionale. Vetëm hyrje. I pandryshueshëm. Konfigurimi i mjetit. Ky konfigurim ndahet për të gjitha mjetet.

Shembull kërkese

Bazë

Python

from google import genai
from google.genai import types

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-1.5-flash-001"

cache = client.caches.create(
    model=model_name,
    config=types.CreateCachedContentConfig(
        contents=[document],
        system_instruction="You are an expert analyzing transcripts.",
    ),
)
print(cache)

response = client.models.generate_content(
    model=model_name,
    contents="Please summarize this transcript",
    config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-1.5-flash-001";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
console.log("Cache created:", cache);

const response = await ai.models.generateContent({
  model: modelName,
  contents: "Please summarize this transcript",
  config: { cachedContent: cache.name },
});
console.log("Response text:", response.text);

Shko

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"), 
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-1.5-flash-001"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents: contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Cache created:")
fmt.Println(cache)

// Use the cache for generating content.
response, err := client.Models.GenerateContent(
	ctx,
	modelName,
	genai.Text("Please summarize this transcript"),
	&genai.GenerateContentConfig{
		CachedContent: cache.Name,
	},
)
if err != nil {
	log.Fatal(err)
}
printResponse(response)

Guaskë

wget https://storage.googleapis.com/generativeai-downloads/data/a11.txt
echo '{
  "model": "models/gemini-1.5-flash-001",
  "contents":[
    {
      "parts":[
        {
          "inline_data": {
            "mime_type":"text/plain",
            "data": "'$(base64 $B64FLAGS a11.txt)'"
          }
        }
      ],
    "role": "user"
    }
  ],
  "systemInstruction": {
    "parts": [
      {
        "text": "You are an expert at analyzing transcripts."
      }
    ]
  },
  "ttl": "300s"
}' > request.json

curl -X POST "https://generativelanguage.googleapis.com/v1beta/cachedContents?key=$GEMINI_API_KEY" \
 -H 'Content-Type: application/json' \
 -d @request.json \
 > cache.json

CACHE_NAME=$(cat cache.json | grep '"name":' | cut -d '"' -f 4 | head -n 1)

curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-1.5-flash-001:generateContent?key=$GEMINI_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
      "contents": [
        {
          "parts":[{
            "text": "Please summarize this transcript"
          }],
          "role": "user"
        },
      ],
      "cachedContent": "'$CACHE_NAME'"
    }'

Nga emri

Python

from google import genai
from google.genai import types

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-1.5-flash-001"

cache = client.caches.create(
    model=model_name,
    config=types.CreateCachedContentConfig(
        contents=[document],
        system_instruction="You are an expert analyzing transcripts.",
    ),
)
cache_name = cache.name  # Save the name for later

# Later retrieve the cache
cache = client.caches.get(name=cache_name)
response = client.models.generate_content(
    model=model_name,
    contents="Find a lighthearted moment from this transcript",
    config=types.GenerateContentConfig(cached_content=cache.name),
)
print(response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-1.5-flash-001";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
const cacheName = cache.name; // Save the name for later

// Later retrieve the cache
const retrievedCache = await ai.caches.get({ name: cacheName });
const response = await ai.models.generateContent({
  model: modelName,
  contents: "Find a lighthearted moment from this transcript",
  config: { cachedContent: retrievedCache.name },
});
console.log("Response text:", response.text);

Shko

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-1.5-flash-001"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}
cacheName := cache.Name

// Later retrieve the cache.
cache, err = client.Caches.Get(ctx, cacheName, &genai.GetCachedContentConfig{})
if err != nil {
	log.Fatal(err)
}

response, err := client.Models.GenerateContent(
	ctx,
	modelName,
	genai.Text("Find a lighthearted moment from this transcript"),
	&genai.GenerateContentConfig{
		CachedContent: cache.Name,
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Println("Response from cache (create from name):")
printResponse(response)

Nga biseda

Python

from google import genai
from google.genai import types

client = genai.Client()
model_name = "gemini-1.5-flash-001"
system_instruction = "You are an expert analyzing transcripts."

# Create a chat session with the given system instruction.
chat = client.chats.create(
    model=model_name,
    config=types.GenerateContentConfig(system_instruction=system_instruction),
)
document = client.files.upload(file=media / "a11.txt")

response = chat.send_message(
    message=["Hi, could you summarize this transcript?", document]
)
print("\n\nmodel:  ", response.text)
response = chat.send_message(
    message=["Okay, could you tell me more about the trans-lunar injection"]
)
print("\n\nmodel:  ", response.text)

# To cache the conversation so far, pass the chat history as the list of contents.
cache = client.caches.create(
    model=model_name,
    config={
        "contents": chat.get_history(),
        "system_instruction": system_instruction,
    },
)
# Continue the conversation using the cached content.
chat = client.chats.create(
    model=model_name,
    config=types.GenerateContentConfig(cached_content=cache.name),
)
response = chat.send_message(
    message="I didn't understand that last part, could you explain it in simpler language?"
)
print("\n\nmodel:  ", response.text)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const modelName = "gemini-1.5-flash-001";
const systemInstruction = "You are an expert analyzing transcripts.";

// Create a chat session with the system instruction.
const chat = ai.chats.create({
  model: modelName,
  config: { systemInstruction: systemInstruction },
});
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);

let response = await chat.sendMessage({
  message: createUserContent([
    "Hi, could you summarize this transcript?",
    createPartFromUri(document.uri, document.mimeType),
  ]),
});
console.log("\n\nmodel:", response.text);

response = await chat.sendMessage({
  message: "Okay, could you tell me more about the trans-lunar injection",
});
console.log("\n\nmodel:", response.text);

// To cache the conversation so far, pass the chat history as the list of contents.
const chatHistory = chat.getHistory();
const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: chatHistory,
    systemInstruction: systemInstruction,
  },
});

// Continue the conversation using the cached content.
const chatWithCache = ai.chats.create({
  model: modelName,
  config: { cachedContent: cache.name },
});
response = await chatWithCache.sendMessage({
  message:
    "I didn't understand that last part, could you explain it in simpler language?",
});
console.log("\n\nmodel:", response.text);

Shko

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-1.5-flash-001"
systemInstruction := "You are an expert analyzing transcripts."

// Create initial chat with a system instruction.
chat, err := client.Chats.Create(ctx, modelName, &genai.GenerateContentConfig{
	SystemInstruction: genai.NewContentFromText(systemInstruction, genai.RoleUser),
}, nil)
if err != nil {
	log.Fatal(err)
}

document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}

// Send first message with the transcript.
parts := make([]genai.Part, 2)
parts[0] = genai.Part{Text: "Hi, could you summarize this transcript?"}
parts[1] = genai.Part{
	FileData: &genai.FileData{
		FileURI :      document.URI,
		MIMEType: document.MIMEType,
	},
}

// Send chat message.
resp, err := chat.SendMessage(ctx, parts...)
if err != nil {
	log.Fatal(err)
}
fmt.Println("\n\nmodel: ", resp.Text())

resp, err = chat.SendMessage(
	ctx, 
	genai.Part{
		Text: "Okay, could you tell me more about the trans-lunar injection",
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Println("\n\nmodel: ", resp.Text())

// To cache the conversation so far, pass the chat history as the list of contents.
cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          chat.History(false),
	SystemInstruction: genai.NewContentFromText(systemInstruction, genai.RoleUser),
})
if err != nil {
	log.Fatal(err)
}

// Continue the conversation using the cached history.
chat, err = client.Chats.Create(ctx, modelName, &genai.GenerateContentConfig{
	CachedContent: cache.Name,
}, nil)
if err != nil {
	log.Fatal(err)
}

resp, err = chat.SendMessage(
	ctx, 
	genai.Part{
		Text: "I didn't understand that last part, could you explain it in simpler language?",
	},
)
if err != nil {
	log.Fatal(err)
}
fmt.Println("\n\nmodel: ", resp.Text())

Trupi i përgjigjes

Nëse është e suksesshme, trupi i përgjigjes përmban një instancë të sapokrijuar të CachedContent .

Metoda: cachedContents.list

Listat e Përmbajtjeve të Ruajtura në Memorje.

Pika e Fundit

merrni https: / /generativelanguage.googleapis.com /v1beta /cachedContents

Parametrat e pyetjes

pageSize integer

Opsionale. Numri maksimal i përmbajtjeve të ruajtura në memorje për t'u kthyer. Shërbimi mund të kthejë më pak se kjo vlerë. Nëse nuk specifikohet, do të kthehet një numër i parazgjedhur (nën maksimumin) i artikujve. Vlera maksimale është 1000; vlerat mbi 1000 do të detyrohen në 1000.

vargu i pageToken string

Opsionale. Një shenjë faqeje, e marrë nga një thirrje e mëparshme cachedContents.list . Jepni këtë për të marrë faqen pasuese.

Gjatë faqosjes, të gjithë parametrat e tjerë të dhënë për cachedContents.list duhet të përputhen me thirrjen që ofroi tokenin e faqes.

Trupi i kërkesës

Trupi i kërkesës duhet të jetë bosh.

Trupi i përgjigjes

Përgjigje me listën CachedContents.

Nëse është i suksesshëm, trupi i përgjigjes përmban të dhëna me strukturën e mëposhtme:

Fushat
objekti cachedContents[] object ( CachedContent )

Lista e përmbajtjeve të ruajtura në memorien e përkohshme.

string nextPageToken

Një shenjë, e cila mund të dërgohet si pageToken për të marrë faqen tjetër. Nëse kjo fushë lihet jashtë, nuk ka faqe pasuese.

Përfaqësimi JSON
{
  "cachedContents": [
    {
      object (CachedContent)
    }
  ],
  "nextPageToken": string
}

Metoda: cachedContents.get

Lexon burimin CachedContent.

Pika e Fundit

merrni https: / /generativelanguage.googleapis.com /v1beta /{name=cachedContents /*}

Parametrat e shtegut

string name

E detyrueshme. Emri i burimit që i referohet hyrjes në memorien e përkohshme të përmbajtjes. Formati: cachedContents/{id} Merr formën cachedContents/{cachedcontent} .

Trupi i kërkesës

Trupi i kërkesës duhet të jetë bosh.

Shembull kërkese

Python

from google import genai

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-1.5-flash-001"

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)
print(client.caches.get(name=cache.name))

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-1.5-flash-001";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
const retrievedCache = await ai.caches.get({ name: cache.name });
console.log("Retrieved Cache:", retrievedCache);

Shko

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-1.5-flash-001"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}

cache, err = client.Caches.Get(ctx, cache.Name, &genai.GetCachedContentConfig{})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Retrieved cache:")
fmt.Println(cache)

Guaskë

curl "https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME?key=$GEMINI_API_KEY"

Trupi i përgjigjes

Nëse është e suksesshme, trupi i përgjigjes përmban një instancë të CachedContent .

Metoda: cachedContents.patch

Përditëson burimin CachedContent (vetëm data e skadimit mund të përditësohet).

Pika e Fundit

përditësim https: / /generativelanguage.googleapis.com /v1beta /{cachedContent.name=cachedContents /*}
PATCH https://generativelanguage.googleapis.com/v1beta/{cachedContent.name=cachedContents/*}

Parametrat e shtegut

string cachedContent.name

Vetëm rezultati. Identifikuesi. Emri i burimit që i referohet përmbajtjes së ruajtur në memorje. Formati: cachedContents/{id} Merr formën cachedContents/{cachedcontent} .

Parametrat e pyetjes

vargu updateMask string ( FieldMask format)

Lista e fushave që duhen përditësuar.

Kjo është një listë e ndarë me presje e emrave të fushave plotësisht të kualifikuara. Shembull: "user.displayName,photo" .

Trupi i kërkesës

Trupi i kërkesës përmban një instancë të CachedContent .

Fushat
Union type expiration
Specifikon se kur do të skadojë ky burim. expiration mund të jetë vetëm një nga të mëposhtmet:
Vargu expireTime string ( Timestamp format)

Vula kohore në UTC e kohës kur ky burim konsiderohet i skaduar. Kjo jepet gjithmonë në dalje, pavarësisht se çfarë është dërguar në hyrje.

Përdor RFC 3339, ku rezultati i gjeneruar do të jetë gjithmonë i normalizuar sipas Z-së dhe do të përdorë 0, 3, 6 ose 9 shifra thyesore. Pranohen edhe zhvendosje të tjera përveç "Z". Shembuj: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" ose "2014-10-02T15:01:23+05:30" .

vargu ttl string ( Duration format)

Vetëm hyrje. TTL e re për këtë burim, vetëm hyrje.

Një kohëzgjatje në sekonda me deri në nëntë shifra thyesore, që mbaron me ' s '. Shembull: "3.5s" .

Shembull kërkese

Python

from google import genai
from google.genai import types
import datetime

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-1.5-flash-001"

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)

# Update the cache's time-to-live (ttl)
ttl = f"{int(datetime.timedelta(hours=2).total_seconds())}s"
client.caches.update(
    name=cache.name, config=types.UpdateCachedContentConfig(ttl=ttl)
)
print(f"After update:\n {cache}")

# Alternatively, update the expire_time directly
# Update the expire_time directly in valid RFC 3339 format (UTC with a "Z" suffix)
expire_time = (
    (
        datetime.datetime.now(datetime.timezone.utc)
        + datetime.timedelta(minutes=15)
    )
    .isoformat()
    .replace("+00:00", "Z")
)
client.caches.update(
    name=cache.name,
    config=types.UpdateCachedContentConfig(expire_time=expire_time),
)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-1.5-flash-001";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

let cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});

// Update the cache's time-to-live (ttl)
const ttl = `${2 * 3600}s`; // 2 hours in seconds
cache = await ai.caches.update({
  name: cache.name,
  config: { ttl },
});
console.log("After update (TTL):", cache);

// Alternatively, update the expire_time directly (in RFC 3339 format with a "Z" suffix)
const expireTime = new Date(Date.now() + 15 * 60000)
  .toISOString()
  .replace(/\.\d{3}Z$/, "Z");
cache = await ai.caches.update({
  name: cache.name,
  config: { expireTime: expireTime },
});
console.log("After update (expire_time):", cache);

Shko

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-1.5-flash-001"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}

_, err = client.Caches.Delete(ctx, cache.Name, &genai.DeleteCachedContentConfig{})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Cache deleted:", cache.Name)

Guaskë

curl -X PATCH "https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME?key=$GEMINI_API_KEY" \
 -H 'Content-Type: application/json' \
 -d '{"ttl": "600s"}'

Trupi i përgjigjes

Nëse është e suksesshme, trupi i përgjigjes përmban një instancë të CachedContent .

Metoda: cachedContents.delete

Fshin burimin CachedContent.

Pika e Fundit

fshi https: / /generativelanguage.googleapis.com /v1beta /{name=cachedContents /*}

Parametrat e shtegut

string name

E detyrueshme. Emri i burimit që i referohet hyrjes në memorien e përkohshme të përmbajtjes. Formati: cachedContents/{id} Merr formën cachedContents/{cachedcontent} .

Trupi i kërkesës

Trupi i kërkesës duhet të jetë bosh.

Shembull kërkese

Python

from google import genai

client = genai.Client()
document = client.files.upload(file=media / "a11.txt")
model_name = "gemini-1.5-flash-001"

cache = client.caches.create(
    model=model_name,
    config={
        "contents": [document],
        "system_instruction": "You are an expert analyzing transcripts.",
    },
)
client.caches.delete(name=cache.name)

Node.js

// Make sure to include the following import:
// import {GoogleGenAI} from '@google/genai';
const ai = new GoogleGenAI({ apiKey: process.env.GEMINI_API_KEY });
const filePath = path.join(media, "a11.txt");
const document = await ai.files.upload({
  file: filePath,
  config: { mimeType: "text/plain" },
});
console.log("Uploaded file name:", document.name);
const modelName = "gemini-1.5-flash-001";

const contents = [
  createUserContent(createPartFromUri(document.uri, document.mimeType)),
];

const cache = await ai.caches.create({
  model: modelName,
  config: {
    contents: contents,
    systemInstruction: "You are an expert analyzing transcripts.",
  },
});
await ai.caches.delete({ name: cache.name });
console.log("Cache deleted:", cache.name);

Shko

ctx := context.Background()
client, err := genai.NewClient(ctx, &genai.ClientConfig{
	APIKey:  os.Getenv("GEMINI_API_KEY"),
	Backend: genai.BackendGeminiAPI,
})
if err != nil {
	log.Fatal(err)
}

modelName := "gemini-1.5-flash-001"
document, err := client.Files.UploadFromPath(
	ctx, 
	filepath.Join(getMedia(), "a11.txt"), 
	&genai.UploadFileConfig{
		MIMEType : "text/plain",
	},
)
if err != nil {
	log.Fatal(err)
}
parts := []*genai.Part{
	genai.NewPartFromURI(document.URI, document.MIMEType),
}
contents := []*genai.Content{
	genai.NewContentFromParts(parts, genai.RoleUser),
}

cache, err := client.Caches.Create(ctx, modelName, &genai.CreateCachedContentConfig{
	Contents:          contents,
	SystemInstruction: genai.NewContentFromText(
		"You are an expert analyzing transcripts.", genai.RoleUser,
	),
})
if err != nil {
	log.Fatal(err)
}

_, err = client.Caches.Delete(ctx, cache.Name, &genai.DeleteCachedContentConfig{})
if err != nil {
	log.Fatal(err)
}
fmt.Println("Cache deleted:", cache.Name)

Guaskë

curl -X DELETE "https://generativelanguage.googleapis.com/v1beta/$CACHE_NAME?key=$GEMINI_API_KEY"

Trupi i përgjigjes

Nëse është i suksesshëm, trupi i përgjigjes është një objekt JSON bosh.

Burimi REST: cachedContents

Burimi: CachedContent

Përmbajtje që është përpunuar paraprakisht dhe mund të përdoret në kërkesën pasuese drejtuar GenerativeService.

Përmbajtja e ruajtur në memorien e përkohshme mund të përdoret vetëm me modelin për të cilin është krijuar.

Fushat
contents[] object ( Content )

Opsionale. Vetëm hyrje. E pandryshueshme. Përmbajtja në memorien e përkohshme.

tools[] object ( Tool )

Opsionale. Vetëm hyrje. I pandryshueshëm. Një listë Tools që modeli mund të përdorë për të gjeneruar përgjigjen tjetër.

createTime string ( Timestamp format)

Vetëm rezultati. Koha e krijimit të hyrjes në memorien e përkohshme.

Përdor RFC 3339, ku rezultati i gjeneruar do të jetë gjithmonë i normalizuar sipas Z-së dhe do të përdorë 0, 3, 6 ose 9 shifra thyesore. Pranohen edhe zhvendosje të tjera përveç "Z". Shembuj: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" ose "2014-10-02T15:01:23+05:30" .

vargu updateTime string ( Timestamp format)

Vetëm dalje. Kur hyrja e memories së përkohshme është përditësuar për herë të fundit në kohën UTC.

Përdor RFC 3339, ku rezultati i gjeneruar do të jetë gjithmonë i normalizuar sipas Z-së dhe do të përdorë 0, 3, 6 ose 9 shifra thyesore. Pranohen edhe zhvendosje të tjera përveç "Z". Shembuj: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" ose "2014-10-02T15:01:23+05:30" .

objekti usageMetadata object ( UsageMetadata )

Vetëm rezultate. Meta të dhëna mbi përdorimin e përmbajtjes së ruajtur në memorien e përkohshme.

Union type expiration
Specifikon se kur do të skadojë ky burim. expiration mund të jetë vetëm një nga të mëposhtmet:
Vargu expireTime string ( Timestamp format)

Vula kohore në UTC e kohës kur ky burim konsiderohet i skaduar. Kjo jepet gjithmonë në dalje, pavarësisht se çfarë është dërguar në hyrje.

Përdor RFC 3339, ku rezultati i gjeneruar do të jetë gjithmonë i normalizuar sipas Z-së dhe do të përdorë 0, 3, 6 ose 9 shifra thyesore. Pranohen edhe zhvendosje të tjera përveç "Z". Shembuj: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" ose "2014-10-02T15:01:23+05:30" .

vargu ttl string ( Duration format)

Vetëm hyrje. TTL e re për këtë burim, vetëm hyrje.

Një kohëzgjatje në sekonda me deri në nëntë shifra thyesore, që mbaron me ' s '. Shembull: "3.5s" .

string name

Vetëm rezultat. Identifikues. Emri i burimit që i referohet përmbajtjes së ruajtur në memorje. Formati: cachedContents/{id}

string displayName

Opsionale. I pandryshueshëm. Emri i shfaqjes kuptimplotë i gjeneruar nga përdoruesi i përmbajtjes së ruajtur në memorien e përkohshme. Maksimumi 128 karaktere Unicode.

string model

E detyrueshme. I pandryshueshëm. Emri i Model që do të përdoret për përmbajtjen e ruajtur në memorje. Formati: models/{model}

objekti systemInstruction object ( Content )

Opsionale. Vetëm hyrje. I pandryshueshëm. Zhvilluesi vendosi udhëzimet e sistemit. Aktualisht vetëm tekst.

objekti toolConfig object ( ToolConfig )

Opsionale. Vetëm hyrje. I pandryshueshëm. Konfigurimi i mjetit. Ky konfigurim ndahet për të gjitha mjetet.

Përfaqësimi JSON
{
  "contents": [
    {
      object (Content)
    }
  ],
  "tools": [
    {
      object (Tool)
    }
  ],
  "createTime": string,
  "updateTime": string,
  "usageMetadata": {
    object (UsageMetadata)
  },

  // expiration
  "expireTime": string,
  "ttl": string
  // Union type
  "name": string,
  "displayName": string,
  "model": string,
  "systemInstruction": {
    object (Content)
  },
  "toolConfig": {
    object (ToolConfig)
  }
}

Përmbajtja

Lloji i të dhënave të strukturuara bazë që përmban përmbajtje shumëpjesëshe të një mesazhi.

Një Content përfshin një fushë role që përcakton prodhuesin e Content dhe një fushë parts që përmban të dhëna shumëpjesëshe që përmbajnë përmbajtjen e mesazhit të radhës.

Fushat
objekti parts[] object ( Part )

Parts të renditura që përbëjnë një mesazh të vetëm. Pjesët mund të kenë lloje të ndryshme MIME.

string role

Opsionale. Prodhuesi i përmbajtjes. Duhet të jetë ose 'përdorues' ose 'model'.

E dobishme për t'u vendosur për biseda me shumë kthesa, përndryshe mund të lihet bosh ose e pacaktuar.

Përfaqësimi JSON
{
  "parts": [
    {
      object (Part)
    }
  ],
  "role": string
}

Pjesë

Një lloj të dhënash që përmban media që është pjesë e një mesazhi Content me shumë pjesë.

Një Part përbëhet nga të dhëna që kanë një lloj të dhënash të shoqëruar. Një Part mund të përmbajë vetëm një nga llojet e pranuara në Part.data .

Një Part duhet të ketë një lloj fiks IANA MIME që identifikon llojin dhe nëntipin e medias nëse fusha inlineData është e mbushur me bajt të papërpunuar.

Fushat
thought boolean

Opsionale. Tregon nëse pjesa është menduar nga modeli.

vargu thoughtSignature string ( bytes format)

Opsionale. Një nënshkrim i errët për mendimin në mënyrë që të mund të ripërdoret në kërkesat pasuese.

Një varg i koduar me base64.

objekti partMetadata object ( Struct format)

Meta të dhënat e personalizuara të shoqëruara me Pjesën. Agjentët që përdorin genai.Part si përfaqësim të përmbajtjes mund të kenë nevojë të mbajnë gjurmët e informacionit shtesë. Për shembull, mund të jetë emri i një skedari/burimi nga i cili buron Pjesa ose një mënyrë për të shumëfishuar rrjedha të shumëfishta Pjesësh.

objekti mediaResolution object ( MediaResolution )

Opsionale. Rezolucioni i medias për median hyrëse.

Union type data
data mund të jenë vetëm një nga të mëposhtmet:
string text

Tekst i integruar.

Objekti inlineData object ( Blob )

Bajt mediash të integruara.

objekti functionCall object ( FunctionCall )

Një FunctionCall i parashikuar i kthyer nga modeli që përmban një varg që përfaqëson FunctionDeclaration.name me argumentet dhe vlerat e tyre.

objekti functionResponse object ( FunctionResponse )

Rezultati i një FunctionCall që përmban një varg që përfaqëson FunctionDeclaration.name dhe një objekt të strukturuar JSON që përmban çdo rezultat nga funksioni përdoret si kontekst për modelin.

objekti fileData object ( FileData )

Të dhëna të bazuara në URI.

objekti executableCode object ( ExecutableCode )

Kodi i gjeneruar nga modeli që është menduar të ekzekutohet.

objekti codeExecutionResult object ( CodeExecutionResult )

Rezultati i ekzekutimit të ExecutableCode .

objekti toolCall object ( ToolCall )

Thirrje mjeti nga ana e serverit. Kjo fushë plotësohet kur modeli parashikon një thirrje mjeti që duhet të ekzekutohet në server. Pritet që klienti ta dërgojë këtë mesazh përsëri te API-ja.

objekti toolResponse object ( ToolResponse )

Rezultati nga një ekzekutim ToolCall në anën e serverit. Kjo fushë plotësohet nga klienti me rezultatet e ekzekutimit të ToolCall përkatëse.

Union type metadata
Kontrollon përpunimin paraprak shtesë të të dhënave. metadata mund të jenë vetëm një nga të mëposhtmet:
objekti videoMetadata object ( VideoMetadata )

Opsionale. Meta të dhënat e videos. Meta të dhënat duhet të specifikohen vetëm kur të dhënat e videos paraqiten në inlineData ose fileData.

Përfaqësimi JSON
{
  "thought": boolean,
  "thoughtSignature": string,
  "partMetadata": {
    object
  },
  "mediaResolution": {
    object (MediaResolution)
  },

  // data
  "text": string,
  "inlineData": {
    object (Blob)
  },
  "functionCall": {
    object (FunctionCall)
  },
  "functionResponse": {
    object (FunctionResponse)
  },
  "fileData": {
    object (FileData)
  },
  "executableCode": {
    object (ExecutableCode)
  },
  "codeExecutionResult": {
    object (CodeExecutionResult)
  },
  "toolCall": {
    object (ToolCall)
  },
  "toolResponse": {
    object (ToolResponse)
  }
  // Union type

  // metadata
  "videoMetadata": {
    object (VideoMetadata)
  }
  // Union type
}

Pikë

Bajt të medias së papërpunuar.

Teksti nuk duhet të dërgohet si bajt i papërpunuar, përdorni fushën 'tekst'.

Fushat
string mimeType

Lloji standard MIME IANA i të dhënave burimore. Shembuj: - image/png - image/jpeg Nëse jepet një lloj MIME i pambështetur, do të kthehet një gabim. Për një listë të plotë të llojeve të mbështetura, shihni Formatet e skedarëve të mbështetura .

varg data string ( bytes format)

Bajt të papërpunuar për formatet mediatike.

Një varg i koduar me base64.

Përfaqësimi JSON
{
  "mimeType": string,
  "data": string
}

Thirrja e Funksionit

Një FunctionCall i parashikuar i kthyer nga modeli që përmban një varg që përfaqëson FunctionDeclaration.name me argumentet dhe vlerat e tyre.

Fushat
string id

Opsionale. Identifikues unik i thirrjes së funksionit. Nëse plotësohet, klienti duhet të ekzekutojë functionCall dhe të kthejë përgjigjen me id në përkatëse.

string name

E detyrueshme. Emri i funksionit që do të thirret. Duhet të jetë az, AZ, 0-9, ose të përmbajë nënvizime dhe viza, me një gjatësi maksimale prej 128.

objekti args object ( Struct format)

Opsionale. Parametrat dhe vlerat e funksionit në formatin e objektit JSON.

Përfaqësimi JSON
{
  "id": string,
  "name": string,
  "args": {
    object
  }
}

FunksioniPërgjigja

Rezultati i dhënë nga një FunctionCall që përmban një varg që përfaqëson FunctionDeclaration.name dhe një objekt të strukturuar JSON që përmban çdo rezultat nga funksioni përdoret si kontekst për modelin. Ky duhet të përmbajë rezultatin e një FunctionCall të bërë bazuar në parashikimin e modelit.

Fushat
string id

Opsionale. Identifikuesi i thirrjes së funksionit për të cilin është kjo përgjigje. Plotësohet nga klienti për t'u përputhur me id në përkatëse të thirrjes së funksionit.

string name

E detyrueshme. Emri i funksionit që do të thirret. Duhet të jetë az, AZ, 0-9, ose të përmbajë nënvizime dhe viza, me një gjatësi maksimale prej 128.

objekt response object ( Struct format)

E detyrueshme. Përgjigja e funksionit në formatin e objektit JSON. Thirrësit mund të përdorin çdo çelës sipas zgjedhjes së tyre që i përshtatet sintaksës së funksionit për të kthyer rezultatin e funksionit, p.sh. "output", "result", etj. Në veçanti, nëse thirrja e funksionit dështoi të ekzekutohej, përgjigjja mund të ketë një çelës "gabim" për të kthyer detajet e gabimit në model.

objekti parts[] object ( FunctionResponsePart )

Opsionale. Parts të porositura që përbëjnë një përgjigje funksioni. Pjesët mund të kenë lloje të ndryshme IANA MIME.

willContinue boolean

Opsionale. Sinjalizon që thirrja e funksionit vazhdon dhe do të kthehen më shumë përgjigje, duke e shndërruar thirrjen e funksionit në një gjenerator. I zbatueshëm vetëm për thirrjet e funksionit NON_BLOCKING, përndryshe injorohet. Nëse vendoset në false, përgjigjet e ardhshme nuk do të merren në konsideratë. Lejohet të kthehet response boshe me willContinue=False për të sinjalizuar se thirrja e funksionit ka mbaruar. Kjo mund të shkaktojë ende gjenerimin e modelit. Për të shmangur shkaktimin e gjenerimit dhe për të përfunduar thirrjen e funksionit, vendosni gjithashtu schedulingSILENT .

numërimi scheduling enum ( Scheduling )

Opsionale. Specifikon se si duhet të planifikohet përgjigja në bisedë. I zbatueshëm vetëm për thirrjet e funksioneve NON_BLOCKING, përndryshe injorohet. Parazgjedhja është WHEN_IDLE.

Përfaqësimi JSON
{
  "id": string,
  "name": string,
  "response": {
    object
  },
  "parts": [
    {
      object (FunctionResponsePart)
    }
  ],
  "willContinue": boolean,
  "scheduling": enum (Scheduling)
}

FunctionResponsePjesa

Një lloj të dhënash që përmban media që është pjesë e një mesazhi FunctionResponse .

Një FunctionResponsePart përbëhet nga të dhëna që kanë një lloj të dhënash të shoqëruar. Një FunctionResponsePart mund të përmbajë vetëm një nga llojet e pranuara në FunctionResponsePart.data .

Një FunctionResponsePart duhet të ketë një lloj IANA MIME të fiksuar që identifikon llojin dhe nëntipin e medias nëse fusha inlineData është e mbushur me bajt të papërpunuar.

Fushat
Union type data
Të dhënat e pjesës së përgjigjes së funksionit. data mund të jenë vetëm një nga të mëposhtmet:
Objekti inlineData object ( FunctionResponseBlob )

Bajt mediash të integruara.

Përfaqësimi JSON
{

  // data
  "inlineData": {
    object (FunctionResponseBlob)
  }
  // Union type
}

FunksioniResponseBlob

Bajt të medias së papërpunuar për përgjigjen e funksionit.

Teksti nuk duhet të dërgohet si bajt i papërpunuar, përdorni fushën 'FunctionResponse.response'.

Fushat
string mimeType

Lloji standard MIME IANA i të dhënave burimore. Shembuj: - image/png - image/jpeg Nëse jepet një lloj MIME i pambështetur, do të kthehet një gabim. Për një listë të plotë të llojeve të mbështetura, shihni Formatet e skedarëve të mbështetura .

varg data string ( bytes format)

Bajt të papërpunuar për formatet mediatike.

Një varg i koduar me base64.

Përfaqësimi JSON
{
  "mimeType": string,
  "data": string
}

Planifikimi

Specifikon se si duhet të planifikohet përgjigja në bisedë.

Numërime
SCHEDULING_UNSPECIFIED Kjo vlerë nuk përdoret.
SILENT Shtoni rezultatin vetëm në kontekstin e bisedës, mos e ndërprisni ose mos aktivizoni gjenerimin.
WHEN_IDLE Shtoni rezultatin në kontekstin e bisedës dhe kërkoni që të gjenerohet rezultati pa ndërprerë gjenerimin në vazhdim.
INTERRUPT Shtoni rezultatin në kontekstin e bisedës, ndërpritni gjenerimin e vazhdueshëm dhe nxitni për të gjeneruar rezultate.

Të Dhënat e Skedarit

Të dhëna të bazuara në URI.

Fushat
string mimeType

Opsionale. Lloji standard MIME IANA i të dhënave burimore.

fileUri string

E detyrueshme. URI.

Përfaqësimi JSON
{
  "mimeType": string,
  "fileUri": string
}

Kodi i Ekzekutueshëm

Kodi i gjeneruar nga modeli që është menduar të ekzekutohet dhe rezultati i kthyer te modeli.

Gjenerohet vetëm kur përdoret mjeti CodeExecution , në të cilin kodi do të ekzekutohet automatikisht dhe do të gjenerohet gjithashtu një CodeExecutionResult përkatës.

Fushat
string id

Opsionale. Identifikues unik i pjesës ExecutableCode . Serveri kthen CodeExecutionResult me id në përkatëse.

numërimi language enum ( Language )

E detyrueshme. Gjuha e programimit të code .

code string

E detyrueshme. Kodi që do të ekzekutohet.

Përfaqësimi JSON
{
  "id": string,
  "language": enum (Language),
  "code": string
}

Gjuha

Gjuhët e programimit të mbështetura për kodin e gjeneruar.

Numërime
LANGUAGE_UNSPECIFIED Gjuhë e paspecifikuar. Kjo vlerë nuk duhet të përdoret.
PYTHON Python >= 3.10, me numpy dhe simpy të disponueshëm. Python është gjuha e parazgjedhur.

Rezultati i Ekzekutimit të Kodit

Rezultati i ekzekutimit të ExecutableCode .

Gjenerohet vetëm kur përdoret mjeti CodeExecution .

Fushat
string id

Opsionale. Identifikuesi i pjesës ExecutableCode për të cilën është ky rezultat. Plotësohet vetëm nëse ExecutableCode përkatës ka një id.

numërimi i outcome enum ( Outcome )

E detyrueshme. Rezultati i ekzekutimit të kodit.

output string

Opsionale. Përmban stdout kur ekzekutimi i kodit është i suksesshëm, stderr ose përshkrim tjetër ndryshe.

Përfaqësimi JSON
{
  "id": string,
  "outcome": enum (Outcome),
  "output": string
}

Rezultati

Numërimi i rezultateve të mundshme të ekzekutimit të kodit.

Numërime
OUTCOME_UNSPECIFIED Status i papërcaktuar. Kjo vlerë nuk duhet të përdoret.
OUTCOME_OK Ekzekutimi i kodit përfundoi me sukses. output përmban stdout-in, nëse ka.
OUTCOME_FAILED Ekzekutimi i kodit dështoi. output përmban stderr dhe stdout, nëse ka.
OUTCOME_DEADLINE_EXCEEDED Ekzekutimi i kodit u zhvillua për një kohë shumë të gjatë dhe u anulua. Mund të ketë ose jo një output të pjesshëm.

ToolCall

Një ToolCall i parashikuar nga ana e serverit u kthye nga modeli. Ky mesazh përmban informacion në lidhje me një mjet që modeli dëshiron të thirret. NUK pritet që klienti ta ekzekutojë këtë ToolCall . Në vend të kësaj, klienti duhet ta kalojë këtë ToolCall përsëri te API në një kthesë pasuese brenda një mesazhi Content , së bashku me ToolResponse përkatëse.

Fushat
string id

Opsionale. Identifikues unik i thirrjes së mjetit. Serveri kthen përgjigjen e mjetit me id në përkatëse.

numërimi toolType enum ( ToolType )

E detyrueshme. Lloji i mjetit që u thirr.

objekti args object ( Struct format)

Opsionale. Argumentet e thirrjes së mjetit. Shembull: {"arg1" : "vlera1", "arg2" : "vlera2", ...}

Përfaqësimi JSON
{
  "id": string,
  "toolType": enum (ToolType),
  "args": {
    object
  }
}

Lloji i mjetit

Lloji i mjetit në thirrjen e funksionit.

Numërime
TOOL_TYPE_UNSPECIFIED Lloj mjeti i papërcaktuar.
GOOGLE_SEARCH_WEB Mjeti i kërkimit në Google, hartëzon Tool.google_search.search_types.web_search.
GOOGLE_SEARCH_IMAGE Mjeti i kërkimit të imazheve, lidhet me Tool.google_search.search_types.image_search.
URL_CONTEXT Mjeti i kontekstit të URL-së, lidhet me Tool.url_context.
GOOGLE_MAPS Mjeti i hartave të Google, hartat te Tool.google_maps.

ToolResponse

Rezultati nga një ekzekutim ToolCall në anën e serverit. Ky mesazh përmban rezultatet e një thirrjeje mjeti që u iniciua nga një ToolCall nga modeli. Klienti duhet ta kalojë këtë ToolResponse përsëri te API në një kthesë pasuese brenda një mesazhi Content , së bashku me ToolCall përkatëse.

Fushat
string id

Opsionale. Identifikuesi i thirrjes së mjetit për të cilin është ky përgjigje.

numërimi toolType enum ( ToolType )

E detyrueshme. Lloji i mjetit që u thirr, që përputhet me toolTypeToolCall përkatëse.

objekt response object ( Struct format)

Opsionale. Përgjigja e mjetit.

Përfaqësimi JSON
{
  "id": string,
  "toolType": enum (ToolType),
  "response": {
    object
  }
}

Meta të dhëna video

I vjetruar: Përdorni GenerateContentRequest.processing_options në vend të tij. Metadatat përshkruajnë përmbajtjen e videos hyrëse.

Fushat
vargu startOffset string ( Duration format)

Opsionale. Zhvendosja fillestare e videos.

Një kohëzgjatje në sekonda me deri në nëntë shifra thyesore, që mbaron me ' s '. Shembull: "3.5s" .

Vargu endOffset string ( Duration format)

Opsionale. Zhvendosja në fund të videos.

Një kohëzgjatje në sekonda me deri në nëntë shifra thyesore, që mbaron me ' s '. Shembull: "3.5s" .

number fps it

Opsionale. Shpejtësia e kuadrove të videos së dërguar te modeli. Nëse nuk specifikohet, vlera e parazgjedhur do të jetë 1.0. Diapazoni i kuadrove për sekondë është (0.0, 24.0].

Përfaqësimi JSON
{
  "startOffset": string,
  "endOffset": string,
  "fps": number
}

Rezolucioni i Medias

Rezolucioni i medias për tokenizimin.

Fushat
Union type value
Vlera e nivelit të rezolucionit të medias mund të jetë vetëm një nga value e mëposhtme:
numërimi i level enum ( Level )

Cilësia e tokenizimit të përdorur për median e dhënë. për mbështetjen e Gemini API .

Përfaqësimi JSON
{

  // value
  "level": enum (Level)
  // Union type
}

Niveli

Niveli i rezolucionit të medias.

Numërime
MEDIA_RESOLUTION_UNSPECIFIED Rezolucioni i medias nuk është vendosur.
MEDIA_RESOLUTION_LOW Rezolucioni i medias është vendosur në të ulët.
MEDIA_RESOLUTION_MEDIUM Rezolucioni i medias është vendosur në mesatare.
MEDIA_RESOLUTION_HIGH Rezolucioni i medias është vendosur në nivel të lartë.
MEDIA_RESOLUTION_ULTRA_HIGH Rezolucioni i medias është vendosur në ultra të lartë.

Mjet

Detajet e mjetit që modeli mund të përdorë për të gjeneruar përgjigje.

Një Tool është një pjesë kodi që i mundëson sistemit të bashkëveprojë me sisteme të jashtme për të kryer një veprim, ose një sërë veprimesh, jashtë njohurive dhe fushëveprimit të modelit.

ID-ja tjetër: 16

Fushat
objekti functionDeclarations[] object ( FunctionDeclaration )

Opsionale. Një listë e FunctionDeclarations të disponueshme për modelin që mund të përdoren për thirrjen e funksioneve.

Modeli ose sistemi nuk e ekzekuton funksionin. Në vend të kësaj, funksioni i përcaktuar mund të kthehet si një FunctionCall me argumente në anën e klientit për ekzekutim. Modeli mund të vendosë të thërrasë një nëngrup të këtyre funksioneve duke plotësuar FunctionCall në përgjigje. Raundi tjetër i bisedës mund të përmbajë një FunctionResponse me kontekstin e gjenerimit të "funksionit" Content.role për raundin tjetër të modelit.

object ( GoogleSearchRetrieval ) googleSearchRetrieval ...

Opsionale. Mjet kërkimi që mundësohet nga kërkimi në Google.

objekti codeExecution object ( CodeExecution )

Opsionale. I mundëson modelit të ekzekutojë kodin si pjesë të gjenerimit.

objekti computerUse object ( ComputerUse )

Opsionale. Mjet për të mbështetur modelin që bashkëvepron drejtpërdrejt me kompjuterin. Nëse aktivizohet, ai automatikisht plotëson Deklaratat e Funksioneve specifike për përdorimin e kompjuterit.

Objekti urlContext object ( UrlContext )

Opsionale. Mjet për të mbështetur rikthimin e kontekstit të URL-së.

objekti mcpServers[] object ( McpServer )

Opsionale. Serverat MCP për t'u lidhur.

objekti googleMaps object ( GoogleMaps )

Opsionale. Mjet që lejon bazën e përgjigjes së modelit me kontekst gjeohapësinor që lidhet me pyetjen e përdoruesit.

Përfaqësimi JSON
{
  "functionDeclarations": [
    {
      object (FunctionDeclaration)
    }
  ],
  "googleSearchRetrieval": {
    object (GoogleSearchRetrieval)
  },
  "codeExecution": {
    object (CodeExecution)
  },
  "googleSearch": {
    object (GoogleSearch)
  },
  "computerUse": {
    object (ComputerUse)
  },
  "urlContext": {
    object (UrlContext)
  },
  "fileSearch": {
    object (FileSearch)
  },
  "mcpServers": [
    {
      object (McpServer)
    }
  ],
  "googleMaps": {
    object (GoogleMaps)
  }
}

Deklarata e Funksionit

Përfaqësim i strukturuar i një deklarate funksioni siç përcaktohet nga specifikimi OpenAPI 3.03 . Në këtë deklaratë përfshihen emri dhe parametrat e funksionit. Kjo Deklaratë Funksioni është një përfaqësim i një blloku kodi që mund të përdoret si një Tool nga modeli dhe të ekzekutohet nga klienti.

Fushat
string name

E detyrueshme. Emri i funksionit. Duhet të jetë az, AZ, 0-9, ose të përmbajë nënvizime, dy pika, pika dhe viza, me një gjatësi maksimale prej 128.

string description

E detyrueshme. Një përshkrim i shkurtër i funksionit.

numërim behavior enum ( Behavior )

Opsionale. Specifikon funksionin Sjellja. Aktualisht mbështetet vetëm nga metoda BidiGenerateContent.

objekti parameters object ( Schema )

Opsionale. Përshkruan parametrat e këtij funksioni. Pasqyron vargun e objektit të parametrit Open API 3.03. Çelësi: emri i parametrit. Emrat e parametrave janë të ndjeshëm ndaj shkronjave të mëdha dhe të vogla. Vlera e skemës: Skema që përcakton llojin e përdorur për parametrin.

parametersJsonSchema value ( Value format)

Opsionale. Përshkruan parametrat e funksionit në formatin JSON Schema. Skema duhet të përshkruajë një objekt ku vetitë janë parametrat e funksionit. Për shembull:

{
  "type": "object",
  "properties": {
    "name": { "type": "string" },
    "age": { "type": "integer" }
  },
  "additionalProperties": false,
  "required": ["name", "age"],
  "propertyOrdering": ["name", "age"]
}

Kjo fushë është reciprokisht ekskluzive me parameters .

objekt response object ( Schema )

Opsionale. Përshkruan rezultatin nga ky funksion në formatin JSON Schema. Pasqyron Objektin e Përgjigjes së Open API 3.03. Skema përcakton llojin e përdorur për vlerën e përgjigjes së funksionit.

value ( Value format) responseJsonSchema (formati i vlerës)

Opsionale. Përshkruan rezultatin nga ky funksion në formatin JSON Schema. Vlera e specifikuar nga skema është vlera e përgjigjes së funksionit.

Kjo fushë është reciprokisht ekskluzive me response .

Përfaqësimi JSON
{
  "name": string,
  "description": string,
  "behavior": enum (Behavior),
  "parameters": {
    object (Schema)
  },
  "parametersJsonSchema": value,
  "response": {
    object (Schema)
  },
  "responseJsonSchema": value
}

Skema

Objekti Schema lejon përcaktimin e llojeve të të dhënave hyrëse dhe dalëse. Këto lloje mund të jenë objekte, por edhe primitive dhe vargje. Përfaqëson një nëngrup të zgjedhur të një objekti skeme OpenAPI 3.0 .

Fushat
type enum ( Type )

E detyrueshme. Lloji i të dhënave.

format string

Opsionale. Formati i të dhënave. Lejohet çdo vlerë, por shumica nuk aktivizojnë ndonjë funksionalitet të veçantë.

string title

Opsionale. Titulli i skemës.

string description

Opsionale. Një përshkrim i shkurtër i parametrit. Ky mund të përmbajë shembuj përdorimi. Përshkrimi i parametrit mund të formatohet si Markdown.

boolean nullable

Opsionale. Tregon nëse vlera mund të jetë null.

vargu i string enum[]

Opsionale. Vlerat e mundshme të elementit Type.STRING me formatin enum. Për shembull, mund të përcaktojmë një Drejtim Enum si: {type:STRING, format:enum, enum:["LINDJE", VERI", "JUG", "PERËNDIM"]}

vargu maxItems string ( int64 format)

Opsionale. Numri maksimal i elementeve për Type.ARRAY.

Vargu minItems string ( int64 format)

Opsionale. Numri minimal i elementeve për Type.ARRAY.

harta properties map (key: string, value: object ( Schema ))

Opsionale. Vetitë e Tipit.OBJECT.

Një objekt që përmban një listë çiftesh "key": value :. Shembull: { "name": "wrench", "mass": "1.3kg", "count": "3" } .

string required[]

Opsionale. Vetitë e kërkuara të Type.OBJECT.

minProperties string ( int64 format)

Opsionale. Numri minimal i vetive për Type.OBJECT.

vargu maxProperties string ( int64 format)

Opsionale. Numri maksimal i vetive për Type.OBJECT.

Vargu i gjatësisë minLength string ( int64 format)

Opsionale. FUSHAT E SKEMËS PËR TIPIN STRING Gjatësia minimale e Tipit.STRING

vargu maxLength string ( int64 format)

Opsionale. Gjatësia maksimale e Llojit.STRING

pattern string

Opsionale. Modeli i Tipit.STRING për të kufizuar një varg në një shprehje të rregullt.

example value ( Value format)

Opsionale. Shembull i objektit. Do të plotësohet vetëm kur objekti është rrënja.

objekti anyOf[] object ( Schema )

Opsionale. Vlera duhet të validohet kundrejt çdo (një ose më shumë) nënskemave në listë.

string propertyOrdering[]

Opsionale. Renditja e vetive. Nuk është një fushë standarde në specifikimin e hapur të api-t. Përdoret për të përcaktuar renditjen e vetive në përgjigje.

vlera default value ( Value format)

Opsionale. Vlera e parazgjedhur e fushës. Sipas Skemës JSON, kjo fushë është menduar për gjeneratorët e dokumentacionit dhe nuk ndikon në validim. Kështu, përfshihet këtu dhe injorohet në mënyrë që zhvilluesit që dërgojnë skema me një fushë default të mos marrin gabime të fushës së panjohur.

objekti i items object ( Schema )

Opsionale. Skema e elementeve të Type.ARRAY.

number minimum

Opsionale. FUSHAT E SKEMËS PËR TIPIN INTEGER dhe NUMËR Vlera minimale e TIPI.INTEGER dhe TIPI.NUMËR

number maximum

Opsionale. Vlera maksimale e Type.INTEGER dhe Type.NUMBER

Përfaqësimi JSON
{
  "type": enum (Type),
  "format": string,
  "title": string,
  "description": string,
  "nullable": boolean,
  "enum": [
    string
  ],
  "maxItems": string,
  "minItems": string,
  "properties": {
    string: {
      object (Schema)
    },
    ...
  },
  "required": [
    string
  ],
  "minProperties": string,
  "maxProperties": string,
  "minLength": string,
  "maxLength": string,
  "pattern": string,
  "example": value,
  "anyOf": [
    {
      object (Schema)
    }
  ],
  "propertyOrdering": [
    string
  ],
  "default": value,
  "items": {
    object (Schema)
  },
  "minimum": number,
  "maximum": number
}

Lloji

Lloji përmban listën e llojeve të të dhënave OpenAPI siç përcaktohen nga https://spec.openapis.org/oas/v3.0.3#data-types

Numërime
TYPE_UNSPECIFIED Nuk specifikohet, nuk duhet të përdoret.
STRING Lloji i vargut.
NUMBER Lloji i numrit.
INTEGER Lloji i numrit të plotë.
BOOLEAN Lloji boolean.
ARRAY Lloji i vargut.
OBJECT Lloji i objektit.
NULL Lloji Null.

Sjellje

Përcakton sjelljen e funksionit. Vlera e parazgjedhur është BLOCKING .

Numërime
UNSPECIFIED Kjo vlerë nuk përdoret.
BLOCKING Nëse është vendosur, sistemi do të presë për të marrë përgjigjen e funksionit përpara se të vazhdojë bisedën.
NON_BLOCKING Nëse vendoset, sistemi nuk do të presë për të marrë përgjigjen e funksionit. Në vend të kësaj, ai do të përpiqet të trajtojë përgjigjet e funksionit kur ato bëhen të disponueshme, duke ruajtur njëkohësisht bisedën midis përdoruesit dhe modelit.

Kërkimi në Google

Mjet për të marrë të dhëna publike të uebit për tokëzim, mundësuar nga Google.

Fushat
objekti dynamicRetrievalConfig object ( DynamicRetrievalConfig )

Specifikon konfigurimin dinamik të rikthimit për burimin e dhënë.

Përfaqësimi JSON
{
  "dynamicRetrievalConfig": {
    object (DynamicRetrievalConfig)
  }
}

Konfigurimi i Rikthimit Dinamike

Përshkruan opsionet për të personalizuar rikthimin dinamik.

Fushat
numërimi i mode enum ( Mode )

Modaliteti i parashikuesit që do të përdoret në rikthimin dinamik.

number dynamicThreshold

Pragu që do të përdoret në rikthimin dinamik. Nëse nuk është vendosur, përdoret një vlerë e parazgjedhur e sistemit.

Përfaqësimi JSON
{
  "mode": enum (Mode),
  "dynamicThreshold": number
}

Modaliteti

Modaliteti i parashikuesit që do të përdoret në rikthimin dinamik.

Numërime
MODE_UNSPECIFIED Gjithmonë aktivizo rikthimin.
MODE_DYNAMIC Ekzekutoni rikuperimin vetëm kur sistemi vendos se është e nevojshme.

Ekzekutimi i Kodit

Ky lloj nuk ka fusha.

Mjet që ekzekuton kodin e gjeneruar nga modeli dhe automatikisht e kthen rezultatin në model.

Shihni gjithashtu ExecutableCode dhe CodeExecutionResult të cilat gjenerohen vetëm kur përdoret ky mjet.

Kërkimi në Google

Lloji i mjetit të Kërkimit në Google. Mjet për të mbështetur Kërkimin në Google në Model. Mundësuar nga Google.

Fushat
objekti timeRangeFilter object ( Interval )

Optional. Filter search results to a specific time range. If customers set a start time, they must set an end time (and vice versa).

searchTypes object ( SearchTypes )

Optional. The set of search types to enable. If not set, web search is enabled by default.

JSON representation
{
  "timeRangeFilter": {
    object (Interval)
  },
  "searchTypes": {
    object (SearchTypes)
  }
}

Intervali

Represents a time interval, encoded as a Timestamp start (inclusive) and a Timestamp end (exclusive).

The start must be less than or equal to the end. When the start equals the end, the interval is empty (matches no time). When both start and end are unspecified, the interval matches any time.

Fushat
startTime string ( Timestamp format)

Optional. Inclusive start of the interval.

If specified, a Timestamp matching this interval will have to be the same or after the start.

Uses RFC 3339, where generated output will always be Z-normalized and use 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30" .

endTime string ( Timestamp format)

Optional. Exclusive end of the interval.

If specified, a Timestamp matching this interval will have to be before the end.

Uses RFC 3339, where generated output will always be Z-normalized and use 0, 3, 6 or 9 fractional digits. Offsets other than "Z" are also accepted. Examples: "2014-10-02T15:01:23Z" , "2014-10-02T15:01:23.045123456Z" or "2014-10-02T15:01:23+05:30" .

JSON representation
{
  "startTime": string,
  "endTime": string
}

SearchTypes

Different types of search that can be enabled on the GoogleSearch tool.

Fushat
JSON representation
{
  "webSearch": {
    object (WebSearch)
  },
  "imageSearch": {
    object (ImageSearch)
  }
}

WebSearch

This type has no fields.

Standard web search for grounding and related configurations.

ImageSearch

This type has no fields.

Image search for grounding and related configurations.

ComputerUse

Computer Use tool type.

Fushat
environment enum ( Environment )

Required. The environment being operated.

excludedPredefinedFunctions[] string

Optional. By default, predefined functions are included in the final model call. Some of them can be explicitly excluded from being automatically included. This can serve two purposes: 1. Using a more restricted / different action space. 2. Improving the definitions / instructions of predefined functions.

JSON representation
{
  "environment": enum (Environment),
  "excludedPredefinedFunctions": [
    string
  ]
}

Mjedisi

Represents the environment being operated, such as a web browser.

Enums
ENVIRONMENT_UNSPECIFIED Defaults to browser.
ENVIRONMENT_BROWSER Operates in a web browser.

UrlContext

This type has no fields.

Tool to support URL context retrieval.

FileSearch

The FileSearch tool that retrieves knowledge from Semantic Retrieval corpora. Files are imported to Semantic Retrieval corpora using the ImportFile API.

Fushat
fileSearchStoreNames[] string

Required. The names of the fileSearchStores to retrieve from. Example: fileSearchStores/my-file-search-store-123

metadataFilter string

Optional. Metadata filter to apply to the semantic retrieval documents and chunks.

topK integer

Optional. The number of semantic retrieval chunks to retrieve.

JSON representation
{
  "fileSearchStoreNames": [
    string
  ],
  "metadataFilter": string,
  "topK": integer
}

McpServer

A MCPServer is a server that can be called by the model to perform actions. It is a server that implements the MCP protocol. Next ID: 5

Fushat
name string

The name of the MCPServer.

transport Union type
The transport to use to connect to the MCPServer. transport can be only one of the following:
streamableHttpTransport object ( StreamableHttpTransport )

A transport that can stream HTTP requests and responses.

JSON representation
{
  "name": string,

  // transport
  "streamableHttpTransport": {
    object (StreamableHttpTransport)
  }
  // Union type
}

StreamableHttpTransport

A transport that can stream HTTP requests and responses. Next ID: 6

Fushat
url string

The full URL for the MCPServer endpoint. Example: "https://api.example.com/mcp"

headers map (key: string, value: string)

Optional: Fields for authentication headers, timeouts, etc., if needed.

An object containing a list of "key": value pairs. Example: { "name": "wrench", "mass": "1.3kg", "count": "3" } .

timeout string ( Duration format)

HTTP timeout for regular operations.

A duration in seconds with up to nine fractional digits, ending with ' s '. Example: "3.5s" .

sseReadTimeout string ( Duration format)

Timeout for SSE read operations.

A duration in seconds with up to nine fractional digits, ending with ' s '. Example: "3.5s" .

terminateOnClose boolean

Whether to close the client session when the transport closes.

JSON representation
{
  "url": string,
  "headers": {
    string: string,
    ...
  },
  "timeout": string,
  "sseReadTimeout": string,
  "terminateOnClose": boolean
}

GoogleMaps

The GoogleMaps Tool that provides geospatial context for the user's query.

Fushat
enableWidget boolean

Optional. Whether to return a widget context token in the GroundingMetadata of the response. Developers can use the widget context token to render a Google Maps widget with geospatial context related to the places that the model references in the response.

JSON representation
{
  "enableWidget": boolean
}

ToolConfig

The Tool configuration containing parameters for specifying Tool use in the request.

Fushat
functionCallingConfig object ( FunctionCallingConfig )

Optional. Function calling config.

retrievalConfig object ( RetrievalConfig )

Optional. Retrieval config.

includeServerSideToolInvocations boolean

Optional. If true, the API response will include the server-side tool calls and responses within the Content message. This allows clients to observe the server's tool interactions.

JSON representation
{
  "functionCallingConfig": {
    object (FunctionCallingConfig)
  },
  "retrievalConfig": {
    object (RetrievalConfig)
  },
  "includeServerSideToolInvocations": boolean
}

FunctionCallingConfig

Configuration for specifying function calling behavior.

Fushat
mode enum ( Mode )

Optional. Specifies the mode in which function calling should execute. If unspecified, the default value will be set to AUTO.

allowedFunctionNames[] string

Optional. A set of function names that, when provided, limits the functions the model will call.

This should only be set when the Mode is ANY or VALIDATED. Function names should match [FunctionDeclaration.name]. When set, model will predict a function call from only allowed function names.

JSON representation
{
  "mode": enum (Mode),
  "allowedFunctionNames": [
    string
  ]
}

Modaliteti

Defines the execution behavior for function calling by defining the execution mode.

Enums
MODE_UNSPECIFIED Unspecified function calling mode. This value should not be used.
AUTO Default model behavior, model decides to predict either a function call or a natural language response.
ANY Model is constrained to always predicting a function call only. If "allowedFunctionNames" are set, the predicted function call will be limited to any one of "allowedFunctionNames", else the predicted function call will be any one of the provided "functionDeclarations".
NONE Model will not predict any function call. Model behavior is same as when not passing any function declarations.
VALIDATED Model decides to predict either a function call or a natural language response, but will validate function calls with constrained decoding. If "allowedFunctionNames" are set, the predicted function call will be limited to any one of "allowedFunctionNames", else the predicted function call will be any one of the provided "functionDeclarations".

RetrievalConfig

Retrieval config.

Fushat
latLng object ( LatLng )

Optional. The location of the user.

languageCode string

Optional. The language code of the user. Language code for content. Use language tags defined by BCP47 .

JSON representation
{
  "latLng": {
    object (LatLng)
  },
  "languageCode": string
}

LatLng

An object that represents a latitude/longitude pair. This is expressed as a pair of doubles to represent degrees latitude and degrees longitude. Unless specified otherwise, this object must conform to the WGS84 standard . Values must be within normalized ranges.

Fushat
latitude number

The latitude in degrees. It must be in the range [-90.0, +90.0].

longitude number

The longitude in degrees. It must be in the range [-180.0, +180.0].

JSON representation
{
  "latitude": number,
  "longitude": number
}

UsageMetadata

Metadata on the usage of the cached content.

Fushat
totalTokenCount integer

Total number of tokens that the cached content consumes.

JSON representation
{
  "totalTokenCount": integer
}