Générez du contenu avec des appels de fonction.
Restez organisé à l'aide des collections
Enregistrez et classez les contenus selon vos préférences.
Générez du contenu avec des appels de fonction. Cet exemple illustre un scénario de modalité textuelle avec une fonction et une requête.
En savoir plus
Pour obtenir une documentation détaillée incluant cet exemple de code, consultez les articles suivants :
Exemple de code
Python
Avant d'essayer cet exemple, suivez les instructions de configuration pour Python décrites dans le guide de démarrage rapide de Vertex AI à l'aide des bibliothèques clientes.
Pour en savoir plus, consultez la documentation de référence de l'API Vertex AI Python.
Pour vous authentifier auprès de Vertex AI, configurez le service Identifiants par défaut de l'application.
Pour en savoir plus, consultez Configurer l'authentification pour un environnement de développement local.
import vertexai
from vertexai.generative_models import (
Content,
FunctionDeclaration,
GenerationConfig,
GenerativeModel,
Part,
Tool,
)
# Initialize Vertex AI
# TODO(developer): Update and un-comment below lines
# project_id = "PROJECT_ID"
vertexai.init(project=project_id, location="us-central1")
# Initialize Gemini model
model = GenerativeModel(model_name="gemini-1.0-pro-001")
# Define the user's prompt in a Content object that we can reuse in model calls
user_prompt_content = Content(
role="user",
parts=[
Part.from_text("What is the weather like in Boston?"),
],
)
# Specify a function declaration and parameters for an API request
function_name = "get_current_weather"
get_current_weather_func = FunctionDeclaration(
name=function_name,
description="Get the current weather in a given location",
# Function parameters are specified in OpenAPI JSON schema format
parameters={
"type": "object",
"properties": {"location": {"type": "string", "description": "Location"}},
},
)
# Define a tool that includes the above get_current_weather_func
weather_tool = Tool(
function_declarations=[get_current_weather_func],
)
# Send the prompt and instruct the model to generate content using the Tool that you just created
response = model.generate_content(
user_prompt_content,
generation_config=GenerationConfig(temperature=0),
tools=[weather_tool],
)
function_call = response.candidates[0].function_calls[0]
print(function_call)
# Check the function name that the model responded with, and make an API call to an external system
if function_call.name == function_name:
# Extract the arguments to use in your API call
location = function_call.args["location"] # noqa: F841
# Here you can use your preferred method to make an API request to fetch the current weather, for example:
# api_response = requests.post(weather_api_url, data={"location": location})
# In this example, we'll use synthetic data to simulate a response payload from an external API
api_response = """{ "location": "Boston, MA", "temperature": 38, "description": "Partly Cloudy",
"icon": "partly-cloudy", "humidity": 65, "wind": { "speed": 10, "direction": "NW" } }"""
# Return the API response to Gemini so it can generate a model response or request another function call
response = model.generate_content(
[
user_prompt_content, # User prompt
response.candidates[0].content, # Function call response
Content(
parts=[
Part.from_function_response(
name=function_name,
response={
"content": api_response, # Return the API response to Gemini
},
),
],
),
],
tools=[weather_tool],
)
# Get the model response
print(response.text)
Sauf indication contraire, le contenu de cette page est régi par une licence Creative Commons Attribution 4.0, et les échantillons de code sont régis par une licence Apache 2.0. Pour en savoir plus, consultez les Règles du site Google Developers. Java est une marque déposée d'Oracle et/ou de ses sociétés affiliées.
[{
"type": "thumb-down",
"id": "hardToUnderstand",
"label":"Hard to understand"
},{
"type": "thumb-down",
"id": "incorrectInformationOrSampleCode",
"label":"Incorrect information or sample code"
},{
"type": "thumb-down",
"id": "missingTheInformationSamplesINeed",
"label":"Missing the information/samples I need"
},{
"type": "thumb-down",
"id": "translationIssue",
"label":"Problème de traduction"
},{
"type": "thumb-down",
"id": "otherDown",
"label":"Autre"
}]
[{
"type": "thumb-up",
"id": "easyToUnderstand",
"label":"Facile à comprendre"
},{
"type": "thumb-up",
"id": "solvedMyProblem",
"label":"J'ai pu résoudre mon problème"
},{
"type": "thumb-up",
"id": "otherUp",
"label":"Autre"
}]