A partir de 29 de abril de 2025, os modelos Gemini 1.5 Pro e Gemini 1.5 Flash não estarão disponíveis em projetos que não os usaram antes, incluindo novos projetos. Para mais detalhes, consulte Versões e ciclo de vida do modelo.
Mantenha tudo organizado com as coleções Salve e categorize o conteúdo com base nas suas preferências.
Este guia fornece uma referência para usar a chamada de função com a API Gemini. Ele abrange os seguintes tópicos:
Modelos compatíveis:lista os modelos que oferecem suporte à chamada de função.
Exemplo de sintaxe:mostra a estrutura básica de uma solicitação de API de chamada de função.
Parâmetros da API:detalha os parâmetros usados na chamada de função, como FunctionDeclaration e FunctionCallingConfig.
Exemplos:fornece exemplos de código para enviar declarações de função e configurar o comportamento de chamada de função.
A chamada de função melhora a capacidade do LLM de fornecer respostas relevantes e contextuais.
Com a API Function Calling, é possível fornecer funções personalizadas a um modelo de IA generativa. O modelo não invoca essas funções diretamente. Em vez disso, ele gera uma saída de dados estruturados que especifica o nome da função e os argumentos sugeridos. Essa saída permite chamar APIs ou sistemas de informação externos, como bancos de dados, sistemas de gestão de relacionamento com o cliente (CRM) e repositórios de documentos. É possível então fornecer a saída da API resultante de volta ao modelo para melhorar a qualidade da resposta.
Para uma visão geral conceitual da chamada de função, consulte Chamada de função.
Nesta seção, descrevemos os parâmetros para chamada de função. Para detalhes de implementação, consulte a seção Exemplos.
FunctionDeclaration
Uma FunctionDeclaration define uma função para a qual o modelo pode gerar entradas JSON, com base nas especificações OpenAPI 3.0.
Parâmetros
name
string
O nome da função a ser chamada. O nome precisa começar com uma letra ou um sublinhado. Ele pode conter letras (a-z, A-Z), números (0-9), sublinhados, pontos ou traços, com um tamanho máximo de 64 caracteres.
description
Opcional: string
Uma descrição da finalidade da função. O modelo usa essa descrição para decidir como e se a função será chamada. Para melhores resultados, recomendamos incluir uma descrição.
parameters
Opcional: Schema
Os parâmetros da função, descritos no formato de objeto de esquema JSON da OpenAPI.
response
Opcional: Schema
A saída da função, descrita no formato de objeto de esquema JSON da OpenAPI.
Um Schema define o formato dos dados de entrada e saída em uma chamada de função, com base na especificação de Esquema da OpenAPI 3.0.
Parâmetros
tipo
string
O tipo de dados. Deve atender a uma das seguintes condições:
STRING
INTEGER
BOOLEAN
NUMBER
ARRAY
OBJECT
description
Opcional: string
Uma descrição dos dados.
enum
Opcional: string[]
Os valores possíveis para um elemento de um tipo primitivo.
items
Opcional: Schema[]
O esquema dos elementos de um tipo ARRAY.
properties
Opcional: Schema
O esquema das propriedades de um tipo OBJECT.
required
Opcional: string[]
As propriedades obrigatórias de um tipo OBJECT.
nullable
Opcional: bool
Indica se o valor pode ser null.
FunctionCallingConfig
O FunctionCallingConfig permite controlar o comportamento do modelo e determinar qual função chamar.
Parâmetros
mode
Opcional: enum/string[]
AUTO: esse é o comportamento padrão. O modelo decide se quer chamar uma função ou responder com linguagem natural com base no contexto.
NONE: o modelo não chama nenhuma função.
ANY: o modelo é restrito a sempre prever uma chamada de função. Se você não fornecer allowed_function_names, o modelo vai escolher entre todas as declarações de função disponíveis. Se você fornecer allowed_function_names, o modelo vai escolher entre esse conjunto de funções.
allowed_function_names
Opcional: string[]
Uma lista de nomes de funções a serem chamadas. Só é possível definir isso quando o mode é ANY. Os nomes das funções precisam corresponder a um FunctionDeclaration.name. Quando o modo é ANY, o modelo prevê uma chamada de função da lista de nomes de função fornecida.
functionCall
Uma functionCall é uma previsão retornada do modelo. Ele contém o nome da função a ser chamada (functionDeclaration.name) e um objeto JSON estruturado com os parâmetros e os valores deles.
Parâmetros
name
string
O nome da função a ser chamada.
args
Struct
Os parâmetros da função e os valores deles no formato de objeto JSON.
Um functionResponse é a saída de um FunctionCall. Ele contém o nome da função que foi chamada e um objeto JSON estruturado com a saída da função. Você fornece essa resposta ao modelo para usar como contexto.
Parâmetros
name
string
O nome da função que foi chamada.
response
Struct
A resposta da função no formato de objeto JSON.
Exemplos
Enviar uma declaração de função
O exemplo a seguir mostra como enviar uma consulta e uma declaração de função ao modelo.
REST
Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:
PROJECT_ID=myproject LOCATION=us-central1 MODEL_ID=gemini-2.5-flash curl-XPOST\-H"Authorization: Bearer $(gcloudauthprint-access-token)"\-H"Content-Type: application/json"\https://${LOCATION}-aiplatform.googleapis.com/v1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent\-d'{ "contents": [{ "role": "user", "parts": [{ "text": "What is the weather in Boston?" }] }], "tools": [{ "functionDeclarations": [ { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "object", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616" } }, "required": [ "location" ] } } ] }] }'
SDK da IA generativa para Python
fromgoogleimportgenaifromgoogle.genai.typesimportGenerateContentConfig,HttpOptionsdefget_current_weather(location:str)-> str:"""Example method. Returns the current weather. Args: location: The city and state, e.g. San Francisco, CA """weather_map:dict[str,str]={"Boston, MA":"snowing","San Francisco, CA":"foggy","Seattle, WA":"raining","Austin, TX":"hot","Chicago, IL":"windy",}returnweather_map.get(location,"unknown")client=genai.Client(http_options=HttpOptions(api_version="v1"))model_id="gemini-2.5-flash"response=client.models.generate_content(model=model_id,contents="What is the weather like in Boston?",config=GenerateContentConfig(tools=[get_current_weather],temperature=0,),)print(response.text)# Example response:# The weather in Boston is sunny.
Node.js
const{VertexAI,FunctionDeclarationSchemaType,}=require('@google-cloud/vertexai');constfunctionDeclarations=[{function_declarations:[{name:'get_current_weather',description:'get weather in a given location',parameters:{type:FunctionDeclarationSchemaType.OBJECT,properties:{location:{type:FunctionDeclarationSchemaType.STRING},unit:{type:FunctionDeclarationSchemaType.STRING,enum:['celsius','fahrenheit'],},},required:['location'],},},],},];/** * TODO(developer): Update these variables before running the sample. */asyncfunctionfunctionCallingBasic(projectId='PROJECT_ID',location='us-central1',model='gemini-2.0-flash-001'){// Initialize Vertex with your Cloud project and locationconstvertexAI=newVertexAI({project:projectId,location:location});// Instantiate the modelconstgenerativeModel=vertexAI.preview.getGenerativeModel({model:model,});constrequest={contents:[{role:'user',parts:[{text:'What is the weather in Boston?'}]},],tools:functionDeclarations,};constresult=awaitgenerativeModel.generateContent(request);console.log(JSON.stringify(result.response.candidates[0].content));}
Java
importcom.google.cloud.vertexai.VertexAI;importcom.google.cloud.vertexai.api.Content;importcom.google.cloud.vertexai.api.FunctionDeclaration;importcom.google.cloud.vertexai.api.GenerateContentResponse;importcom.google.cloud.vertexai.api.Schema;importcom.google.cloud.vertexai.api.Tool;importcom.google.cloud.vertexai.api.Type;importcom.google.cloud.vertexai.generativeai.ChatSession;importcom.google.cloud.vertexai.generativeai.ContentMaker;importcom.google.cloud.vertexai.generativeai.GenerativeModel;importcom.google.cloud.vertexai.generativeai.PartMaker;importcom.google.cloud.vertexai.generativeai.ResponseHandler;importjava.io.IOException;importjava.util.Arrays;importjava.util.Collections;publicclassFunctionCalling{publicstaticvoidmain(String[]args)throwsIOException{// TODO(developer): Replace these variables before running the sample.StringprojectId="your-google-cloud-project-id";Stringlocation="us-central1";StringmodelName="gemini-2.0-flash-001";StringpromptText="What's the weather like in Paris?";whatsTheWeatherLike(projectId,location,modelName,promptText);}// A request involving the interaction with an external toolpublicstaticStringwhatsTheWeatherLike(StringprojectId,Stringlocation,StringmodelName,StringpromptText)throwsIOException{// Initialize client that will be used to send requests.// This client only needs to be created once, and can be reused for multiple requests.try(VertexAIvertexAI=newVertexAI(projectId,location)){FunctionDeclarationfunctionDeclaration=FunctionDeclaration.newBuilder().setName("getCurrentWeather").setDescription("Get the current weather in a given location").setParameters(Schema.newBuilder().setType(Type.OBJECT).putProperties("location",Schema.newBuilder().setType(Type.STRING).setDescription("location").build()).addRequired("location").build()).build();System.out.println("Function declaration:");System.out.println(functionDeclaration);// Add the function to a "tool"Tooltool=Tool.newBuilder().addFunctionDeclarations(functionDeclaration).build();// Start a chat session from a model, with the use of the declared function.GenerativeModelmodel=newGenerativeModel(modelName,vertexAI).withTools(Arrays.asList(tool));ChatSessionchat=model.startChat();System.out.println(String.format("Ask the question: %s",promptText));GenerateContentResponseresponse=chat.sendMessage(promptText);// The model will most likely return a function call to the declared// function `getCurrentWeather` with "Paris" as the value for the// argument `location`.System.out.println("\nPrint response: ");System.out.println(ResponseHandler.getContent(response));// Provide an answer to the model so that it knows what the result// of a "function call" is.Contentcontent=ContentMaker.fromMultiModalData(PartMaker.fromFunctionResponse("getCurrentWeather",Collections.singletonMap("currentWeather","sunny")));System.out.println("Provide the function response: ");System.out.println(content);response=chat.sendMessage(content);// See what the model replies nowSystem.out.println("Print response: ");StringfinalAnswer=ResponseHandler.getText(response);System.out.println(finalAnswer);returnfinalAnswer;}}}
Go
import("context""fmt""io"genai"google.golang.org/genai")//generateWithFuncCallshowshowtosubmitapromptandafunctiondeclarationtothemodel,//allowingittosuggestacalltothefunctiontofetchexternaldata.Returningthisdata//enablesthemodeltogenerateatextresponsethatincorporatesthedata.funcgenerateWithFuncCall(wio.Writer)error{ctx:=context.Background()client,err:=genai.NewClient(ctx, &genai.ClientConfig{HTTPOptions:genai.HTTPOptions{APIVersion:"v1"},})iferr!=nil{returnfmt.Errorf("failed to create genai client: %w",err)}weatherFunc:= &genai.FunctionDeclaration{Description:"Returns the current weather in a location.",Name:"getCurrentWeather",Parameters: &genai.Schema{Type:"object",Properties:map[string]*genai.Schema{"location":{Type:"string"},},Required:[]string{"location"},},}config:= &genai.GenerateContentConfig{Tools:[]*genai.Tool{{FunctionDeclarations:[]*genai.FunctionDeclaration{weatherFunc}},},Temperature:genai.Ptr(float32(0.0)),}modelName:="gemini-2.5-flash"contents:=[]*genai.Content{{Parts:[]*genai.Part{{Text:"What is the weather like in Boston?"},},Role:"user"},}resp,err:=client.Models.GenerateContent(ctx,modelName,contents,config)iferr!=nil{returnfmt.Errorf("failed to generate content: %w",err)}varfuncCall*genai.FunctionCallfor_,p:=rangeresp.Candidates[0].Content.Parts{ifp.FunctionCall!=nil{funcCall=p.FunctionCallfmt.Fprint(w,"The model suggests to call the function ")fmt.Fprintf(w,"%q with args: %v\n",funcCall.Name,funcCall.Args)//Exampleresponse://Themodelsuggeststocallthefunction"getCurrentWeather"withargs:map[location:Boston]}}iffuncCall==nil{returnfmt.Errorf("model did not suggest a function call")}//UsesyntheticdatatosimulatearesponsefromtheexternalAPI.//Inarealapplication,thiswouldcomefromanactualweatherAPI.funcResp:= &genai.FunctionResponse{Name:"getCurrentWeather",Response:map[string]any{"location":"Boston","temperature":"38","temperature_unit":"F","description":"Cold and cloudy","humidity":"65","wind":`{"speed":"10","direction":"NW"}`,},}//ReturnconversationturnsandAPIresponsetocompletethemodel's response.contents=[]*genai.Content{{Parts:[]*genai.Part{{Text:"What is the weather like in Boston?"},},Role:"user"},{Parts:[]*genai.Part{{FunctionCall:funcCall},}},{Parts:[]*genai.Part{{FunctionResponse:funcResp},}},}resp,err=client.Models.GenerateContent(ctx,modelName,contents,config)iferr!=nil{returnfmt.Errorf("failed to generate content: %w",err)}respText:=resp.Text()fmt.Fprintln(w,respText)//Exampleresponse://TheweatherinBostoniscoldandcloudywithatemperatureof38degreesFahrenheit.Thehumidityis...returnnil}
Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:
PROJECT_ID: .
MODEL_ID: o ID do modelo que está sendo processado.
Método HTTP e URL:
POST https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/endpoints/openapi/chat/completions
Corpo JSON da solicitação:
{ "model": "google/MODEL_ID", "messages": [ { "role": "user", "content": "What is the weather in Boston?" } ], "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "OBJECT", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616" } }, "required": ["location"] } } } ] }
Para enviar a solicitação, escolha uma destas opções:
curl
Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:
importvertexaiimportopenaifromgoogle.authimportdefault,transport# TODO(developer): Update & uncomment below line# PROJECT_ID = "your-project-id"location="us-central1"vertexai.init(project=PROJECT_ID,location=location)# Programmatically get an access tokencredentials,_=default(scopes=["https://www.googleapis.com/auth/cloud-platform"])auth_request=transport.requests.Request()credentials.refresh(auth_request)# # OpenAI Clientclient=openai.OpenAI(base_url=f"https://{location}-aiplatform.googleapis.com/v1beta1/projects/{PROJECT_ID}/locations/{location}/endpoints/openapi",api_key=credentials.token,)tools=[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA or a zip code e.g. 95616",},},"required":["location"],},},}]messages=[]messages.append({"role":"system","content":"Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",})messages.append({"role":"user","content":"What is the weather in Boston?"})response=client.chat.completions.create(model="google/gemini-2.0-flash-001",messages=messages,tools=tools,)print("Function:",response.choices[0].message.tool_calls[0].id)print("Arguments:",response.choices[0].message.tool_calls[0].function.arguments)# Example response:# Function: get_current_weather# Arguments: {"location":"Boston"}
Configurar o comportamento de chamada de função
O exemplo abaixo mostra como transmitir um FunctionCallingConfig ao modelo.
Use functionCallingConfig para exigir que o modelo gere uma chamada de função específica. Para configurar esse comportamento:
Defina a função que chama mode como ANY.
Especifique os nomes das funções que você quer usar em allowed_function_names. Se allowed_function_names estiver vazio, qualquer uma das funções fornecidas podem ser retornados.
REST
PROJECT_ID=myproject LOCATION=us-central1 MODEL_ID=gemini-2.5-flash curl-XPOST\-H"Authorization: Bearer $(gcloudauthprint-access-token)"\-H"Content-Type: application/json"\https://${LOCATION}-aiplatform.googleapis.com/v1beta1/projects/${PROJECT_ID}/locations/${LOCATION}/publishers/google/models/${MODEL_ID}:generateContent\-d'{ "contents": [{ "role": "user", "parts": [{ "text": "Do you have the White Pixel 8 Pro 128GB in stock in the US?" }] }], "tools": [{ "functionDeclarations": [ { "name": "get_product_sku", "description": "Get the available inventory for a Google products, e.g: Pixel phones, Pixel Watches, Google Home etc", "parameters": { "type": "object", "properties": { "product_name": {"type": "string", "description": "Product name"} } } }, { "name": "get_store_location", "description": "Get the location of the closest store", "parameters": { "type": "object", "properties": { "location": {"type": "string", "description": "Location"} }, } } ] }], "toolConfig": { "functionCallingConfig": { "mode":"ANY", "allowedFunctionNames": ["get_product_sku"] } }, "generationConfig": { "temperature": 0.95, "topP": 1.0, "maxOutputTokens": 8192 } }'
SDK da IA generativa para Python
fromgoogleimportgenaifromgoogle.genai.typesimport(FunctionDeclaration,GenerateContentConfig,HttpOptions,Tool,)client=genai.Client(http_options=HttpOptions(api_version="v1"))model_id="gemini-2.5-flash"get_album_sales=FunctionDeclaration(name="get_album_sales",description="Gets the number of albums sold",# Function parameters are specified in JSON schema formatparameters={"type":"OBJECT","properties":{"albums":{"type":"ARRAY","description":"List of albums","items":{"description":"Album and its sales","type":"OBJECT","properties":{"album_name":{"type":"STRING","description":"Name of the music album",},"copies_sold":{"type":"INTEGER","description":"Number of copies sold",},},},},},},)sales_tool=Tool(function_declarations=[get_album_sales],)response=client.models.generate_content(model=model_id,contents='At Stellar Sounds, a music label, 2024 was a rollercoaster. "Echoes of the Night," a debut synth-pop album, ''surprisingly sold 350,000 copies, while veteran rock band "Crimson Tide\'s" latest, "Reckless Hearts," ''lagged at 120,000. Their up-and-coming indie artist, "Luna Bloom\'s" EP, "Whispers of Dawn," ''secured 75,000 sales. The biggest disappointment was the highly-anticipated rap album "Street Symphony" '"only reaching 100,000 units. Overall, Stellar Sounds moved over 645,000 units this year, revealing unexpected ""trends in music consumption.",config=GenerateContentConfig(tools=[sales_tool],temperature=0,),)print(response.function_calls)# Example response:# [FunctionCall(# id=None,# name="get_album_sales",# args={# "albums": [# {"album_name": "Echoes of the Night", "copies_sold": 350000},# {"copies_sold": 120000, "album_name": "Reckless Hearts"},# {"copies_sold": 75000, "album_name": "Whispers of Dawn"},# {"copies_sold": 100000, "album_name": "Street Symphony"},# ]# },# )]
Node.js
const{VertexAI,FunctionDeclarationSchemaType,}=require('@google-cloud/vertexai');constfunctionDeclarations=[{function_declarations:[{name:'get_product_sku',description:'Get the available inventory for a Google products, e.g: Pixel phones, Pixel Watches, Google Home etc',parameters:{type:FunctionDeclarationSchemaType.OBJECT,properties:{productName:{type:FunctionDeclarationSchemaType.STRING},},},},{name:'get_store_location',description:'Get the location of the closest store',parameters:{type:FunctionDeclarationSchemaType.OBJECT,properties:{location:{type:FunctionDeclarationSchemaType.STRING},},},},],},];consttoolConfig={function_calling_config:{mode:'ANY',allowed_function_names:['get_product_sku'],},};constgenerationConfig={temperature:0.95,topP:1.0,maxOutputTokens:8192,};/** * TODO(developer): Update these variables before running the sample. */asyncfunctionfunctionCallingAdvanced(projectId='PROJECT_ID',location='us-central1',model='gemini-2.0-flash-001'){// Initialize Vertex with your Cloud project and locationconstvertexAI=newVertexAI({project:projectId,location:location});// Instantiate the modelconstgenerativeModel=vertexAI.preview.getGenerativeModel({model:model,});constrequest={contents:[{role:'user',parts:[{text:'Do you have the White Pixel 8 Pro 128GB in stock in the US?'},],},],tools:functionDeclarations,tool_config:toolConfig,generation_config:generationConfig,};constresult=awaitgenerativeModel.generateContent(request);console.log(JSON.stringify(result.response.candidates[0].content));}
Go
import("context""encoding/json""errors""fmt""io""cloud.google.com/go/vertexai/genai")// functionCallsChat opens a chat session and sends 4 messages to the model:// - convert a first text question into a structured function call request// - convert the first structured function call response into natural language// - convert a second text question into a structured function call request// - convert the second structured function call response into natural languagefuncfunctionCallsChat(wio.Writer,projectID,location,modelNamestring)error{// location := "us-central1"// modelName := "gemini-2.0-flash-001"ctx:=context.Background()client,err:=genai.NewClient(ctx,projectID,location)iferr!=nil{returnfmt.Errorf("unable to create client: %w",err)}deferclient.Close()model:=client.GenerativeModel(modelName)// Build an OpenAPI schema, in memoryparamsProduct:=&genai.Schema{Type:genai.TypeObject,Properties:map[string]*genai.Schema{"productName":{Type:genai.TypeString,Description:"Product name",},},}fundeclProductInfo:=&genai.FunctionDeclaration{Name:"getProductSku",Description:"Get the SKU for a product",Parameters:paramsProduct,}paramsStore:=&genai.Schema{Type:genai.TypeObject,Properties:map[string]*genai.Schema{"location":{Type:genai.TypeString,Description:"Location",},},}fundeclStoreLocation:=&genai.FunctionDeclaration{Name:"getStoreLocation",Description:"Get the location of the closest store",Parameters:paramsStore,}model.Tools=[]*genai.Tool{{FunctionDeclarations:[]*genai.FunctionDeclaration{fundeclProductInfo,fundeclStoreLocation,}},}model.SetTemperature(0.0)chat:=model.StartChat()// Send a prompt for the first conversation turn that should invoke the getProductSku functionprompt:="Do you have the Pixel 8 Pro in stock?"fmt.Fprintf(w,"Question: %s\n",prompt)resp,err:=chat.SendMessage(ctx,genai.Text(prompt))iferr!=nil{returnerr}iflen(resp.Candidates)==0||len(resp.Candidates[0].Content.Parts)==0{returnerrors.New("empty response from model")}// The model has returned a function call to the declared function `getProductSku`// with a value for the argument `productName`.jsondata,err:=json.MarshalIndent(resp.Candidates[0].Content.Parts[0],"\t"," ")iferr!=nil{returnfmt.Errorf("json.MarshalIndent: %w",err)}fmt.Fprintf(w,"function call generated by the model:\n\t%s\n",string(jsondata))// Create a function call response, to simulate the result of a call to a// real servicefunresp:=&genai.FunctionResponse{Name:"getProductSku",Response:map[string]any{"sku":"GA04834-US","in_stock":"yes",},}jsondata,err=json.MarshalIndent(funresp,"\t"," ")iferr!=nil{returnfmt.Errorf("json.MarshalIndent: %w",err)}fmt.Fprintf(w,"function call response sent to the model:\n\t%s\n\n",string(jsondata))// And provide the function call response to the modelresp,err=chat.SendMessage(ctx,funresp)iferr!=nil{returnerr}iflen(resp.Candidates)==0||len(resp.Candidates[0].Content.Parts)==0{returnerrors.New("empty response from model")}// The model has taken the function call response as input, and has// reformulated the response to the user.jsondata,err=json.MarshalIndent(resp.Candidates[0].Content.Parts[0],"\t"," ")iferr!=nil{returnfmt.Errorf("json.MarshalIndent: %w",err)}fmt.Fprintf(w,"Answer generated by the model:\n\t%s\n\n",string(jsondata))// Send a prompt for the second conversation turn that should invoke the getStoreLocation functionprompt2:="Is there a store in Mountain View, CA that I can visit to try it out?"fmt.Fprintf(w,"Question: %s\n",prompt)resp,err=chat.SendMessage(ctx,genai.Text(prompt2))iferr!=nil{returnerr}iflen(resp.Candidates)==0||len(resp.Candidates[0].Content.Parts)==0{returnerrors.New("empty response from model")}// The model has returned a function call to the declared function `getStoreLocation`// with a value for the argument `store`.jsondata,err=json.MarshalIndent(resp.Candidates[0].Content.Parts[0],"\t"," ")iferr!=nil{returnfmt.Errorf("json.MarshalIndent: %w",err)}fmt.Fprintf(w,"function call generated by the model:\n\t%s\n",string(jsondata))// Create a function call response, to simulate the result of a call to a// real servicefunresp=&genai.FunctionResponse{Name:"getStoreLocation",Response:map[string]any{"store":"2000 N Shoreline Blvd, Mountain View, CA 94043, US",},}jsondata,err=json.MarshalIndent(funresp,"\t"," ")iferr!=nil{returnfmt.Errorf("json.MarshalIndent: %w",err)}fmt.Fprintf(w,"function call response sent to the model:\n\t%s\n\n",string(jsondata))// And provide the function call response to the modelresp,err=chat.SendMessage(ctx,funresp)iferr!=nil{returnerr}iflen(resp.Candidates)==0||len(resp.Candidates[0].Content.Parts)==0{returnerrors.New("empty response from model")}// The model has taken the function call response as input, and has// reformulated the response to the user.jsondata,err=json.MarshalIndent(resp.Candidates[0].Content.Parts[0],"\t"," ")iferr!=nil{returnfmt.Errorf("json.MarshalIndent: %w",err)}fmt.Fprintf(w,"Answer generated by the model:\n\t%s\n\n",string(jsondata))returnnil}
Antes de usar os dados da solicitação abaixo, faça as substituições a seguir:
PROJECT_ID: .
MODEL_ID: o ID do modelo que está sendo processado.
Método HTTP e URL:
POST https://aiplatform.googleapis.com/v1beta1/projects/PROJECT_ID/locations/global/endpoints/openapi/chat/completions
Corpo JSON da solicitação:
{ "model": "google/MODEL_ID", "messages": [ { "role": "user", "content": "What is the weather in Boston?" } ], "tools": [ { "type": "function", "function": { "name": "get_current_weather", "description": "Get the current weather in a given location", "parameters": { "type": "OBJECT", "properties": { "location": { "type": "string", "description": "The city and state, e.g. San Francisco, CA or a zip code e.g. 95616" } }, "required": ["location"] } } } ], "tool_choice": "auto" }
Para enviar a solicitação, escolha uma destas opções:
curl
Salve o corpo da solicitação em um arquivo com o nome request.json e execute o comando a seguir:
importvertexaiimportopenaifromgoogle.authimportdefault,transport# TODO(developer): Update & uncomment below line# PROJECT_ID = "your-project-id"location="us-central1"vertexai.init(project=PROJECT_ID,location=location)# Programmatically get an access tokencredentials,_=default(scopes=["https://www.googleapis.com/auth/cloud-platform"])auth_request=transport.requests.Request()credentials.refresh(auth_request)# OpenAI Clientclient=openai.OpenAI(base_url=f"https://{location}-aiplatform.googleapis.com/v1beta1/projects/{PROJECT_ID}/locations/{location}/endpoints/openapi",api_key=credentials.token,)tools=[{"type":"function","function":{"name":"get_current_weather","description":"Get the current weather in a given location","parameters":{"type":"object","properties":{"location":{"type":"string","description":"The city and state, e.g. San Francisco, CA or a zip code e.g. 95616",},},"required":["location"],},},}]messages=[]messages.append({"role":"system","content":"Don't make assumptions about what values to plug into functions. Ask for clarification if a user request is ambiguous.",})messages.append({"role":"user","content":"What is the weather in Boston, MA?"})response=client.chat.completions.create(model="google/gemini-2.0-flash-001",messages=messages,tools=tools,tool_choice="auto",)print("Function:",response.choices[0].message.tool_calls[0].id)print("Arguments:",response.choices[0].message.tool_calls[0].function.arguments)# Example response:# Function: get_current_weather# Arguments: {"location":"Boston"}
A seguir
Para saber mais, consulte a seguinte documentação:
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2025-08-19 UTC."],[],[]]