### Install the SDK
Source: https://context7.com/google-gemini/deprecated-generative-ai-js/llms.txt
Use npm to install the package in your project.
```bash
npm install @google/generative-ai
```
--------------------------------
### Install Dependencies
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/contributing.md
Run this command to install project dependencies before making changes.
```bash
npm install
```
--------------------------------
### Installation
Source: https://context7.com/google-gemini/deprecated-generative-ai-js/llms.txt
Install the Google Generative AI JavaScript SDK using npm.
```APIDOC
## Installation
```bash
npm install @google/generative-ai
```
```
--------------------------------
### Example JSON Schema for parameters
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.functiondeclaration.parameters.md
Example configuration for a function with one required and one optional parameter.
```yaml
param1:
type: STRING
param2:
type: INTEGER
required:
- param1
```
--------------------------------
### StartChatParams.systemInstruction
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.startchatparams.systeminstruction.md
The systemInstruction property allows you to set a system-level instruction that guides the behavior of the AI model during a chat conversation. This can be a string or a Part object.
```APIDOC
## StartChatParams.systemInstruction
### Description
Optional. System instruction for the chat. This is a string or a Part object that provides high-level instructions, rules, or context to the model to guide its responses throughout the conversation.
### Method
Not Applicable (Property)
### Endpoint
Not Applicable (Property)
### Parameters
#### Request Body
- **systemInstruction** (string | Part | Content) - Optional - System instruction for the chat. This is a string or a Part object that provides high-level instructions, rules, or context to the model to guide its responses throughout the conversation.
### Request Example
```json
{
"systemInstruction": "You are a helpful assistant that translates English to French."
}
```
### Response
This is a property, not an endpoint, so there is no direct response. The value of systemInstruction is used internally by the SDK.
```
--------------------------------
### StartChatParams Interface
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.startchatparams.md
Defines the parameters for starting a chat session with a generative model.
```APIDOC
## StartChatParams Interface
### Description
Configuration parameters for initializing a chat session via GenerativeModel.startChat().
### Properties
- **cachedContent** (string) - Optional - The name of a CachedContent resource.
- **history** (Content[]) - Optional - An array of previous chat messages.
- **systemInstruction** (string | Part | Content) - Optional - Instructions to guide the model's behavior.
- **toolConfig** (ToolConfig) - Optional - Configuration for tools used in the chat.
- **tools** (Tool[]) - Optional - A list of tools available to the model.
```
--------------------------------
### GenerateContentRequest.systemInstruction
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.generatecontentrequest.systeminstruction.md
The systemInstruction property allows you to provide a system-level instruction to the model. This instruction guides the model's behavior and can be a string or a Part object.
```APIDOC
## GenerateContentRequest.systemInstruction
### Description
Provides a system-level instruction to the model to guide its behavior. This can be a string or a Part object.
### Method
Not Applicable (Property)
### Endpoint
Not Applicable (Property)
### Parameters
#### Request Body
- **systemInstruction** (string | Part | Content) - Optional - A system-level instruction for the model.
### Request Example
```json
{
"systemInstruction": "You are a helpful assistant."
}
```
### Response
This is a property of the request object, not a response.
```
--------------------------------
### Start Multi-turn Conversations
Source: https://context7.com/google-gemini/deprecated-generative-ai-js/llms.txt
Initialize a chat session with optional history and send messages to maintain context.
```javascript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
// Start chat with optional history
const chat = model.startChat({
history: [
{
role: "user",
parts: [{ text: "Hello" }],
},
{
role: "model",
parts: [{ text: "Great to meet you. What would you like to know?" }],
},
],
});
// Send messages and receive responses
let result = await chat.sendMessage("I have 2 dogs in my house.");
console.log(result.response.text());
// Output: "That's wonderful! Dogs make great companions..."
result = await chat.sendMessage("How many paws are in my house?");
console.log(result.response.text());
// Output: "With 2 dogs, you have 8 paws in your house!"
// Get full conversation history
const history = await chat.getHistory();
console.log(history);
```
--------------------------------
### GoogleGenerativeAI - Initialize SDK Client
Source: https://context7.com/google-gemini/deprecated-generative-ai-js/llms.txt
Initialize the SDK client and get a generative model instance. Supports additional configuration options for generation and system instructions.
```APIDOC
## GoogleGenerativeAI - Initialize SDK Client
The `GoogleGenerativeAI` class is the main entry point for the SDK, used to create model instances for content generation.
```javascript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
// Get a generative model instance
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
// With additional configuration options
const modelWithConfig = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
generationConfig: {
maxOutputTokens: 1000,
temperature: 0.7,
},
systemInstruction: "You are a helpful assistant.",
});
```
```
--------------------------------
### GroundingSupportSegment.startIndex property
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.groundingsupportsegment.startindex.md
Defines the starting byte index for a grounding support segment within a Part.
```APIDOC
## GroundingSupportSegment.startIndex property
### Description
Start index in the given Part, measured in bytes. Offset from the start of the Part, inclusive, starting at zero.
### Signature
startIndex?: number;
```
--------------------------------
### GET /files
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/generative-ai.googleaifilemanager.md
Lists all uploaded files. Any request options provided will override the initial request options.
```APIDOC
## GET /files
### Description
List all uploaded files.
### Method
GET
### Endpoint
`/files`
### Parameters
#### Query Parameters
- **listParams** (ListParams) - Optional - Parameters for filtering and pagination of the file list.
- **requestOptions** (SingleRequestOptions) - Optional - Options to override initial request settings.
### Response
#### Success Response (200)
- **files** (array) - An array of file metadata objects.
- **id** (string) - The unique identifier for the file.
- **filename** (string) - The name of the file.
- **size_bytes** (number) - The size of the file in bytes.
- **mime_type** (string) - The MIME type of the file.
- **creation_time** (string) - The timestamp when the file was created.
#### Error Response (500)
- **error** (string) - Message indicating an internal server error.
```
--------------------------------
### JavaScript Chat Interface Implementation
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/samples/web/chat.html
This snippet sets up an event listener for form submission to send user messages to a Generative AI model and display the conversation. It initializes the chat session if it hasn't been started and updates the UI with user and model messages.
```javascript
import { getGenerativeModel, scrollToDocumentBottom, updateUI, } from "./utils/shared.js";
const promptInput = document.querySelector("#prompt");
const historyElement = document.querySelector("#chat-history");
let chat;
document
.querySelector("#form")
.addEventListener("submit", async (event) => {
event.preventDefault();
if (!chat) {
const model = await getGenerativeModel({ model: "gemini-1.5-flash" });
chat = model.startChat({
generationConfig: {
maxOutputTokens: 100,
},
});
}
const userMessage = promptInput.value;
promptInput.value = "";
// Create UI for the new user / assistant messages pair
historyElement.innerHTML += `
`;
scrollToDocumentBottom();
const resultEls = document.querySelectorAll(
".model-role > blockquote",
);
await updateUI(
resultEls[resultEls.length - 1],
() => chat.sendMessageStream(userMessage),
true,
);
});
```
--------------------------------
### CitationSource.startIndex
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.citationsource.startindex.md
The startIndex property represents the starting index of a citation within a larger text. It is an optional number.
```APIDOC
## CitationSource.startIndex
### Description
The `startIndex` property is an optional number that indicates the starting index of a citation source. This is useful for referencing specific parts of a generated text.
### Property Type
`number`
### Optional
Yes
```
--------------------------------
### Build Project
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/contributing.md
Execute this command after making changes to build the project.
```bash
npm run build
```
--------------------------------
### GET GoogleAICacheManager.list
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/server/generative-ai.googleaicachemanager.list.md
Retrieves a list of all uploaded content caches.
```APIDOC
## GET GoogleAICacheManager.list()
### Description
List all uploaded content caches.
### Method
GET
### Parameters
#### Query Parameters
- **listParams** (ListParams) - Optional - Parameters for listing caches.
### Response
#### Success Response (200)
- **Promise** - A promise that resolves to the list of cached content.
```
--------------------------------
### GoogleGenerativeAI.getGenerativeModel()
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.googlegenerativeai.getgenerativemodel.md
Gets a GenerativeModel instance for the provided model name.
```APIDOC
## GoogleGenerativeAI.getGenerativeModel()
### Description
Gets a [GenerativeModel](./generative-ai.generativemodel.md) instance for the provided model name.
### Method
(Implicitly called via class instance)
### Endpoint
N/A (Method within a class)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```typescript
// Example usage within a class context
const model = genAI.getGenerativeModel({ model: "gemini-pro" });
```
### Response
#### Success Response (200)
- **GenerativeModel** - An instance of the GenerativeModel class.
#### Response Example
```json
{
"example": "GenerativeModel instance"
}
```
```
--------------------------------
### Format Code and Add License Headers
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/contributing.md
Run this command to automatically format code and add necessary license headers.
```bash
npm run format
```
--------------------------------
### ChatSession.getHistory()
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.chatsession.gethistory.md
Gets the chat history so far. Blocked prompts and candidates are not included in the history.
```APIDOC
## ChatSession.getHistory()
### Description
Gets the chat history so far. Blocked prompts are not added to history. Blocked candidates are not added to history, nor are the prompts that generated them.
### Method
GET
### Endpoint
N/A (This is a method call on an object instance)
### Parameters
None
### Request Example
```javascript
// Assuming 'chatSession' is an instance of ChatSession
const history = await chatSession.getHistory();
```
### Response
#### Success Response (200)
- **history** (Content[]) - An array of Content objects representing the chat history.
#### Response Example
```json
[
{
"role": "user",
"parts": [
{
"text": "Hello!"
}
]
},
{
"role": "model",
"parts": [
{
"text": "Hi there! How can I help you today?"
}
]
}
]
```
```
--------------------------------
### Initialize SDK Client
Source: https://context7.com/google-gemini/deprecated-generative-ai-js/llms.txt
Create a GoogleGenerativeAI instance and configure model parameters.
```javascript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
// Get a generative model instance
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
// With additional configuration options
const modelWithConfig = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
generationConfig: {
maxOutputTokens: 1000,
temperature: 0.7,
},
systemInstruction: "You are a helpful assistant.",
});
```
--------------------------------
### Run Unit Tests
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/contributing.md
Run this command to execute the project's unit tests.
```bash
npm run test
```
--------------------------------
### Package Overview
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/index.md
Provides the entry point for the @google/generative-ai package documentation.
```APIDOC
## Package: @google/generative-ai
### Description
This package contains the core functionality for interacting with Google's Generative AI services. Note that this project is currently deprecated.
```
--------------------------------
### Configure System Instructions
Source: https://context7.com/google-gemini/deprecated-generative-ai-js/llms.txt
Define model behavior by providing a system instruction during model initialization.
```javascript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
systemInstruction: "You are a cat. Your name is Neko.",
});
const result = await model.generateContent("Good morning! How are you?");
console.log(result.response.text());
// Output: "*stretches and yawns* Meow! Good morning, human! I'm doing wonderfully..."
```
--------------------------------
### Package Overview
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/index.md
Provides the entry point and package information for the Google Generative AI SDK.
```APIDOC
## Package: @google/generative-ai
### Description
This package contains the core functionality for interacting with Google's Generative AI models. Please note that this specific package version is deprecated.
### Reference
For more details, see the [official documentation](./generative-ai.md).
```
--------------------------------
### Generate Reference Documentation
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/contributing.md
Use this command to generate or update reference documentation. The output is placed in the docs/reference directory.
```bash
npm run docs
```
--------------------------------
### GET /files/{fileId}
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/generative-ai.googleaifilemanager.md
Retrieves metadata for a file using its ID. Optional request options can override initial settings.
```APIDOC
## GET /files/{fileId}
### Description
Get metadata for file with given ID.
### Method
GET
### Endpoint
`/files/{fileId}`
### Parameters
#### Path Parameters
- **fileId** (string) - Required - The ID of the file to retrieve.
#### Query Parameters
- **requestOptions** (SingleRequestOptions) - Optional - Options to override initial request settings.
### Response
#### Success Response (200)
- **fileMetadata** (object) - Metadata of the requested file.
- **id** (string) - The unique identifier for the file.
- **filename** (string) - The name of the file.
- **size_bytes** (number) - The size of the file in bytes.
- **mime_type** (string) - The MIME type of the file.
- **creation_time** (string) - The timestamp when the file was created.
#### Error Response (404)
- **error** (string) - Message indicating the file was not found.
```
--------------------------------
### Configure Request Options in JavaScript
Source: https://context7.com/google-gemini/deprecated-generative-ai-js/llms.txt
Demonstrates setting global request options during model initialization and overriding them for individual generateContent calls.
```javascript
import { GoogleGenerativeAI } from "@google/generative-ai";
// Global request options
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel(
{ model: "gemini-1.5-flash" },
{
timeout: 60000, // 60 second timeout
apiVersion: "v1beta", // Use beta API
baseUrl: "https://generativelanguage.googleapis.com",
customHeaders: { "X-Custom-Header": "value" },
}
);
// Per-request options override global settings
const result = await model.generateContent("Hello!", {
timeout: 30000, // Override timeout for this request
signal: new AbortController().signal,
});
console.log(result.response.text());
```
--------------------------------
### Initialize a ChatSession with startChat
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.generativemodel.startchat.md
Use this method to create a session for multi-turn chat interactions. It accepts an optional StartChatParams object to configure the session.
```typescript
startChat(startChatParams?: StartChatParams): ChatSession;
```
--------------------------------
### CachedContent.ttl Property
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.cachedcontent.ttl.md
The ttl property of the CachedContent class allows you to set the time-to-live for cached content. It accepts a string in the protobuf.Duration format, for example, '3.0001s'.
```APIDOC
## CachedContent.ttl
### Description
Specifies the time-to-live for cached content in protobuf.Duration format (ex. "3.0001s").
### Property Type
`string`
### Optional
Yes
### Example
```json
{
"ttl": "5m"
}
```
```
--------------------------------
### GenerativeModel.systemInstruction Property
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.generativemodel.systeminstruction.md
Defines the system instruction content for the GenerativeModel instance.
```APIDOC
## GenerativeModel.systemInstruction
### Description
The systemInstruction property allows you to set specific instructions that guide the behavior of the GenerativeModel. It accepts a Content object.
### Property Details
- **Name**: systemInstruction
- **Type**: Content
- **Requirement**: Optional
### Usage
```typescript
const model = genAI.getGenerativeModel({
model: "gemini-pro",
systemInstruction: {
role: "system",
parts: [{ text: "You are a helpful assistant." }]
}
});
```
```
--------------------------------
### GroundingSupportSegment.endIndex Property
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.groundingsupportsegment.endindex.md
The endIndex property indicates the end of a grounding support segment within a Part, measured in bytes. It is an exclusive offset from the beginning of the Part, starting at zero.
```APIDOC
## GroundingSupportSegment.endIndex Property
### Description
End index in the given Part, measured in bytes. Offset from the start of the Part, exclusive, starting at zero.
### Signature
```typescript
endIndex?: number;
```
### Type
`number`
```
--------------------------------
### RequestOptions.apiVersion
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/generative-ai.requestoptions.apiversion.md
The `apiVersion` property allows you to specify the version of the API endpoint to call. For example, you can use 'v1' or 'v1beta'. If this property is not provided, the SDK will default to using the latest stable version of the API.
```APIDOC
## RequestOptions.apiVersion property
Version of API endpoint to call (e.g. "v1" or "v1beta"). If not specified, defaults to latest stable version.
### Signature:
```typescript
apiVersion?: string;
```
```
--------------------------------
### Constructor: GoogleAIFileManager
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/server/generative-ai.googleaifilemanager._constructor_.md
Initializes a new instance of the GoogleAIFileManager class with the required API key and optional request configurations.
```APIDOC
## Constructor: GoogleAIFileManager
### Description
Constructs a new instance of the GoogleAIFileManager class to handle file operations.
### Parameters
#### Constructor Parameters
- **apiKey** (string) - Required - The API key used for authentication.
- **_requestOptions** (RequestOptions) - Optional - Configuration options for the request.
```
--------------------------------
### Send a Chat Message
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.chatsession.sendmessage.md
Use this method to send a message to the chat session and get a response. Optional request options can be provided to customize the request, which will take precedence over the model's default request options.
```typescript
sendMessage(request: string | Array, requestOptions?: SingleRequestOptions): Promise;
```
--------------------------------
### GoogleAIFileManager.listFiles()
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/generative-ai.googleaifilemanager.listfiles.md
Lists all uploaded files. Optional parameters can override initialization settings.
```APIDOC
## GoogleAIFileManager.listFiles()
### Description
List all uploaded files.
Any fields set in the optional [SingleRequestOptions](./generative-ai.singlerequestoptions.md) parameter will take precedence over the [RequestOptions](./generative-ai.requestoptions.md) values provided at the time of the [GoogleAIFileManager](./generative-ai.googleaifilemanager.md) initialization.
### Method
POST
### Endpoint
/v1beta/files: list
### Parameters
#### Query Parameters
- **pageSize** (number) - Optional - The maximum number of files to return.
- **pageToken** (string) - Optional - A page token, received from a previous ListFilesResponse, to return the next page of results.
#### Request Body
This method does not accept a request body.
### Response
#### Success Response (200)
- **files** (array) - A list of files.
- **nextPageToken** (string) - A token to retrieve the next page of results.
#### Response Example
```json
{
"files": [
{
"name": "file-1",
"displayName": "My Document",
"uri": "https://example.com/file-1.pdf",
"createTime": "2023-10-27T10:00:00Z",
"updateTime": "2023-10-27T10:00:00Z",
"mimeType": "application/pdf",
"sizeBytes": 102400
}
],
"nextPageToken": "page-token-123"
}
```
```
--------------------------------
### GenerativeModel.startChat()
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.generativemodel.startchat.md
Initiates a new chat session for multi-turn conversations.
```APIDOC
## GenerativeModel.startChat()
### Description
Gets a new [ChatSession](./generative-ai.chatsession.md) instance which can be used for multi-turn chats.
### Method
N/A (This is a method of a class)
### Endpoint
N/A (This is a method of a class)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
```json
{
"startChatParams": {
"example": "optional parameters for starting a chat"
}
}
```
### Response
#### Success Response (200)
- **ChatSession** (object) - An instance of ChatSession for managing the conversation.
#### Response Example
```json
{
"example": "ChatSession object"
}
```
```
--------------------------------
### List Files Interfaces
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/generative-ai.md
Interfaces for listing files and their parameters.
```APIDOC
## ListFilesResponse
### Description
Response from calling `GoogleAIFileManager.listFiles()`.
### Fields
- **files** (Array) - An array of file metadata objects.
- **nextPageToken** (string) - A token to retrieve the next page of results, if available.
## ListParams
### Description
Params to pass to `GoogleAIFileManager.listFiles()`.
### Fields
- **pageSize** (number) - Optional - The maximum number of files to return in the response.
- **pageToken** (string) - Optional - A page token, received from a previous `listFiles` call.
```
--------------------------------
### Generate Changeset Summary
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/contributing.md
This command is used to generate a summary for changesets, which is part of the release process.
```bash
npx @changesets/cli
```
--------------------------------
### CachedContentBase.systemInstruction Property
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.cachedcontentbase.systeminstruction.md
Defines the system instruction for the cached content, which can be provided as a string, a Part object, or a Content object.
```APIDOC
## Property: systemInstruction
### Description
Specifies the system instructions to be associated with the cached content. This helps guide the model's behavior when interacting with the cached data.
### Signature
`systemInstruction?: string | Part | Content;`
### Parameters
- **systemInstruction** (string | Part | Content) - Optional - The instruction content, which can be a simple string, a structured Part, or a full Content object.
```
--------------------------------
### ModelParams.systemInstruction Property
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.modelparams.systeminstruction.md
Defines the system instruction property used to configure model behavior.
```APIDOC
## ModelParams.systemInstruction
### Description
The systemInstruction property allows you to provide specific instructions or context to the generative model to guide its behavior.
### Signature
`systemInstruction?: string | Part | Content;`
```
--------------------------------
### GoogleAICacheManager Class Overview
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/server/generative-ai.googleaicachemanager.md
Provides an overview of the GoogleAICacheManager class and its constructor.
```APIDOC
## GoogleAICacheManager Class
Class for managing GoogleAI content caches.
**Signature:**
```typescript
export declare class GoogleAICacheManager
```
### Constructors
| Constructor | Modifiers | Description |
|---|---|---|
| [(constructor)(apiKey, _requestOptions)](./generative-ai.googleaicachemanager._constructor_.md) | | Constructs a new instance of the `GoogleAICacheManager` class |
```
--------------------------------
### GoogleGenerativeAI Constructor
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.googlegenerativeai._constructor_.md
Initializes a new instance of the GoogleGenerativeAI class using a provided API key.
```APIDOC
## Constructor GoogleGenerativeAI
### Description
Constructs a new instance of the GoogleGenerativeAI class to interact with the generative AI services.
### Parameters
#### Path Parameters
- **apiKey** (string) - Required - The API key used for authentication with the Google Generative AI service.
### Request Example
const genAI = new GoogleGenerativeAI("YOUR_API_KEY");
```
--------------------------------
### GoogleAIFileManager.uploadFile()
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/server/generative-ai.googleaifilemanager.uploadfile.md
Uploads a file to the Google AI service.
```APIDOC
## GoogleAIFileManager.uploadFile()
### Description
Uploads a file to the Google AI service.
### Method
POST (Internal SDK Method)
### Parameters
#### Path Parameters
- **fileData** (string | Buffer) - Required - The file content to be uploaded.
- **fileMetadata** (FileMetadata) - Required - Metadata associated with the file.
### Response
#### Success Response
- **Promise** - A promise that resolves to the upload response.
```
--------------------------------
### Model Parameters and Configuration
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/common/api-review/generative-ai.api.md
Defines interfaces for model parameters, including system instructions, tools, and cached content.
```APIDOC
## Model Parameters Interface
### ModelParams
Represents parameters for configuring a generative model.
- **model** (string) - The name of the model to use.
- **systemInstruction** (string | Part | Content) - Optional system instruction to guide the model's behavior.
- **cachedContent** (CachedContent) - Optional cached content to influence generation.
- **tools** (Tool[]) - Optional list of tools the model can use.
- **toolConfig** (ToolConfig) - Optional configuration for the tools.
```
--------------------------------
### StartChatParams.tools Property
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.startchatparams.tools.md
Defines the tools property used to configure available tools for a chat session.
```APIDOC
## StartChatParams.tools property
### Description
The tools property allows you to specify an array of Tool objects that the model can utilize during the chat session.
### Signature
`tools?: Tool[];`
```
--------------------------------
### StartChatParams.toolConfig
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.startchatparams.toolconfig.md
The toolConfig property allows you to specify configuration details for tools that can be used by the generative model during a chat session. This is an optional parameter.
```APIDOC
## StartChatParams.toolConfig property
### Description
An optional configuration for tools used in chat interactions.
### Signature
```typescript
toolConfig?: ToolConfig;
```
### Type
`ToolConfig`
```
--------------------------------
### Handle File Input and Display Thumbnails
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/samples/web/index.html
This event listener handles user file selections, creates object URLs for each file, and displays them as thumbnails. It also includes a cleanup mechanism using 'window.URL.revokeObjectURL' to free up memory after the image is loaded.
```javascript
const fileInputEl = document.querySelector("input[type=file]");
const thumbnailsEl = document.querySelector("#thumbnails");
fileInputEl.addEventListener("input", () => {
thumbnailsEl.innerHTML = "";
for (const file of fileInputEl.files) {
const url = URL.createObjectURL(file);
thumbnailsEl.innerHTML += `
`;
}
});
```
--------------------------------
### GoogleAIFileManager Methods
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/common/api-review/generative-ai-server.api.md
Methods for managing files, including uploading, retrieving metadata, listing, and deleting files.
```APIDOC
## POST /uploadFile
### Description
Uploads a file to the Google AI service.
### Method
POST
### Parameters
#### Request Body
- **fileData** (string | Buffer) - Required - The file content to upload.
- **fileMetadata** (FileMetadata) - Required - Metadata associated with the file.
### Response
#### Success Response (200)
- **UploadFileResponse** (object) - The response containing file upload details.
---
## GET /getFile
### Description
Retrieves the metadata for a specific file by its ID.
### Method
GET
### Parameters
#### Path Parameters
- **fileId** (string) - Required - The unique identifier of the file.
### Response
#### Success Response (200)
- **FileMetadataResponse** (object) - The metadata object for the requested file.
---
## GET /listFiles
### Description
Lists all files associated with the account.
### Method
GET
### Parameters
#### Query Parameters
- **listParams** (ListParams) - Optional - Parameters for pagination and filtering.
### Response
#### Success Response (200)
- **ListFilesResponse** (object) - A list of file metadata objects.
---
## DELETE /deleteFile
### Description
Deletes a file by its ID.
### Method
DELETE
### Parameters
#### Path Parameters
- **fileId** (string) - Required - The unique identifier of the file to delete.
```
--------------------------------
### ListParams Interface
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/generative-ai.listparams.md
Defines the optional parameters for paginating file listing requests.
```APIDOC
## ListParams Interface
### Description
Parameters used to configure the listFiles request for GoogleAIFileManager.
### Parameters
#### Properties
- **pageSize** (number) - Optional - The maximum number of files to return in the response.
- **pageToken** (string) - Optional - A unique identifier used to retrieve the next page of results.
```
--------------------------------
### List All Uploaded Files
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/generative-ai.googleaifilemanager.listfiles.md
Call this method to retrieve a list of all files uploaded to your account. Optional parameters can be used to specify request options.
```typescript
listFiles(listParams?: ListParams, requestOptions?: SingleRequestOptions): Promise;
```
--------------------------------
### GoogleAICacheManager.create()
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/server/generative-ai.googleaicachemanager.create.md
Uploads a new content cache using the provided creation options.
```APIDOC
## GoogleAICacheManager.create()
### Description
Upload a new content cache.
### Parameters
#### Request Body
- **createOptions** (CachedContentCreateParams) - Required - Configuration options for creating the cached content.
### Response
- **Returns** (Promise) - A promise that resolves to the created CachedContent object.
```
--------------------------------
### Enable Code Execution
Source: https://context7.com/google-gemini/deprecated-generative-ai-js/llms.txt
Allow the model to generate and run Python code for complex tasks.
```javascript
import { GoogleGenerativeAI } from "@google/generative-ai";
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
const model = genAI.getGenerativeModel({
model: "gemini-1.5-flash",
tools: [{ codeExecution: {} }],
});
const result = await model.generateContent(
"What is the sum of the first 50 prime numbers? " +
"Generate and run code for the calculation, and make sure you get all 50."
);
console.log(result.response.text());
// Output includes generated Python code and execution results
// Code execution in chat
const chat = model.startChat();
const chatResult = await chat.sendMessage(
"Calculate the factorial of 20 using code."
);
console.log(chatResult.response.text());
```
--------------------------------
### RequestOptions
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/common/api-review/generative-ai-server.api.md
Options for configuring API requests, including API client, version, base URL, custom headers, and timeout.
```APIDOC
## RequestOptions
### Description
Options for configuring API requests, including API client, version, base URL, custom headers, and timeout.
### Fields
- **apiClient** (string) - Optional - Identifier for the API client.
- **apiVersion** (string) - Optional - The version of the API to use.
- **baseUrl** (string) - Optional - The base URL for the API requests.
- **customHeaders** (Headers | Record) - Optional - Custom headers to include in the request.
- **timeout** (number) - Optional - The request timeout in milliseconds.
```
--------------------------------
### GoogleAIFileManager.uploadFile
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/generative-ai.googleaifilemanager.uploadfile.md
Upload a file using the GoogleAIFileManager.uploadFile method. Optional request options can override initial settings.
```APIDOC
## POST /uploadFile
### Description
Upload a file.
Any fields set in the optional [SingleRequestOptions](./generative-ai.singlerequestoptions.md) parameter will take precedence over the [RequestOptions](./generative-ai.requestoptions.md) values provided at the time of the [GoogleAIFileManager](./generative-ai.googleaifilemanager.md) initialization.
### Method
POST
### Endpoint
/uploadFile
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **filePath** (string) - Required - The path to the file to upload.
- **fileMetadata** ([FileMetadata](./generative-ai.filemetadata.md)) - Required - Metadata for the file.
- **requestOptions** ([SingleRequestOptions](./generative-ai.singlerequestoptions.md)) - Optional - Request options for the upload.
### Request Example
```json
{
"filePath": "path/to/your/file.txt",
"fileMetadata": {
"mimeType": "text/plain",
"displayName": "My Text File"
},
"requestOptions": {
"timeout": 60000
}
}
```
### Response
#### Success Response (200)
- **UploadFileResponse** ([UploadFileResponse](./generative-ai.uploadfileresponse.md)) - The response from uploading the file.
#### Response Example
```json
{
"file": {
"name": "files/your-file-id",
"displayName": "My Text File",
"mimeType": "text/plain",
"createTime": "2023-10-27T10:00:00Z",
"updateTime": "2023-10-27T10:05:00Z",
"sizeBytes": 1024
}
}
```
```
--------------------------------
### GoogleAIFileManager Constructor
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/generative-ai.googleaifilemanager._constructor_.md
Constructs a new instance of the GoogleAIFileManager class.
```APIDOC
## GoogleAIFileManager.(constructor)
### Description
Constructs a new instance of the `GoogleAIFileManager` class
### Method
constructor
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
None
### Request Example
None
### Response
#### Success Response (200)
None
#### Response Example
None
### Parameters
- **apiKey** (string) - Required - The API key for authentication.
- **_requestOptions** (RequestOptions) - Optional - Additional request options.
```
--------------------------------
### GroundingChunkWeb.uri Property
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.groundingchunkweb.uri.md
Documentation for the uri property of the GroundingChunkWeb interface.
```APIDOC
## GroundingChunkWeb.uri property
### Description
URI reference of the chunk.
### Signature
`uri?: string;`
```
--------------------------------
### File and Request Interfaces
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/common/api-review/generative-ai-server.api.md
Interfaces for listing files, uploading files, and configuring API request options.
```typescript
export interface ListFilesResponse {
// (undocumented)
files: FileMetadataResponse[];
// (undocumented)
nextPageToken?: string;
}
```
```typescript
export interface ListParams {
// (undocumented)
pageSize?: number;
// (undocumented)
pageToken?: string;
}
```
```typescript
export interface RequestOptions {
apiClient?: string;
apiVersion?: string;
baseUrl?: string;
customHeaders?: Headers | Record;
timeout?: number;
}
```
```typescript
export interface SingleRequestOptions extends RequestOptions {
signal?: AbortSignal;
}
```
```typescript
export interface UploadFileResponse {
// (undocumented)
file: FileMetadataResponse;
}
```
--------------------------------
### SimpleStringSchema Interface
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.simplestringschema.md
Details the properties and structure of the SimpleStringSchema interface.
```APIDOC
## SimpleStringSchema Interface
### Description
Describes a simple string schema, with or without format. Extends BaseSchema.
### Properties
- **enum** (never) - Optional.
- **format** ("date-time" | undefined) - Optional.
- **type** (typeof SchemaType.STRING) - Required.
```
--------------------------------
### ListFilesResponse
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/common/api-review/generative-ai-server.api.md
Represents the response structure for listing files. It includes a list of file metadata and an optional token for pagination.
```APIDOC
## ListFilesResponse
### Description
Represents the response structure for listing files. It includes a list of file metadata and an optional token for pagination.
### Fields
- **files** (FileMetadataResponse[]) - Required - A list of file metadata.
- **nextPageToken** (string) - Optional - A token to retrieve the next page of results.
```
--------------------------------
### Generative AI SDK Classes
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.md
Overview of the main classes available in the @google/generative-ai SDK.
```APIDOC
## Classes
| Class |
| --- |
| [ChatSession](./generative-ai.chatsession.md) |
| [GenerativeModel](./generative-ai.generativemodel.md) |
| [GoogleGenerativeAI](./generative-ai.googlegenerativeai.md) |
| [GoogleGenerativeAIAbortError](./generative-ai.googlegenerativeaiaborterror.md) |
| [GoogleGenerativeAIError](./generative-ai.googlegenerativeaierror.md) |
| [GoogleGenerativeAIFetchError](./generative-ai.googlegenerativeaifetcherror.md) |
| [GoogleGenerativeAIRequestInputError](./generative-ai.googlegenerativeairequestinputerror.md) |
| [GoogleGenerativeAIResponseError](./generative-ai.googlegenerativeairesponseerror.md) |
### Description
These classes provide the core functionality for interacting with Google's generative AI models, managing chat sessions, handling errors, and more.
```
--------------------------------
### ListFilesResponse Interface
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/generative-ai.listfilesresponse.md
Details the structure of the response object returned when listing files via the GoogleAIFileManager.
```APIDOC
## ListFilesResponse Interface
### Description
Represents the response object returned by the `GoogleAIFileManager.listFiles()` method.
### Properties
- **files** (FileMetadataResponse[]) - An array of file metadata objects.
- **nextPageToken** (string) - Optional. A token that can be used to retrieve the next page of results.
```
--------------------------------
### GroundingMetadata.searchEntryPoint
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.groundingmetadata.searchentrypoint.md
Provides access to Google search entry points for follow-up web searches.
```APIDOC
## GroundingMetadata.searchEntryPoint
### Description
Google search entry for the following-up web searches.
### Signature
```typescript
searchEntryPoint?: SearchEntryPoint;
```
```
--------------------------------
### Upload and Manage Files with GoogleAIFileManager
Source: https://context7.com/google-gemini/deprecated-generative-ai-js/llms.txt
Use GoogleAIFileManager to upload files, monitor their processing state, and use them with generative models. Ensure files are processed before use and handle potential processing failures.
```javascript
import { GoogleAIFileManager, FileState } from "@google/generative-ai/server";
import { GoogleGenerativeAI } from "@google/generative-ai";
const fileManager = new GoogleAIFileManager(process.env.API_KEY);
const genAI = new GoogleGenerativeAI(process.env.API_KEY);
// Upload a file
const uploadResult = await fileManager.uploadFile("./video.mp4", {
mimeType: "video/mp4",
displayName: "My Video",
});
console.log(`Uploaded file ${uploadResult.file.displayName} as: ${uploadResult.file.uri}`);
// Wait for processing to complete
let file = await fileManager.getFile(uploadResult.file.name);
while (file.state === FileState.PROCESSING) {
await new Promise((resolve) => setTimeout(resolve, 10_000));
file = await fileManager.getFile(uploadResult.file.name);
}
if (file.state === FileState.FAILED) {
throw new Error("File processing failed.");
}
// Use the file with the model
const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" });
const result = await model.generateContent([
"Describe this video.",
{
fileData: {
fileUri: uploadResult.file.uri,
mimeType: uploadResult.file.mimeType,
},
},
]);
console.log(result.response.text());
// List all files
const listResult = await fileManager.listFiles();
for (const file of listResult.files) {
console.log(`name: ${file.name} | display name: ${file.displayName}`);
}
// Delete a file
await fileManager.deleteFile(uploadResult.file.name);
```
--------------------------------
### POST /files
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/generative-ai.googleaifilemanager.md
Uploads a file. Any request options provided will override the initial request options.
```APIDOC
## POST /files
### Description
Upload a file.
### Method
POST
### Endpoint
`/files`
### Parameters
#### Request Body
- **filePath** (string) - Required - The local path to the file to upload.
- **fileMetadata** (FileMetadata) - Optional - Metadata for the file, such as display name or purpose.
#### Query Parameters
- **requestOptions** (SingleRequestOptions) - Optional - Options to override initial request settings.
### Response
#### Success Response (200)
- **file** (object) - Metadata of the uploaded file.
- **id** (string) - The unique identifier for the file.
- **filename** (string) - The name of the file.
- **size_bytes** (number) - The size of the file in bytes.
- **mime_type** (string) - The MIME type of the file.
- **creation_time** (string) - The timestamp when the file was created.
#### Error Response (400)
- **error** (string) - Message indicating an invalid request, such as incorrect file format or size.
```
--------------------------------
### Response and Logging Structures
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/common/api-review/generative-ai.api.md
Defines interfaces for log probabilities and prompt feedback.
```APIDOC
## Response and Logging Interfaces
### LogprobsCandidate
Represents a candidate token with its log probability.
- **token** (string) - The token text.
- **logProbability** (number) - The log probability of the token.
- **tokenID** (number) - The ID of the token.
### LogprobsResult
Contains log probabilities for generated candidates.
- **chosenCandidates** (LogprobsCandidate[]) - List of chosen candidates.
- **topCandidates** (TopCandidates[]) - List of top candidates.
### PromptFeedback
Provides feedback on a prompt, including reasons for blocking and safety ratings.
- **blockReason** (BlockReason) - The reason why the prompt was blocked.
- **blockReasonMessage** (string) - An optional message explaining the block reason.
- **safetyRatings** (SafetyRating[]) - A list of safety ratings for the prompt.
```
--------------------------------
### CachedContentBase.toolConfig Property
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.cachedcontentbase.toolconfig.md
Defines the tool configuration associated with the cached content instance.
```APIDOC
## Property: toolConfig
### Description
Represents the tool configuration settings applied to the cached content. This property is optional.
### Type
ToolConfig
### Signature
`toolConfig?: ToolConfig;`
```
--------------------------------
### Request Options Interfaces
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/files/generative-ai.md
Interfaces for configuring request options.
```APIDOC
## RequestOptions
### Description
Params passed to `getGenerativeModel()` or `GoogleAIFileManager()`.
### Fields
- **apiKey** (string) - Your Google API key.
- **baseUrl** (string) - Optional - The base URL for the API requests.
## SingleRequestOptions
### Description
Params passed to atomic asynchronous operations.
### Fields
- **timeout** (number) - Optional - The timeout for the request in milliseconds.
```
--------------------------------
### Initialize GenerativeModel instance
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.generativemodel._constructor_.md
Use this constructor to create a new GenerativeModel instance with the required API key and model parameters.
```typescript
constructor(apiKey: string, modelParams: ModelParams, _requestOptions?: RequestOptions);
```
--------------------------------
### Run Generative Model with Image Input
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/samples/web/index.html
This function processes image files and sends them along with a text prompt to the Generative AI model. Ensure 'getGenerativeModel' and 'fileToGenerativePart' are correctly imported from './utils/shared.js'.
```javascript
import { getGenerativeModel, fileToGenerativePart, updateUI, } from "./utils/shared.js"; async function run(prompt, files) {
const imageParts = await Promise.all(
[...files].map(fileToGenerativePart),
);
const model = await getGenerativeModel({ model: "gemini-1.5-flash", });
return model.generateContentStream([...imageParts, prompt]);
}
```
--------------------------------
### StartChatParams.history Property
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.startchatparams.history.md
The `history` property allows you to pass previous conversation turns to the `startChat` method. This is useful for continuing an existing conversation.
```APIDOC
## StartChatParams.history Property
### Description
Optional. An array of `Content` objects representing the conversation history. This allows the model to maintain context from previous turns.
### Method
Not applicable (property of an object)
### Endpoint
Not applicable (property of an object)
### Parameters
#### Path Parameters
None
#### Query Parameters
None
#### Request Body
- **history** (Content[]) - Optional - An array of `Content` objects representing the conversation history.
### Request Example
```json
{
"history": [
{
"role": "user",
"parts": [{"text": "Hello!"}]
},
{
"role": "model",
"parts": [{"text": "Hi there! How can I help you today?"}]
}
]
}
```
### Response
This property is part of the request body for starting a chat. Success responses are related to the chat completion itself.
#### Success Response (200)
Not directly applicable to this property. See chat completion response documentation.
#### Response Example
Not directly applicable to this property. See chat completion response documentation.
```
--------------------------------
### GenerativeModel Constructor
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.generativemodel._constructor_.md
Initializes a new instance of the GenerativeModel class using an API key and model configuration parameters.
```APIDOC
## Constructor GenerativeModel
### Description
Constructs a new instance of the GenerativeModel class.
### Parameters
#### Path Parameters
- **apiKey** (string) - Required - The API key for authentication.
- **modelParams** (ModelParams) - Required - Configuration parameters for the model.
- **_requestOptions** (RequestOptions) - Optional - Additional request configuration options.
```
--------------------------------
### RequestOptions Interface
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.requestoptions.md
Defines the structure for options that can be passed to `getGenerativeModel()` or `GoogleAIFileManager()`.
```APIDOC
## RequestOptions Interface
### Description
Params passed to getGenerativeModel() or GoogleAIFileManager().
### Properties
- **apiClient** (string) - Optional - Additional attribution information to include in the x-goog-api-client header. Used by wrapper SDKs.
- **apiVersion** (string) - Optional - Version of API endpoint to call (e.g. "v1" or "v1beta"). If not specified, defaults to latest stable version.
- **baseUrl** (string) - Optional - Base endpoint url. Defaults to "https://generativelanguage.googleapis.com"
- **customHeaders** (Headers | Record) - Optional - Custom HTTP request headers.
- **timeout** (number) - Optional - Request timeout in milliseconds.
```
--------------------------------
### ChatSession.params Property
Source: https://github.com/google-gemini/deprecated-generative-ai-js/blob/main/docs/reference/main/generative-ai.chatsession.params.md
Accesses the configuration parameters used to initialize a chat session.
```APIDOC
## ChatSession.params
### Description
Retrieves or sets the initialization parameters for the chat session.
### Property
params?: StartChatParams
### Type
StartChatParams
```