Gemini lejon kombinimin e mjeteve të integruara , të tilla si google_search dhe thirrjen e funksioneve (të njohura edhe si mjete të personalizuara ) në një gjeneratë të vetme duke ruajtur dhe ekspozuar historikun e kontekstit të thirrjeve të mjeteve. Kombinimet e mjeteve të integruara dhe të personalizuara lejojnë rrjedha pune komplekse, agjentike, ku, për shembull, modeli mund të bazohet në të dhëna të internetit në kohë reale përpara se të thërrasë logjikën tuaj specifike të biznesit.
Ja një shembull që mundëson kombinime të mjeteve të integruara dhe të personalizuara me google_search dhe një funksion të personalizuar getWeather :
Python
from google import genai
from google.genai import types
client = genai.Client()
getWeather = {
"name": "getWeather",
"description": "Gets the weather for a requested city.",
"parameters": {
"type": "object",
"properties": {
"city": {
"type": "string",
"description": "The city and state, e.g. Utqiaġvik, Alaska",
},
},
"required": ["city"],
},
}
# Turn 1: Initial request with Google Search (built-in) and getWeather (custom) tools enabled
response = client.models.generate_content(
model="gemini-3-flash-preview",
contents="What is the northernmost city in the United States? What's the weather like there today?",
config=types.GenerateContentConfig(
tools=[
types.Tool(
google_search=types.ToolGoogleSearch(), # Built-in tool
function_declarations=[getWeather] # Custom tool
),
],
include_server_side_tool_invocations=True
),
)
for part in response.candidates[0].content.parts:
if part.tool_call:
print(f"Tool call: {part.tool_call.tool_type} (ID: {part.tool_call.id})")
if part.tool_response:
print(f"Tool response: {part.tool_response.tool_type} (ID: {part.tool_response.id})")
if part.function_call:
print(f"Function call: {part.function_call.name} (ID: {part.function_call.id})")
# Turn 2: Manually build history to circulate both tool and function context
history = [
types.Content(
role="user",
parts=[types.Part(text="What is the northernmost city in the United States? What's the weather like there today?")]
),
# Response from Turn 1 includes tool_call, tool_response, and thought_signatures
response.candidates[0].content,
# Return the function_response
types.Content(
role="user",
parts=[types.Part(
function_response=types.FunctionResponse(
name="getWeather",
response={"response": "Very cold. 22 degrees Fahrenheit."},
id=response.candidates[0].content.parts[2].function_call.id # Match the ID from the function_call
)
)]
)
]
response_2 = client.models.generate_content(
model="gemini-3-flash-preview",
contents=history,
config=types.GenerateContentConfig(
tools=[
types.Tool(
google_search=types.ToolGoogleSearch(),
function_declarations=[getWeather]
),
],
# This flag needs to be enabled for built-in tool context circulation and tool combination
include_server_side_tool_invocations=True
),
)
for part in response_2.candidates[0].content.parts:
if part.text:
print(part.text)
Javascript
import { GoogleGenAI } from '@google/genai';
const client = new GoogleGenAI({});
const getWeather = {
name: "getWeather",
description: "Get the weather in a given location",
parameters: {
type: "OBJECT",
properties: {
location: {
type: "STRING",
description: "The city and state, e.g. San Francisco, CA"
}
},
required: ["location"]
}
};
async function run() {
const model = client.getGenerativeModel({
model: "gemini-3-flash-preview",
});
const tools = [
{ googleSearch: {} },
{ functionDeclarations: [getWeather] }
];
// This flag needs to be enabled for built-in tool context circulation and tool combination
const toolConfig = { includeServerSideToolInvocations: true };
// Turn 1: Initial request with Google Search (built-in) and getWeather (custom) tools enabled
const result1 = await model.generateContent({
contents: [{role: "user", parts: [{text: "What is the northernmost city in the United States? What's the weather like there today?"}]}],
tools: tools,
toolConfig: toolConfig,
});
const response1 = result1.response;
for (const part of response1.candidates[0].content.parts) {
if (part.toolCall) {
console.log(`Tool call: ${part.toolCall.toolType} (ID: ${part.toolCall.id})`);
}
if (part.toolResponse) {
console.log(`Tool response: ${part.toolResponse.toolType} (ID: ${part.toolResponse.id})`);
}
if (part.functionCall) {
console.log(`Function call: ${part.functionCall.name} (ID: ${part.functionCall.id})`);
}
}
const functionCallId = response1.candidates[0].content.parts.find(p => p.functionCall)?.functionCall?.id;
// Turn 2: Manually build history to circulate both tool and function context
const history = [
{
role: "user",
parts:[{text: "What is the northernmost city in the United States? What's the weather like there today?"}]
},
// Response from Turn 1 includes tool_call, tool_response, and thought_signatures
response1.candidates[0].content,
// Return the function_response
{
role: "user",
parts: [{
functionResponse: {
name: "getWeather",
response: {response: "Very cold. 22 degrees Fahrenheit."},
id: functionCallId // Match the ID from the function_call
}
}]
}
];
const result2 = await model.generateContent({
contents: history,
tools: tools,
toolConfig: toolConfig,
});
for (const part of result2.response.candidates[0].content.parts) {
if (part.text) {
console.log(part.text);
}
}
}
run();
Shko
package main
import (
"context"
"fmt"
"log"
"os"
"github.com/google/generative-ai-go/genai"
"google.golang.org/api/option"
)
func main() {
ctx := context.Background()
client, err := genai.NewClient(ctx, option.WithAPIKey(os.Getenv("GEMINI_API_KEY")))
if err != nil {
log.Exit(err)
}
defer client.Close()
getWeather := &genai.FunctionDeclaration{
Name: "getWeather",
Description: "Get the weather in a given location",
Parameters: &genai.Schema{
Type: genai.Object,
Properties: map[string]*genai.Schema{
"location": {
Type: genai.String,
Description: "The city and state, e.g. San Francisco, CA",
},
},
Required: []string{"location"},
},
}
model := client.GenerativeModel("gemini-3-flash-preview")
model.Tools = []*genai.Tool{
{GoogleSearch: &genai.GoogleSearch{}}, // Built-in tool
{FunctionDeclarations: []*genai.FunctionDeclaration{getWeather}}, // Custom tool
}
ist := true
model.ToolConfig = &genai.ToolConfig{
IncludeServerSideToolInvocations: &ist, // This flag needs to be enabled for built-in tool context circulation and tool combination
}
chat := model.StartChat()
// Turn 1: Initial request with Google Search (built-in) and getWeather (custom) tools enabled
prompt := genai.Text("What is the northernmost city in the United States? What's the weather like there today?")
resp1, err := chat.SendMessage(ctx, prompt)
if err != nil {
log.Exitf("SendMessage failed: %v", err)
}
if resp1 == nil || len(resp1.Candidates) == 0 || resp1.Candidates[0].Content == nil {
log.Exit("empty response from model")
}
var functionCallID string
for _, part := range resp1.Candidates[0].Content.Parts {
switch p := part.(type) {
case genai.FunctionCall:
fmt.Printf("Function call: %s (ID: %s)\n", p.Name, p.ID)
if p.Name == "getWeather" {
functionCallID = p.ID
}
case genai.ToolCallPart:
fmt.Printf("Tool call: %s (ID: %s)\n", p.ToolType, p.ID)
case genai.ToolResponsePart:
fmt.Printf("Tool response: %s (ID: %s)\n", p.ToolType, p.ID)
}
}
if functionCallID == "" {
log.Exit("no getWeather function call in response")
}
// Turn 2: Provide function result back to model.
// Chat history automatically includes tool_call, tool_response, and thought_signatures from Turn 1.
fr := genai.FunctionResponse{
Name: "getWeather",
ID: functionCallID,
Response: map[string]any{
"response": "Very cold. 22 degrees Fahrenheit.",
},
}
resp2, err := chat.SendMessage(ctx, fr)
if err != nil {
log.Exitf("SendMessage for turn 2 failed: %v", err)
}
if resp2 == nil || len(resp2.Candidates) == 0 || resp2.Candidates[0].Content == nil {
log.Exit("empty response from model in turn 2")
}
for _, part := range resp2.Candidates[0].Content.Parts {
if txt, ok := part.(genai.Text); ok {
fmt.Println(string(txt))
}
}
}
PUSHTIM
# Turn 1: Initial request with Google Search (built-in) and getWeather (custom) tools enabled
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"contents": [{
"role": "user",
"parts": [{
"text": "What is the northernmost city in the United States? What'\''s the weather like there today?"
}]
}],
"tools": [{
"googleSearch": {}
}, {
"functionDeclarations": [{
"name": "getWeather",
"description": "Get the weather in a given location",
"parameters": {
"type": "OBJECT",
"properties": {
"location": {
"type": "STRING",
"description": "The city and state, e.g. San Francisco, CA"
}
},
"required": ["location"]
}
}]
}],
"toolConfig": {
"includeServerSideToolInvocations": true
}
}'
# Turn 2: Manually build history to circulate both tool and function context
# The following request assumes you have captured candidates[0].content from Turn 1 response,
# and extracted function_call.id for getWeather.
# Replace FUNCTION_CALL_ID and insert candidate content from turn 1.
curl -X POST "https://generativelanguage.googleapis.com/v1beta/models/gemini-3-flash-preview:generateContent" \
-H "Content-Type: application/json" \
-H "x-goog-api-key: $GEMINI_API_KEY" \
-d '{
"contents": [
{
"role": "user",
"parts": [{"text": "What is the northernmost city in the United States? What'\''s the weather like there today?"}]
},
YOUR_CANDIDATE_CONTENT_FROM_TURN_1_RESPONSE,
{
"role": "user",
"parts": [{
"functionResponse": {
"name": "getWeather",
"id": "FUNCTION_CALL_ID",
"response": {"response": "Very cold. 22 degrees Fahrenheit."}
}
}]
}
],
"tools": [{
"googleSearch": {}
}, {
"functionDeclarations": [{
"name": "getWeather",
"description": "Get the weather in a given location",
"parameters": {
"type": "OBJECT",
"properties": {
"location": {
"type": "STRING",
"description": "The city and state, e.g. San Francisco, CA"
}
},
"required": ["location"]
}
}]
}],
"toolConfig": {
"includeServerSideToolInvocations": true
}
}'
Si funksionon
Modelet Gemini 3 përdorin qarkullimin e kontekstit të mjeteve për të mundësuar kombinime mjetesh të integruara dhe të personalizuara. Qarkullimi i kontekstit të mjeteve bën të mundur ruajtjen dhe ekspozimin e kontekstit të mjeteve të integruara dhe ndarjen e tij me mjete të personalizuara në të njëjtën thirrje nga radha në raund.
Aktivizo kombinimin e mjeteve
- Duhet ta caktoni flamurin
include_server_side_tool_invocationsnëtruepër të aktivizuar qarkullimin e kontekstit të mjetit. - Përfshini
function_declarations, së bashku me mjetet e integruara që dëshironi të përdorni, për të aktivizuar sjelljen e kombinimit.- Nëse nuk përfshini
function_declarations, qarkullimi i kontekstit të mjetit do të veprojë ende mbi mjetet e integruara të përfshira, për sa kohë që flamuri është i vendosur.
- Nëse nuk përfshini
API kthen pjesë
Në një përgjigje të vetme, API kthen pjesët toolCall dhe toolResponse për thirrjen e mjetit të integruar. Për thirrjen e funksionit (mjet i personalizuar), API kthen pjesën e thirrjes functionCall , së cilës përdoruesi i jep pjesën functionResponse në kthesën tjetër.
-
toolCalldhetoolResponse: API i kthen këto pjesë për të ruajtur kontekstin se cilat mjete ekzekutohen në anën e serverit dhe rezultatin e ekzekutimit të tyre, për kthesën tjetër. -
functionCalldhefunctionResponse: API-ja ia dërgon thirrjen e funksionit përdoruesit për ta plotësuar, dhe përdoruesi e dërgon rezultatin përsëri në përgjigjen e funksionit (këto pjesë janë standarde për të gjitha thirrjet e funksioneve në Gemini API, jo unike për veçorinë e kombinimit të mjeteve). - (Vetëm mjeti i ekzekutimit të kodit )
executableCodedhecodeExecutionResult: Kur përdoret mjeti i Ekzekutimit të Kodit, në vend tëfunctionCalldhefunctionResponse, API kthenexecutableCode(kodi i gjeneruar nga modeli që duhet të ekzekutohet) dhecodeExecutionResult(rezultati i kodit të ekzekutueshëm).
Duhet t’i ktheni të gjitha pjesët, duke përfshirë të gjitha fushat që ato përmbajnë, përsëri në model në çdo kthesë për të ruajtur kontekstin dhe për të aktivizuar kombinimet e mjeteve.
Fushat kritike në pjesët e kthyera
Disa pjesë të kthyera nga API do të përfshijnë fushat id , tool_type dhe thought_signature . Këto fusha janë kritike për ruajtjen e kontekstit të mjetit (dhe për këtë arsye kritike për kombinimet e mjeteve); ju duhet të ktheni të gjitha pjesët siç jepen në përgjigje në kërkesat tuaja të mëvonshme.
-
id: Një identifikues unik që lidh një thirrje me përgjigjen e saj.idvendoset në të gjitha përgjigjet e thirrjes së funksionit , pavarësisht nga qarkullimi i kontekstit të mjetit. Ju duhet të jepni të njëjtinidnë përgjigjen e funksionit që API ofron në thirrjen e funksionit. Mjetet e integruara ndajnë automatikishtidmidis thirrjes së mjetit dhe përgjigjes së mjetit.- Gjendet në të gjitha pjesët që lidhen me mjetet:
toolCall,toolResponse,functionCall,functionResponse,executableCode,codeExecutionResult
- Gjendet në të gjitha pjesët që lidhen me mjetet:
-
tool_type: Identifikon mjetin specifik që po përdoret; emrin e mjetit të integruar literal ose (p.sh.URL_CONTEXT) ose funksionit (p.sh.getWeather).- Gjendet në pjesët
toolCalldhetoolResponse.
- Gjendet në pjesët
-
thought_signature: Konteksti aktual i enkriptuar i integruar në secilën pjesë i kthyer nga API . Konteksti nuk mund të rindërtohet pa nënshkrime mendimi; nëse nuk ktheni nënshkrimet e mendimit për të gjitha pjesët në çdo kthesë, modeli do të ketë gabim.- Gjendet në të gjitha pjesët.
Të dhëna specifike për mjetin
Disa mjete të integruara kthejnë argumente të të dhënave të dukshme për përdoruesin, specifike për llojin e mjetit.
| Mjet | Argumentet e thirrjes së mjetit të dukshëm të përdoruesit (nëse ka) | Përgjigja e dukshme e mjetit të përdoruesit (nëse ka) |
|---|---|---|
| GOOGLE_SEARCH | queries | search_suggestions |
| GOOGLE_MAPS | queries | placesgoogle_maps_widget_context_token |
| URL_CONTEXT | urlsURL-të që do të shfletohen | urls_metadataretrieved_url : URL-të e shfletuaraurl_retrieval_status : Statusi i shfletimit |
| FILE_SEARCH | Asnjë | Asnjë |
Shembull strukture kërkese për kombinim mjetesh
Struktura e mëposhtme e kërkesës tregon strukturën e kërkesës së kërkesës: "Cili është qyteti më verior në Shtetet e Bashkuara? Si është moti atje sot?". Ajo kombinon tre mjete: mjetet e integruara Gemini google_search dhe code_execution , dhe një funksion të personalizuar get_weather .
{
"model": "models/gemini-3-flash-preview",
"contents": [{
"parts": [{
"text": "What is the northernmost city in the United States? What's the weather like there today?"
}],
"role": "user"
}, {
"parts": [{
"thoughtSignature": "...",
"toolCall": {
"toolType": "GOOGLE_SEARCH_WEB",
"args": {
"queries": ["northernmost city in the United States"]
},
"id": "a7b3k9p2"
}
}, {
"thoughtSignature": "...",
"toolResponse": {
"toolType": "GOOGLE_SEARCH_WEB",
"response": {
"search_suggestions": "..."
},
"id": "a7b3k9p2"
}
}, {
"functionCall": {
"name": "getWeather",
"args": {
"city": "Utqiaġvik, Alaska"
},
"id": "m4q8z1v6"
},
"thoughtSignature": "..."
}],
"role": "model"
}, {
"parts": [{
"functionResponse": {
"name": "getWeather",
"response": {
"response": "Very cold. 22 degrees Fahrenheit."
},
"id": "m4q8z1v6"
}
}],
"role": "user"
}],
"tools": [{
"functionDeclarations": [{
"name": "getWeather"
}]
}, {
"googleSearch": {
}
}, {
"codeExecution": {
}
}],
"toolConfig": {
"includeServerSideToolInvocations": true
}
}
Tokenat dhe çmimet
Vini re se pjesët e toolCall dhe toolResponse në kërkesa llogariten për prompt_token_count . Meqenëse këto hapa të ndërmjetëm të mjetit tani janë të dukshëm dhe ju kthehen, ato janë pjesë e historikut të bisedës. Ky është rasti vetëm për kërkesat , jo për përgjigjet .
Mjeti i Kërkimit në Google është një përjashtim nga ky rregull. Kërkimi në Google tashmë zbaton modelin e vet të çmimeve në nivelin e pyetjes, kështu që tokenët nuk tarifohen dy herë (shih faqen e Çmimeve ).
Lexoni faqen e Tokenave për më shumë informacion.
Kufizime
- Modaliteti i parazgjedhur i
VALIDATED(modalitetiAUTOnuk mbështetet) kur aktivizohet flamuriinclude_server_side_tool_invocations - Mjetet e integruara si
google_searchmbështeten në informacionin e vendndodhjes dhe kohës aktuale, kështu që nësesystem_instructionosefunction_declaration.descriptionjuaj ka informacion kontradiktor të vendndodhjes dhe kohës, funksioni i kombinimit të mjeteve mund të mos funksionojë mirë.
Mjetet e mbështetura
Mjeti standard i qarkullimit të kontekstit zbatohet për mjetet nga ana e serverit (të integruara). Ekzekutimi i kodit është gjithashtu një mjet nga ana e serverit, por ka zgjidhjen e vet të integruar për qarkullimin e kontekstit. Përdorimi i kompjuterit dhe thirrja e funksioneve janë mjete nga ana e klientit dhe gjithashtu kanë zgjidhje të integruara për qarkullimin e kontekstit.
| Mjet | Ana e ekzekutimit | Mbështetje për Qarkullimin e Kontekstit |
|---|---|---|
| Kërkimi në Google | Nga ana e serverit | Mbështetur |
| Hartat e Google-it | Nga ana e serverit | Mbështetur |
| Konteksti i URL-së | Nga ana e serverit | Mbështetur |
| Kërkimi i skedarëve | Nga ana e serverit | Mbështetur |
| Ekzekutimi i Kodit | Nga ana e serverit | Mbështetur (i integruar, përdor pjesët executableCode dhe codeExecutionResult ) |
| Përdorimi i kompjuterit | Nga ana e klientit | Mbështetur (i integruar, përdor pjesët functionCall dhe functionResponse ) |
| Funksione të personalizuara | Nga ana e klientit | Mbështetur (i integruar, përdor pjesët functionCall dhe functionResponse ) |
Çfarë vjen më pas
- Mësoni më shumë rreth thirrjes së funksioneve në Gemini API.
- Eksploroni mjetet e mbështetura: