Google AI JavaScript SDK (Deprecated)

repository·main·Indexed 22 days ago

https://github.com/google-gemini/deprecated-generative-ai-js

Legacy version of the Google AI JavaScript SDK for the Gemini API. This SDK provides interfaces for content generation, multi-turn chat sessions, embeddings, and token counting. It includes support for tools such as function calling, code execution, and Google Search retrieval, as well as file management via GoogleAIFileManager and context caching via GoogleAICacheManager. This repository is in limited maintenance and will reach end-of-life on November 30, 2025; users are encouraged to migrate to the unified Google Gen AI SDK.

Tokens
76.1K
Snippets
357
Records
661
Agent score
75%

What's inside @google/generative-ai

  1. Understand the GenerateContentResponse interface

    main
    The GenerateContentResponse interface represents the individual response received from calling GenerativeModel.generateContent() or GenerativeModel.generateContentStream(). When using generateContentStream(), the API returns one GenerateContentResponse object for each chunk in the stream until the stream is complete.
  2. Manage multi-turn conversations with ChatSession

    main

    The ChatSession class enables multi-turn conversations by sending chat messages and automatically storing the history of sent and received messages. This allows the model to maintain context across multiple interactions.

    Key behaviors:

    • History Management: The session tracks the conversation flow. However, blocked prompts and blocked candidates (and the prompts that generated them) are not added to the history.
    • Message Sending: You can send messages using either a non-streaming method (sendMessage) or a streaming method (sendMessageStream).
    • Configuration Precedence: When sending a message, any fields provided in the optional SingleRequestOptions will take precedence over the RequestOptions originally provided to GoogleGenerativeAI.getGenerativeModel().
  3. Define structured output with Schema

    main

    You can enforce structured responses by providing a ResponseSchema. The Schema type is a union of several specific schema interfaces:

    • StringSchema: Includes SimpleStringSchema and EnumStringSchema (for fixed sets of strings).
    • NumberSchema: For floating-point numbers.
    • IntegerSchema: For integers (supports int32 or int64 formats).
    • BooleanSchema: For boolean values.
    • ArraySchema: For lists of items, with optional minItems and maxItems constraints.
    • ObjectSchema: For complex objects with defined properties and required fields.

    Use the SchemaType enum to specify the type (e.g., SchemaType.OBJECT, SchemaType.STRING).

  4. Define tools for the Gemini model

    main

    A Tool allows the Gemini model to access external knowledge or capabilities by defining specific interfaces it can invoke. The Tool type is a union that supports three distinct types of tools:

    1. Function Declarations: Allows the model to call your own custom functions (via FunctionDeclarationsTool).
    2. Code Execution: Allows the model to run code in a sandboxed environment (via CodeExecutionTool).
    3. Google Search Retrieval: Allows the model to use Google Search to retrieve up-to-date information (via GoogleSearchRetrievalTool).

    You provide these tools as part of the model configuration to enable the model to perform tasks beyond simple text generation.

    export declare type Tool = FunctionDeclarationsTool | CodeExecutionTool | GoogleSearchRetrievalTool;
  5. Understand Content and Parts structure

    main

    The core data unit in the Gemini API is Content. A Content object consists of a role (e.g., 'user', 'model', 'system', 'function') and an array of Part objects.

    Part is a union type that can represent:

    • TextPart: Plain text.
    • InlineDataPart: Base64 encoded media (blobs).
    • FunctionCallPart: A request from the model to call a function.
    • FunctionResponsePart: The result of a function execution provided to the model.
    • FileDataPart: Reference to a file via URI.
    • ExecutableCodePart: Code to be executed by the model.
    • CodeExecutionResultPart: The output of code execution.
  6. Handle streaming responses with GenerateContentStreamResult

    main

    When calling generateContentStream(), the API returns a GenerateContentStreamResult object. This object provides two ways to access the generated content:

    1. Real-time streaming: Iterate over the stream property, which is an AsyncGenerator. This allows you to process individual chunks of the response as they are being generated.
    2. Aggregated response: Await the response property, which is a Promise. This resolves to the full, aggregated EnhancedGenerateContentResponse once the entire stream has completed.

    You can use both simultaneously if you need to update a UI incrementally while also having access to the final complete object.

  7. Use Tools: Function Calling, Code Execution, and Google Search

    main

    The Tool type allows you to extend model capabilities. A Tool can be one of the following:

    1. Function Declarations (FunctionDeclarationsTool): Define FunctionDeclaration objects containing a name, description, and parameters (using FunctionDeclarationSchema) to enable the model to call your local functions.
    2. Code Execution (CodeExecutionTool): Enables the model to write and run code (currently supports PYTHON).
    3. Google Search Retrieval (GoogleSearchRetrievalTool): Enables the model to use Google Search for information retrieval.
  8. Use the Part type for multi-modal content

    main

    The Part type is a union type used to represent different types of content within a request or response in the Gemini API. It allows you to compose multi-modal inputs (text, images, files) or handle structured data like function calls and code execution results.

    Depending on your use case, a Part can be one of the following:

    • TextPart: Plain text content.
    • InlineDataPart: Base64 encoded data (e.g., images).
    • FunctionCallPart: A request from the model to call a specific function.
    • FunctionResponsePart: The result of a function call provided back to the model.
    • FileDataPart: Reference to a file already uploaded to the Gemini File API.
    • ExecutableCodePart: Code intended for execution.
    • CodeExecutionResultPart: The output/result of executed code.
    export type Part = TextPart | InlineDataPart | FunctionCallPart | FunctionResponsePart | FileDataPart | ExecutableCodePart | CodeExecutionResultPart;
  9. Use StringSchema to define string properties in schema

    main

    The StringSchema type is used to describe string-based properties within a JSON schema for structured output. It is a union type that allows you to define either a basic string or a string constrained to a specific set of allowed values (an enum).

    To use it, you must choose between:

    • SimpleStringSchema: For general strings.
    • EnumStringSchema: For strings that must match one of several predefined values.
    export type StringSchema = SimpleStringSchema | EnumStringSchema;