|
| 1 | +# Copyright 2023 Google LLC |
| 2 | +# |
| 3 | +# Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +# you may not use this file except in compliance with the License. |
| 5 | +# You may obtain a copy of the License at |
| 6 | +# |
| 7 | +# https://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +# |
| 9 | +# Unless required by applicable law or agreed to in writing, software |
| 10 | +# distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +# See the License for the specific language governing permissions and |
| 13 | +# limitations under the License. |
| 14 | + |
| 15 | +# [START aiplatform_function_calling] |
| 16 | +from vertexai.preview.generative_models import ( |
| 17 | + FunctionDeclaration, |
| 18 | + GenerativeModel, |
| 19 | + Tool, |
| 20 | +) |
| 21 | + |
| 22 | +# Load the Vertex AI Gemini API to use function calling |
| 23 | +model = GenerativeModel("gemini-pro") |
| 24 | + |
| 25 | +# Specify a function declaration and parameters for an API request |
| 26 | +get_current_weather_func = FunctionDeclaration( |
| 27 | + name="get_current_weather", |
| 28 | + description="Get the current weather in a given location", |
| 29 | + # Function parameters are specified in OpenAPI JSON schema format |
| 30 | + parameters={ |
| 31 | + "type": "object", |
| 32 | + "properties": {"location": {"type": "string", "description": "Location"}}, |
| 33 | + }, |
| 34 | +) |
| 35 | + |
| 36 | +# Define a tool that includes the above get_current_weather_func |
| 37 | +weather_tool = Tool( |
| 38 | + function_declarations=[get_current_weather_func], |
| 39 | +) |
| 40 | + |
| 41 | +# Prompt to ask the model about weather, which will invoke the Tool |
| 42 | +prompt = "What is the weather like in Boston?" |
| 43 | + |
| 44 | +# Instruct the model to generate content using the Tool that you just created: |
| 45 | +response = model.generate_content( |
| 46 | + prompt, |
| 47 | + generation_config={"temperature": 0}, |
| 48 | + tools=[weather_tool], |
| 49 | +) |
| 50 | + |
| 51 | +# Print the entire response |
| 52 | +print(response) |
| 53 | + |
| 54 | +# Print the part of the response that contains info about the function call |
| 55 | +print(response.candidates[0].content.parts[0].function_call) |
| 56 | +# [END aiplatform_function_calling] |
0 commit comments