-
Notifications
You must be signed in to change notification settings - Fork 56
Expand file tree
/
Copy pathfunction_call_with_gemini_api.js
More file actions
85 lines (74 loc) · 2.5 KB
/
Copy pathfunction_call_with_gemini_api.js
File metadata and controls
85 lines (74 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
//This example defines a simple function to get the current weather and uses the Gemini API to interpret a user query, call the function, and return a response.
const { GoogleGenerativeAI } = require("@google/generative-ai");
// Initialize the Gemini API client with your API key
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
// Define a sample function to simulate getting the weather
function getWeather(location) {
// Simulated weather data (in a real app, this could call an external API)
const weatherData = {
"New York": { temp: 65, condition: "Sunny" },
"London": { temp: 50, condition: "Rainy" },
};
return weatherData[location] || { temp: "unknown", condition: "unknown" };
}
// Define the function schema for the Gemini API
const tools = [
{
functionDeclarations: [
{
name: "getWeather",
description: "Get the current weather for a specified location",
parameters: {
type: "object",
properties: {
location: {
type: "string",
description: "The city or location to get the weather for",
},
},
required: ["location"],
},
},
],
},
];
// Test case for function calling
async function testFunctionCalling() {
// [START function_calling_weather]
const model = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
tools: tools,
});
const prompt = "What's the weather like in New York today?";
// Generate content with function calling enabled
const result = await model.generateContent(prompt);
const response = result.response;
// Check if the model wants to call a function
const functionCall = response.functionCalls && response.functionCalls()[0];
if (functionCall && functionCall.name === "getWeather") {
const { location } = functionCall.args;
const weather = getWeather(location);
// Send the function result back to the model for a final response
const finalResult = await model.generateContent([
prompt,
{
functionCall: {
name: "getWeather",
args: { location },
},
},
{
functionResponse: {
name: "getWeather",
response: weather,
},
},
]);
console.log(finalResult.response.text());
} else {
console.log(response.text());
}
// [END function_calling_weather]
}
// Run the test
testFunctionCalling().catch(console.error);