@google/generative-ai
Advanced tools
Comparing version 0.2.1 to 0.3.0
@@ -89,22 +89,7 @@ /** | ||
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
/** | ||
* Content type for both prompts and response candidates. | ||
* @public | ||
*/ | ||
export declare interface Content extends InputContent { | ||
export declare interface Content { | ||
role: Role; | ||
parts: Part[]; | ||
@@ -166,2 +151,3 @@ } | ||
text: () => string; | ||
functionCall: () => FunctionCall | undefined; | ||
} | ||
@@ -183,2 +169,181 @@ | ||
/** | ||
* A predicted [FunctionCall] returned from the model | ||
* that contains a string representing the [FunctionDeclaration.name] | ||
* and a structured JSON object containing the parameters and their values. | ||
* @public | ||
*/ | ||
export declare interface FunctionCall { | ||
name: string; | ||
args: object; | ||
} | ||
/** | ||
* Content part interface if the part represents FunctionResponse. | ||
* @public | ||
*/ | ||
export declare interface FunctionCallPart { | ||
text?: never; | ||
inlineData?: never; | ||
functionCall: FunctionCall; | ||
functionResponse?: never; | ||
} | ||
/** | ||
* Structured representation of a function declaration as defined by the | ||
* [OpenAPI 3.0 specification](https://spec.openapis.org/oas/v3.0.3). Included | ||
* in this declaration are the function name and parameters. This | ||
* FunctionDeclaration is a representation of a block of code that can be used | ||
* as a Tool by the model and executed by the client. | ||
* @public | ||
*/ | ||
export declare interface FunctionDeclaration { | ||
/** | ||
* The name of the function to call. Must start with a letter or an | ||
* underscore. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with | ||
* a max length of 64. | ||
*/ | ||
name: string; | ||
/** | ||
* Optional. Description and purpose of the function. Model uses it to decide | ||
* how and whether to call the function. | ||
*/ | ||
description?: string; | ||
/** | ||
* Optional. Describes the parameters to this function in JSON Schema Object | ||
* format. Reflects the Open API 3.03 Parameter Object. string Key: the name | ||
* of the parameter. Parameter names are case sensitive. Schema Value: the | ||
* Schema defining the type used for the parameter. For function with no | ||
* parameters, this can be left unset. | ||
* | ||
* @example with 1 required and 1 optional parameter: type: OBJECT properties: | ||
* ``` | ||
* param1: | ||
* | ||
* type: STRING | ||
* param2: | ||
* | ||
* type: INTEGER | ||
* required: | ||
* | ||
* - param1 | ||
* ``` | ||
*/ | ||
parameters?: FunctionDeclarationSchema; | ||
} | ||
/** | ||
* Schema for parameters passed to {@link FunctionDeclaration.parameters}. | ||
* @public | ||
*/ | ||
export declare interface FunctionDeclarationSchema { | ||
/** The type of the parameter. */ | ||
type: FunctionDeclarationSchemaType; | ||
/** The format of the parameter. */ | ||
properties: { | ||
[k: string]: FunctionDeclarationSchemaProperty; | ||
}; | ||
/** Optional. Description of the parameter. */ | ||
description?: string; | ||
/** Optional. Array of required parameters. */ | ||
required?: string[]; | ||
} | ||
/** | ||
* Schema is used to define the format of input/output data. | ||
* Represents a select subset of an OpenAPI 3.0 schema object. | ||
* More fields may be added in the future as needed. | ||
* @public | ||
*/ | ||
export declare interface FunctionDeclarationSchemaProperty { | ||
/** | ||
* Optional. The type of the property. {@link | ||
* FunctionDeclarationSchemaType}. | ||
*/ | ||
type?: FunctionDeclarationSchemaType; | ||
/** Optional. The format of the property. */ | ||
format?: string; | ||
/** Optional. The description of the property. */ | ||
description?: string; | ||
/** Optional. Whether the property is nullable. */ | ||
nullable?: boolean; | ||
/** Optional. The items of the property. {@link FunctionDeclarationSchema} */ | ||
items?: FunctionDeclarationSchema; | ||
/** Optional. The enum of the property. */ | ||
enum?: string[]; | ||
/** Optional. Map of {@link FunctionDeclarationSchema}. */ | ||
properties?: { | ||
[k: string]: FunctionDeclarationSchema; | ||
}; | ||
/** Optional. Array of required property. */ | ||
required?: string[]; | ||
/** Optional. The example of the property. */ | ||
example?: unknown; | ||
} | ||
/** | ||
* Contains the list of OpenAPI data types | ||
* as defined by https://swagger.io/docs/specification/data-models/data-types/ | ||
* @public | ||
*/ | ||
export declare enum FunctionDeclarationSchemaType { | ||
/** String type. */ | ||
STRING = "STRING", | ||
/** Number type. */ | ||
NUMBER = "NUMBER", | ||
/** Integer type. */ | ||
INTEGER = "INTEGER", | ||
/** Boolean type. */ | ||
BOOLEAN = "BOOLEAN", | ||
/** Array type. */ | ||
ARRAY = "ARRAY", | ||
/** Object type. */ | ||
OBJECT = "OBJECT" | ||
} | ||
/** | ||
* A FunctionDeclarationsTool is a piece of code that enables the system to | ||
* interact with external systems to perform an action, or set of actions, | ||
* outside of knowledge and scope of the model. | ||
* @public | ||
*/ | ||
export declare interface FunctionDeclarationsTool { | ||
/** | ||
* Optional. One or more function declarations | ||
* to be passed to the model along with the current user query. Model may | ||
* decide to call a subset of these functions by populating | ||
* [FunctionCall][content.part.functionCall] in the response. User should | ||
* provide a [FunctionResponse][content.part.functionResponse] for each | ||
* function call in the next turn. Based on the function responses, Model will | ||
* generate the final response back to the user. Maximum 64 function | ||
* declarations can be provided. | ||
*/ | ||
functionDeclarations?: FunctionDeclaration[]; | ||
} | ||
/** | ||
* The result output from a [FunctionCall] that contains a string | ||
* representing the [FunctionDeclaration.name] | ||
* and a structured JSON object containing any output | ||
* from the function is used as context to the model. | ||
* This should contain the result of a [FunctionCall] | ||
* made based on model prediction. | ||
* @public | ||
*/ | ||
export declare interface FunctionResponse { | ||
name: string; | ||
response: object; | ||
} | ||
/** | ||
* Content part interface if the part represents FunctionResponse. | ||
* @public | ||
*/ | ||
export declare interface FunctionResponsePart { | ||
text?: never; | ||
inlineData?: never; | ||
functionCall?: never; | ||
functionResponse: FunctionResponse; | ||
} | ||
/** | ||
* A candidate returned as part of a {@link GenerateContentResponse}. | ||
@@ -202,2 +367,3 @@ * @public | ||
contents: Content[]; | ||
tools?: Tool[]; | ||
} | ||
@@ -274,2 +440,3 @@ | ||
requestOptions: RequestOptions; | ||
tools?: Tool[]; | ||
constructor(apiKey: string, modelParams: ModelParams, requestOptions?: RequestOptions); | ||
@@ -333,18 +500,2 @@ /** | ||
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
/** | ||
* Harm categories that would cause prompts or candidates to be blocked. | ||
@@ -380,14 +531,7 @@ * @public | ||
inlineData: GenerativeContentBlob; | ||
functionCall?: never; | ||
functionResponse?: never; | ||
} | ||
/** | ||
* Content that can be provided as history input to startChat(). | ||
* @public | ||
*/ | ||
export declare interface InputContent { | ||
parts: string | Array<string | Part>; | ||
role: string; | ||
} | ||
/** | ||
* Params passed to {@link GoogleGenerativeAI.getGenerativeModel}. | ||
@@ -398,2 +542,3 @@ * @public | ||
model: string; | ||
tools?: Tool[]; | ||
} | ||
@@ -405,5 +550,11 @@ | ||
*/ | ||
export declare type Part = TextPart | InlineDataPart; | ||
export declare type Part = TextPart | InlineDataPart | FunctionCallPart | FunctionResponsePart; | ||
/** | ||
* Possible roles. | ||
* @public | ||
*/ | ||
export declare const POSSIBLE_ROLES: readonly ["user", "model", "function"]; | ||
/** | ||
* If the prompt was blocked, this will be populated with `blockReason` and | ||
@@ -424,6 +575,36 @@ * the relevant `safetyRatings`. | ||
export declare interface RequestOptions { | ||
/** | ||
* Request timeout in milliseconds. | ||
*/ | ||
timeout?: number; | ||
/** | ||
* Version of API endpoint to call (e.g. "v1" or "v1beta"). If not specified, | ||
* defaults to latest stable version. | ||
*/ | ||
apiVersion?: string; | ||
} | ||
/** | ||
* @license | ||
* Copyright 2024 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
/** | ||
* Role is the producer of the content. | ||
* @public | ||
*/ | ||
export declare type Role = (typeof POSSIBLE_ROLES)[number]; | ||
/** | ||
* A safety rating associated with a {@link GenerateContentCandidate} | ||
@@ -451,3 +632,4 @@ * @public | ||
export declare interface StartChatParams extends BaseParams { | ||
history?: InputContent[]; | ||
history?: Content[]; | ||
tools?: Tool[]; | ||
} | ||
@@ -475,4 +657,12 @@ | ||
inlineData?: never; | ||
functionCall?: never; | ||
functionResponse?: never; | ||
} | ||
/** | ||
* Defines a tool that model can call to access external knowledge. | ||
* @public | ||
*/ | ||
export declare type Tool = FunctionDeclarationsTool; | ||
export { } |
@@ -5,3 +5,3 @@ 'use strict'; | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -21,2 +21,7 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
/** | ||
* Possible roles. | ||
* @public | ||
*/ | ||
const POSSIBLE_ROLES = ["user", "model", "function"]; | ||
/** | ||
* Harm categories that would cause prompts or candidates to be blocked. | ||
@@ -115,3 +120,3 @@ * @public | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -130,2 +135,39 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
*/ | ||
/** | ||
* Contains the list of OpenAPI data types | ||
* as defined by https://swagger.io/docs/specification/data-models/data-types/ | ||
* @public | ||
*/ | ||
exports.FunctionDeclarationSchemaType = void 0; | ||
(function (FunctionDeclarationSchemaType) { | ||
/** String type. */ | ||
FunctionDeclarationSchemaType["STRING"] = "STRING"; | ||
/** Number type. */ | ||
FunctionDeclarationSchemaType["NUMBER"] = "NUMBER"; | ||
/** Integer type. */ | ||
FunctionDeclarationSchemaType["INTEGER"] = "INTEGER"; | ||
/** Boolean type. */ | ||
FunctionDeclarationSchemaType["BOOLEAN"] = "BOOLEAN"; | ||
/** Array type. */ | ||
FunctionDeclarationSchemaType["ARRAY"] = "ARRAY"; | ||
/** Object type. */ | ||
FunctionDeclarationSchemaType["OBJECT"] = "OBJECT"; | ||
})(exports.FunctionDeclarationSchemaType || (exports.FunctionDeclarationSchemaType = {})); | ||
/** | ||
* @license | ||
* Copyright 2024 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
class GoogleGenerativeAIError extends Error { | ||
@@ -145,3 +187,3 @@ constructor(message) { | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -161,3 +203,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
const BASE_URL = "https://generativelanguage.googleapis.com"; | ||
const API_VERSION = "v1"; | ||
const DEFAULT_API_VERSION = "v1"; | ||
/** | ||
@@ -167,3 +209,3 @@ * We can't `require` package.json if this runs on web. We will use rollup to | ||
*/ | ||
const PACKAGE_VERSION = "0.2.1"; | ||
const PACKAGE_VERSION = "0.3.0"; | ||
const PACKAGE_LOG_HEADER = "genai-js"; | ||
@@ -179,3 +221,3 @@ var Task; | ||
class RequestUrl { | ||
constructor(model, task, apiKey, stream) { | ||
constructor(model, task, apiKey, stream, requestOptions) { | ||
this.model = model; | ||
@@ -185,5 +227,8 @@ this.task = task; | ||
this.stream = stream; | ||
this.requestOptions = requestOptions; | ||
} | ||
toString() { | ||
let url = `${BASE_URL}/${API_VERSION}/${this.model}:${this.task}`; | ||
var _a; | ||
const apiVersion = ((_a = this.requestOptions) === null || _a === void 0 ? void 0 : _a.apiVersion) || DEFAULT_API_VERSION; | ||
let url = `${BASE_URL}/${apiVersion}/${this.model}:${this.task}`; | ||
if (this.stream) { | ||
@@ -249,3 +294,3 @@ url += "?alt=sse"; | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -286,2 +331,19 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
}; | ||
response.functionCall = () => { | ||
if (response.candidates && response.candidates.length > 0) { | ||
if (response.candidates.length > 1) { | ||
console.warn(`This response had ${response.candidates.length} ` + | ||
`candidates. Returning function call from the first candidate only. ` + | ||
`Access response.candidates directly to use the other candidates.`); | ||
} | ||
if (hadBadFinishReason(response.candidates[0])) { | ||
throw new GoogleGenerativeAIResponseError(`${formatBlockErrorMessage(response)}`, response); | ||
} | ||
return getFunctionCall(response); | ||
} | ||
else if (response.promptFeedback) { | ||
throw new GoogleGenerativeAIResponseError(`Function call not available. ${formatBlockErrorMessage(response)}`, response); | ||
} | ||
return undefined; | ||
}; | ||
return response; | ||
@@ -295,3 +357,5 @@ } | ||
if ((_d = (_c = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.text) { | ||
return response.candidates[0].content.parts[0].text; | ||
return response.candidates[0].content.parts | ||
.map(({ text }) => text) | ||
.join(""); | ||
} | ||
@@ -302,2 +366,9 @@ else { | ||
} | ||
/** | ||
* Returns functionCall of first candidate. | ||
*/ | ||
function getFunctionCall(response) { | ||
var _a, _b, _c, _d; | ||
return (_d = (_c = (_b = (_a = response.candidates) === null || _a === void 0 ? void 0 : _a[0].content) === null || _b === void 0 ? void 0 : _b.parts) === null || _c === void 0 ? void 0 : _c[0]) === null || _d === void 0 ? void 0 : _d.functionCall; | ||
} | ||
const badFinishReasons = [exports.FinishReason.RECITATION, exports.FinishReason.SAFETY]; | ||
@@ -373,3 +444,3 @@ function hadBadFinishReason(candidate) { | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -509,10 +580,17 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
role: candidate.content.role || "user", | ||
parts: [{ text: "" }], | ||
parts: [], | ||
}; | ||
} | ||
const newPart = {}; | ||
for (const part of candidate.content.parts) { | ||
if (part.text) { | ||
aggregatedResponse.candidates[i].content.parts[0].text += | ||
part.text; | ||
newPart.text = part.text; | ||
} | ||
if (part.functionCall) { | ||
newPart.functionCall = part.functionCall; | ||
} | ||
if (Object.keys(newPart).length === 0) { | ||
newPart.text = ""; | ||
} | ||
aggregatedResponse.candidates[i].content.parts.push(newPart); | ||
} | ||
@@ -528,3 +606,3 @@ } | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -545,3 +623,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
const url = new RequestUrl(model, Task.STREAM_GENERATE_CONTENT, apiKey, | ||
/* stream */ true); | ||
/* stream */ true, requestOptions); | ||
const response = await makeRequest(url, JSON.stringify(params), requestOptions); | ||
@@ -552,3 +630,3 @@ return processStream(response); | ||
const url = new RequestUrl(model, Task.GENERATE_CONTENT, apiKey, | ||
/* stream */ false); | ||
/* stream */ false, requestOptions); | ||
const response = await makeRequest(url, JSON.stringify(params), requestOptions); | ||
@@ -564,3 +642,3 @@ const responseJson = await response.json(); | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -579,3 +657,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
*/ | ||
function formatNewContent(request, role) { | ||
function formatNewContent(request) { | ||
let newParts = []; | ||
@@ -595,4 +673,38 @@ if (typeof request === "string") { | ||
} | ||
return { role, parts: newParts }; | ||
return assignRoleToPartsAndValidateSendMessageRequest(newParts); | ||
} | ||
/** | ||
* When multiple Part types (i.e. FunctionResponsePart and TextPart) are | ||
* passed in a single Part array, we may need to assign different roles to each | ||
* part. Currently only FunctionResponsePart requires a role other than 'user'. | ||
* @private | ||
* @param parts Array of parts to pass to the model | ||
* @returns Array of content items | ||
*/ | ||
function assignRoleToPartsAndValidateSendMessageRequest(parts) { | ||
const userContent = { role: "user", parts: [] }; | ||
const functionContent = { role: "function", parts: [] }; | ||
let hasUserContent = false; | ||
let hasFunctionContent = false; | ||
for (const part of parts) { | ||
if ("functionResponse" in part) { | ||
functionContent.parts.push(part); | ||
hasFunctionContent = true; | ||
} | ||
else { | ||
userContent.parts.push(part); | ||
hasUserContent = true; | ||
} | ||
} | ||
if (hasUserContent && hasFunctionContent) { | ||
throw new GoogleGenerativeAIError("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message."); | ||
} | ||
if (!hasUserContent && !hasFunctionContent) { | ||
throw new GoogleGenerativeAIError("No content is provided for sending chat message."); | ||
} | ||
if (hasUserContent) { | ||
return userContent; | ||
} | ||
return functionContent; | ||
} | ||
function formatGenerateContentInput(params) { | ||
@@ -603,3 +715,3 @@ if (params.contents) { | ||
else { | ||
const content = formatNewContent(params, "user"); | ||
const content = formatNewContent(params); | ||
return { contents: [content] }; | ||
@@ -610,3 +722,3 @@ } | ||
if (typeof params === "string" || Array.isArray(params)) { | ||
const content = formatNewContent(params, "user"); | ||
const content = formatNewContent(params); | ||
return { content }; | ||
@@ -619,3 +731,3 @@ } | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -634,3 +746,78 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
*/ | ||
// https://ai.google.dev/api/rest/v1beta/Content#part | ||
const VALID_PART_FIELDS = [ | ||
"text", | ||
"inlineData", | ||
"functionCall", | ||
"functionResponse", | ||
]; | ||
const VALID_PARTS_PER_ROLE = { | ||
user: ["text", "inlineData"], | ||
function: ["functionResponse"], | ||
model: ["text", "functionCall"], | ||
}; | ||
const VALID_PREVIOUS_CONTENT_ROLES = { | ||
user: ["model"], | ||
function: ["model"], | ||
model: ["user", "function"], | ||
}; | ||
function validateChatHistory(history) { | ||
let prevContent; | ||
for (const currContent of history) { | ||
const { role, parts } = currContent; | ||
if (!prevContent && role !== "user") { | ||
throw new GoogleGenerativeAIError(`First content should be with role 'user', got ${role}`); | ||
} | ||
if (!POSSIBLE_ROLES.includes(role)) { | ||
throw new GoogleGenerativeAIError(`Each item should include role field. Got ${role} but valid roles are: ${JSON.stringify(POSSIBLE_ROLES)}`); | ||
} | ||
if (parts.length === 0) { | ||
throw new GoogleGenerativeAIError("Each Content should have at least one part"); | ||
} | ||
const countFields = { | ||
text: 0, | ||
inlineData: 0, | ||
functionCall: 0, | ||
functionResponse: 0, | ||
}; | ||
for (const part of parts) { | ||
for (const key of VALID_PART_FIELDS) { | ||
if (key in part) { | ||
countFields[key] += 1; | ||
} | ||
} | ||
} | ||
const validParts = VALID_PARTS_PER_ROLE[role]; | ||
for (const key of VALID_PART_FIELDS) { | ||
if (!validParts.includes(key) && countFields[key] > 0) { | ||
throw new GoogleGenerativeAIError(`Content with role '${role}' can't contain '${key}' part`); | ||
} | ||
} | ||
if (prevContent) { | ||
const validPreviousContentRoles = VALID_PREVIOUS_CONTENT_ROLES[role]; | ||
if (!validPreviousContentRoles.includes(prevContent.role)) { | ||
throw new GoogleGenerativeAIError(`Content with role '${role}' can't follow '${prevContent.role}'`); | ||
} | ||
} | ||
prevContent = currContent; | ||
} | ||
} | ||
/** | ||
* @license | ||
* Copyright 2024 Google LLC | ||
* | ||
* Licensed under the Apache License, Version 2.0 (the "License"); | ||
* you may not use this file except in compliance with the License. | ||
* You may obtain a copy of the License at | ||
* | ||
* http://www.apache.org/licenses/LICENSE-2.0 | ||
* | ||
* Unless required by applicable law or agreed to in writing, software | ||
* distributed under the License is distributed on an "AS IS" BASIS, | ||
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
* See the License for the specific language governing permissions and | ||
* limitations under the License. | ||
*/ | ||
/** | ||
* Do not log a message for this error. | ||
@@ -654,8 +841,4 @@ */ | ||
if (params === null || params === void 0 ? void 0 : params.history) { | ||
this._history = params.history.map((content) => { | ||
if (!content.role) { | ||
throw new Error("Missing role for history item: " + JSON.stringify(content)); | ||
} | ||
return formatNewContent(content.parts, content.role); | ||
}); | ||
validateChatHistory(params.history); | ||
this._history = params.history; | ||
} | ||
@@ -677,8 +860,9 @@ } | ||
async sendMessage(request) { | ||
var _a, _b; | ||
var _a, _b, _c; | ||
await this._sendPromise; | ||
const newContent = formatNewContent(request, "user"); | ||
const newContent = formatNewContent(request); | ||
const generateContentRequest = { | ||
safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings, | ||
generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig, | ||
tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools, | ||
contents: [...this._history, newContent], | ||
@@ -717,8 +901,9 @@ }; | ||
async sendMessageStream(request) { | ||
var _a, _b; | ||
var _a, _b, _c; | ||
await this._sendPromise; | ||
const newContent = formatNewContent(request, "user"); | ||
const newContent = formatNewContent(request); | ||
const generateContentRequest = { | ||
safetySettings: (_a = this.params) === null || _a === void 0 ? void 0 : _a.safetySettings, | ||
generationConfig: (_b = this.params) === null || _b === void 0 ? void 0 : _b.generationConfig, | ||
tools: (_c = this.params) === null || _c === void 0 ? void 0 : _c.tools, | ||
contents: [...this._history, newContent], | ||
@@ -769,3 +954,3 @@ }; | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -785,3 +970,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
async function countTokens(apiKey, model, params, requestOptions) { | ||
const url = new RequestUrl(model, Task.COUNT_TOKENS, apiKey, false); | ||
const url = new RequestUrl(model, Task.COUNT_TOKENS, apiKey, false, {}); | ||
const response = await makeRequest(url, JSON.stringify(Object.assign(Object.assign({}, params), { model })), requestOptions); | ||
@@ -793,3 +978,3 @@ return response.json(); | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -809,3 +994,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
async function embedContent(apiKey, model, params, requestOptions) { | ||
const url = new RequestUrl(model, Task.EMBED_CONTENT, apiKey, false); | ||
const url = new RequestUrl(model, Task.EMBED_CONTENT, apiKey, false, {}); | ||
const response = await makeRequest(url, JSON.stringify(params), requestOptions); | ||
@@ -815,3 +1000,3 @@ return response.json(); | ||
async function batchEmbedContents(apiKey, model, params, requestOptions) { | ||
const url = new RequestUrl(model, Task.BATCH_EMBED_CONTENTS, apiKey, false); | ||
const url = new RequestUrl(model, Task.BATCH_EMBED_CONTENTS, apiKey, false, {}); | ||
const requestsWithModel = params.requests.map((request) => { | ||
@@ -826,3 +1011,3 @@ return Object.assign(Object.assign({}, request), { model }); | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -858,2 +1043,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
this.safetySettings = modelParams.safetySettings || []; | ||
this.tools = modelParams.tools; | ||
this.requestOptions = requestOptions || {}; | ||
@@ -867,3 +1053,3 @@ } | ||
const formattedParams = formatGenerateContentInput(request); | ||
return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings }, formattedParams), this.requestOptions); | ||
return generateContent(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools }, formattedParams), this.requestOptions); | ||
} | ||
@@ -878,3 +1064,3 @@ /** | ||
const formattedParams = formatGenerateContentInput(request); | ||
return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings }, formattedParams), this.requestOptions); | ||
return generateContentStream(this.apiKey, this.model, Object.assign({ generationConfig: this.generationConfig, safetySettings: this.safetySettings, tools: this.tools }, formattedParams), this.requestOptions); | ||
} | ||
@@ -886,3 +1072,3 @@ /** | ||
startChat(startChatParams) { | ||
return new ChatSession(this.apiKey, this.model, startChatParams, this.requestOptions); | ||
return new ChatSession(this.apiKey, this.model, Object.assign({ tools: this.tools }, startChatParams), this.requestOptions); | ||
} | ||
@@ -913,3 +1099,3 @@ /** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -951,2 +1137,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
exports.GoogleGenerativeAI = GoogleGenerativeAI; | ||
exports.POSSIBLE_ROLES = POSSIBLE_ROLES; | ||
//# sourceMappingURL=index.js.map |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -5,0 +5,0 @@ * Licensed under the Apache License, Version 2.0 (the "License"); |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -5,0 +5,0 @@ * Licensed under the Apache License, Version 2.0 (the "License"); |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -5,0 +5,0 @@ * Licensed under the Apache License, Version 2.0 (the "License"); |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -5,0 +5,0 @@ * Licensed under the Apache License, Version 2.0 (the "License"); |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -5,0 +5,0 @@ * Licensed under the Apache License, Version 2.0 (the "License"); |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -5,0 +5,0 @@ * Licensed under the Apache License, Version 2.0 (the "License"); |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -5,0 +5,0 @@ * Licensed under the Apache License, Version 2.0 (the "License"); |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -17,3 +17,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
*/ | ||
import { BatchEmbedContentsRequest, BatchEmbedContentsResponse, CountTokensRequest, CountTokensResponse, EmbedContentRequest, EmbedContentResponse, GenerateContentRequest, GenerateContentResult, GenerateContentStreamResult, GenerationConfig, ModelParams, Part, RequestOptions, SafetySetting, StartChatParams } from "../../types"; | ||
import { BatchEmbedContentsRequest, BatchEmbedContentsResponse, CountTokensRequest, CountTokensResponse, EmbedContentRequest, EmbedContentResponse, GenerateContentRequest, GenerateContentResult, GenerateContentStreamResult, GenerationConfig, ModelParams, Part, RequestOptions, SafetySetting, StartChatParams, Tool } from "../../types"; | ||
import { ChatSession } from "../methods/chat-session"; | ||
@@ -30,2 +30,3 @@ /** | ||
requestOptions: RequestOptions; | ||
tools?: Tool[]; | ||
constructor(apiKey: string, modelParams: ModelParams, requestOptions?: RequestOptions); | ||
@@ -32,0 +33,0 @@ /** |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -18,4 +18,4 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
import { Content, EmbedContentRequest, GenerateContentRequest, Part } from "../../types"; | ||
export declare function formatNewContent(request: string | Array<string | Part>, role: string): Content; | ||
export declare function formatNewContent(request: string | Array<string | Part>): Content; | ||
export declare function formatGenerateContentInput(params: GenerateContentRequest | string | Array<string | Part>): GenerateContentRequest; | ||
export declare function formatEmbedContentInput(params: EmbedContentRequest | string | Array<string | Part>): EmbedContentRequest; |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -18,2 +18,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
import { RequestOptions } from "../../types"; | ||
export declare const DEFAULT_API_VERSION = "v1"; | ||
export declare enum Task { | ||
@@ -31,5 +32,6 @@ GENERATE_CONTENT = "generateContent", | ||
stream: boolean; | ||
constructor(model: string, task: Task, apiKey: string, stream: boolean); | ||
requestOptions: RequestOptions; | ||
constructor(model: string, task: Task, apiKey: string, stream: boolean, requestOptions: RequestOptions); | ||
toString(): string; | ||
} | ||
export declare function makeRequest(url: RequestUrl, body: string, requestOptions?: RequestOptions): Promise<Response>; |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -17,3 +17,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
*/ | ||
import { EnhancedGenerateContentResponse, GenerateContentResponse } from "../../types"; | ||
import { EnhancedGenerateContentResponse, FunctionCall, GenerateContentResponse } from "../../types"; | ||
/** | ||
@@ -28,2 +28,6 @@ * Adds convenience helper methods to a response object, including stream | ||
export declare function getText(response: GenerateContentResponse): string; | ||
/** | ||
* Returns functionCall of first candidate. | ||
*/ | ||
export declare function getFunctionCall(response: GenerateContentResponse): FunctionCall; | ||
export declare function formatBlockErrorMessage(response: GenerateContentResponse): string; |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -5,0 +5,0 @@ * Licensed under the Apache License, Version 2.0 (the "License"); |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -17,2 +17,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
*/ | ||
import { Role } from "./enums"; | ||
/** | ||
@@ -22,18 +23,11 @@ * Content type for both prompts and response candidates. | ||
*/ | ||
export interface Content extends InputContent { | ||
export interface Content { | ||
role: Role; | ||
parts: Part[]; | ||
} | ||
/** | ||
* Content that can be provided as history input to startChat(). | ||
* @public | ||
*/ | ||
export interface InputContent { | ||
parts: string | Array<string | Part>; | ||
role: string; | ||
} | ||
/** | ||
* Content part - includes text or image part types. | ||
* @public | ||
*/ | ||
export type Part = TextPart | InlineDataPart; | ||
export type Part = TextPart | InlineDataPart | FunctionCallPart | FunctionResponsePart; | ||
/** | ||
@@ -46,2 +40,4 @@ * Content part interface if the part represents a text string. | ||
inlineData?: never; | ||
functionCall?: never; | ||
functionResponse?: never; | ||
} | ||
@@ -55,4 +51,49 @@ /** | ||
inlineData: GenerativeContentBlob; | ||
functionCall?: never; | ||
functionResponse?: never; | ||
} | ||
/** | ||
* Content part interface if the part represents FunctionResponse. | ||
* @public | ||
*/ | ||
export interface FunctionCallPart { | ||
text?: never; | ||
inlineData?: never; | ||
functionCall: FunctionCall; | ||
functionResponse?: never; | ||
} | ||
/** | ||
* Content part interface if the part represents FunctionResponse. | ||
* @public | ||
*/ | ||
export interface FunctionResponsePart { | ||
text?: never; | ||
inlineData?: never; | ||
functionCall?: never; | ||
functionResponse: FunctionResponse; | ||
} | ||
/** | ||
* A predicted [FunctionCall] returned from the model | ||
* that contains a string representing the [FunctionDeclaration.name] | ||
* and a structured JSON object containing the parameters and their values. | ||
* @public | ||
*/ | ||
export interface FunctionCall { | ||
name: string; | ||
args: object; | ||
} | ||
/** | ||
* The result output from a [FunctionCall] that contains a string | ||
* representing the [FunctionDeclaration.name] | ||
* and a structured JSON object containing any output | ||
* from the function is used as context to the model. | ||
* This should contain the result of a [FunctionCall] | ||
* made based on model prediction. | ||
* @public | ||
*/ | ||
export interface FunctionResponse { | ||
name: string; | ||
response: object; | ||
} | ||
/** | ||
* Interface for sending an image. | ||
@@ -59,0 +100,0 @@ * @public |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -18,2 +18,12 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
/** | ||
* Role is the producer of the content. | ||
* @public | ||
*/ | ||
export type Role = (typeof POSSIBLE_ROLES)[number]; | ||
/** | ||
* Possible roles. | ||
* @public | ||
*/ | ||
export declare const POSSIBLE_ROLES: readonly ["user", "model", "function"]; | ||
/** | ||
* Harm categories that would cause prompts or candidates to be blocked. | ||
@@ -20,0 +30,0 @@ * @public |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -5,0 +5,0 @@ * Licensed under the Apache License, Version 2.0 (the "License"); |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -17,3 +17,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
*/ | ||
import { Content, InputContent } from "./content"; | ||
import { Content } from "./content"; | ||
import { HarmBlockThreshold, HarmCategory, TaskType } from "./enums"; | ||
@@ -34,2 +34,3 @@ /** | ||
model: string; | ||
tools?: Tool[]; | ||
} | ||
@@ -42,2 +43,3 @@ /** | ||
contents: Content[]; | ||
tools?: Tool[]; | ||
} | ||
@@ -69,3 +71,4 @@ /** | ||
export interface StartChatParams extends BaseParams { | ||
history?: InputContent[]; | ||
history?: Content[]; | ||
tools?: Tool[]; | ||
} | ||
@@ -100,3 +103,143 @@ /** | ||
export interface RequestOptions { | ||
/** | ||
* Request timeout in milliseconds. | ||
*/ | ||
timeout?: number; | ||
/** | ||
* Version of API endpoint to call (e.g. "v1" or "v1beta"). If not specified, | ||
* defaults to latest stable version. | ||
*/ | ||
apiVersion?: string; | ||
} | ||
/** | ||
* Defines a tool that model can call to access external knowledge. | ||
* @public | ||
*/ | ||
export declare type Tool = FunctionDeclarationsTool; | ||
/** | ||
* Structured representation of a function declaration as defined by the | ||
* [OpenAPI 3.0 specification](https://spec.openapis.org/oas/v3.0.3). Included | ||
* in this declaration are the function name and parameters. This | ||
* FunctionDeclaration is a representation of a block of code that can be used | ||
* as a Tool by the model and executed by the client. | ||
* @public | ||
*/ | ||
export declare interface FunctionDeclaration { | ||
/** | ||
* The name of the function to call. Must start with a letter or an | ||
* underscore. Must be a-z, A-Z, 0-9, or contain underscores and dashes, with | ||
* a max length of 64. | ||
*/ | ||
name: string; | ||
/** | ||
* Optional. Description and purpose of the function. Model uses it to decide | ||
* how and whether to call the function. | ||
*/ | ||
description?: string; | ||
/** | ||
* Optional. Describes the parameters to this function in JSON Schema Object | ||
* format. Reflects the Open API 3.03 Parameter Object. string Key: the name | ||
* of the parameter. Parameter names are case sensitive. Schema Value: the | ||
* Schema defining the type used for the parameter. For function with no | ||
* parameters, this can be left unset. | ||
* | ||
* @example with 1 required and 1 optional parameter: type: OBJECT properties: | ||
* ``` | ||
* param1: | ||
* | ||
* type: STRING | ||
* param2: | ||
* | ||
* type: INTEGER | ||
* required: | ||
* | ||
* - param1 | ||
* ``` | ||
*/ | ||
parameters?: FunctionDeclarationSchema; | ||
} | ||
/** | ||
* A FunctionDeclarationsTool is a piece of code that enables the system to | ||
* interact with external systems to perform an action, or set of actions, | ||
* outside of knowledge and scope of the model. | ||
* @public | ||
*/ | ||
export declare interface FunctionDeclarationsTool { | ||
/** | ||
* Optional. One or more function declarations | ||
* to be passed to the model along with the current user query. Model may | ||
* decide to call a subset of these functions by populating | ||
* [FunctionCall][content.part.functionCall] in the response. User should | ||
* provide a [FunctionResponse][content.part.functionResponse] for each | ||
* function call in the next turn. Based on the function responses, Model will | ||
* generate the final response back to the user. Maximum 64 function | ||
* declarations can be provided. | ||
*/ | ||
functionDeclarations?: FunctionDeclaration[]; | ||
} | ||
/** | ||
* Contains the list of OpenAPI data types | ||
* as defined by https://swagger.io/docs/specification/data-models/data-types/ | ||
* @public | ||
*/ | ||
export declare enum FunctionDeclarationSchemaType { | ||
/** String type. */ | ||
STRING = "STRING", | ||
/** Number type. */ | ||
NUMBER = "NUMBER", | ||
/** Integer type. */ | ||
INTEGER = "INTEGER", | ||
/** Boolean type. */ | ||
BOOLEAN = "BOOLEAN", | ||
/** Array type. */ | ||
ARRAY = "ARRAY", | ||
/** Object type. */ | ||
OBJECT = "OBJECT" | ||
} | ||
/** | ||
* Schema for parameters passed to {@link FunctionDeclaration.parameters}. | ||
* @public | ||
*/ | ||
export interface FunctionDeclarationSchema { | ||
/** The type of the parameter. */ | ||
type: FunctionDeclarationSchemaType; | ||
/** The format of the parameter. */ | ||
properties: { | ||
[k: string]: FunctionDeclarationSchemaProperty; | ||
}; | ||
/** Optional. Description of the parameter. */ | ||
description?: string; | ||
/** Optional. Array of required parameters. */ | ||
required?: string[]; | ||
} | ||
/** | ||
* Schema is used to define the format of input/output data. | ||
* Represents a select subset of an OpenAPI 3.0 schema object. | ||
* More fields may be added in the future as needed. | ||
* @public | ||
*/ | ||
export interface FunctionDeclarationSchemaProperty { | ||
/** | ||
* Optional. The type of the property. {@link | ||
* FunctionDeclarationSchemaType}. | ||
*/ | ||
type?: FunctionDeclarationSchemaType; | ||
/** Optional. The format of the property. */ | ||
format?: string; | ||
/** Optional. The description of the property. */ | ||
description?: string; | ||
/** Optional. Whether the property is nullable. */ | ||
nullable?: boolean; | ||
/** Optional. The items of the property. {@link FunctionDeclarationSchema} */ | ||
items?: FunctionDeclarationSchema; | ||
/** Optional. The enum of the property. */ | ||
enum?: string[]; | ||
/** Optional. Map of {@link FunctionDeclarationSchema}. */ | ||
properties?: { | ||
[k: string]: FunctionDeclarationSchema; | ||
}; | ||
/** Optional. Array of required property. */ | ||
required?: string[]; | ||
/** Optional. The example of the property. */ | ||
example?: unknown; | ||
} |
/** | ||
* @license | ||
* Copyright 2023 Google LLC | ||
* Copyright 2024 Google LLC | ||
* | ||
@@ -17,3 +17,3 @@ * Licensed under the Apache License, Version 2.0 (the "License"); | ||
*/ | ||
import { Content } from "./content"; | ||
import { Content, FunctionCall } from "./content"; | ||
import { BlockReason, FinishReason, HarmCategory, HarmProbability } from "./enums"; | ||
@@ -51,2 +51,3 @@ /** | ||
text: () => string; | ||
functionCall: () => FunctionCall | undefined; | ||
} | ||
@@ -53,0 +54,0 @@ /** |
{ | ||
"name": "@google/generative-ai", | ||
"version": "0.2.1", | ||
"version": "0.3.0", | ||
"description": "Google AI JavaScript SDK", | ||
@@ -5,0 +5,0 @@ "main": "dist/index.js", |
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
Sorry, the diff of this file is not supported yet
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
License Policy Violation
LicenseThis package is not allowed per your license policy. Review the package's license to ensure compliance.
Found 1 instance in 1 package
146446
26
3741