From 5abb0978a98b6b3aa8cda3c8715618f325bb250f Mon Sep 17 00:00:00 2001 From: Ayush Agrawal Date: Tue, 21 Apr 2026 08:24:46 -0700 Subject: [PATCH] feat: support prompt management in the JS GenAI Modules PiperOrigin-RevId: 903243258 --- src/genai/agentengines.ts | 57 +- src/genai/client.ts | 3 + src/genai/converters/_prompts_converters.ts | 362 +++++++ src/genai/memories.ts | 105 +- src/genai/memoryrevisions.ts | 17 +- src/genai/prompts.ts | 1009 +++++++++++++++++++ src/genai/sandboxes.ts | 49 +- src/genai/sessionevents.ts | 17 +- src/genai/sessions.ts | 49 +- src/genai/types.ts | 1 + src/genai/types/common.ts | 698 ++++++++++++- src/genai/types/prompts.ts | 33 + test/genai/prompts_e2e_test.ts | 91 ++ test/genai/prompts_test.ts | 207 ++++ 14 files changed, 2610 insertions(+), 88 deletions(-) create mode 100644 src/genai/converters/_prompts_converters.ts create mode 100644 src/genai/prompts.ts create mode 100644 src/genai/types/prompts.ts create mode 100644 test/genai/prompts_e2e_test.ts create mode 100644 test/genai/prompts_test.ts diff --git a/src/genai/agentengines.ts b/src/genai/agentengines.ts index 23b54deb..48042a3f 100644 --- a/src/genai/agentengines.ts +++ b/src/genai/agentengines.ts @@ -6,6 +6,7 @@ // Code generated by the Google Gen AI SDK generator DO NOT EDIT. +import * as genaiTypes from '@google/genai'; import * as common from '@google/genai/vertex_internal'; import {ApiClient, BaseModule} from '@google/genai/vertex_internal'; import * as converters from './converters/_agentengines_converters.js'; @@ -51,8 +52,12 @@ export class AgentEngines extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -93,8 +98,12 @@ export class AgentEngines extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'DELETE', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -132,8 +141,12 @@ export class AgentEngines extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -173,8 +186,12 @@ export class AgentEngines extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -216,8 +233,12 @@ export class AgentEngines extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -257,8 +278,12 @@ export class AgentEngines extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -299,8 +324,12 @@ export class AgentEngines extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'PATCH', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); diff --git a/src/genai/client.ts b/src/genai/client.ts index 7d28d99f..3bba8249 100644 --- a/src/genai/client.ts +++ b/src/genai/client.ts @@ -6,6 +6,7 @@ import {ApiClient, NodeAuth, NodeDownloader, NodeUploader,} from '@google/genai/vertex_internal'; import {AgentEngines} from './agentengines'; +import {Prompts} from './prompts'; export const SDK_VERSION = '1.12.0'; // x-release-please-version @@ -14,6 +15,7 @@ let agentEnginesInternalWarned = false; export class Client { protected readonly apiClient: ApiClient; public readonly _agentEnginesInternal: AgentEngines; + public readonly prompts: Prompts; constructor( options: {project?: string; location?: string; apiEndpoint?: string;}) { @@ -43,6 +45,7 @@ export class Client { }); this._agentEnginesInternal = new AgentEngines(this.apiClient); + this.prompts = new Prompts(this.apiClient); } /** diff --git a/src/genai/converters/_prompts_converters.ts b/src/genai/converters/_prompts_converters.ts new file mode 100644 index 00000000..1432129d --- /dev/null +++ b/src/genai/converters/_prompts_converters.ts @@ -0,0 +1,362 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +import * as common from '@google/genai/vertex_internal'; +import * as types from '../types.js'; + +export function createDatasetParametersToVertex( + fromObject: types.CreateDatasetParameters, +): Record { + const toObject: Record = {}; + + const fromName = common.getValueByPath(fromObject, ['name']); + if (fromName != null) { + common.setValueByPath(toObject, ['name'], fromName); + } + + const fromDisplayName = common.getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + common.setValueByPath(toObject, ['displayName'], fromDisplayName); + } + + const fromMetadataSchemaUri = common.getValueByPath(fromObject, [ + 'metadataSchemaUri', + ]); + if (fromMetadataSchemaUri != null) { + common.setValueByPath( + toObject, + ['metadataSchemaUri'], + fromMetadataSchemaUri, + ); + } + + const fromMetadata = common.getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + common.setValueByPath(toObject, ['metadata'], fromMetadata); + } + + const fromDescription = common.getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + common.setValueByPath(toObject, ['description'], fromDescription); + } + + const fromEncryptionSpec = common.getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + common.setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + + const fromModelReference = common.getValueByPath(fromObject, [ + 'modelReference', + ]); + if (fromModelReference != null) { + common.setValueByPath(toObject, ['modelReference'], fromModelReference); + } + + const fromConfig = common.getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + common.setValueByPath(toObject, ['config'], fromConfig); + } + + return toObject; +} + +export function createDatasetVersionParametersToVertex( + fromObject: types.CreateDatasetVersionParameters, +): Record { + const toObject: Record = {}; + + const fromDatasetName = common.getValueByPath(fromObject, ['datasetName']); + if (fromDatasetName != null) { + common.setValueByPath(toObject, ['_url', 'name'], fromDatasetName); + } + + const fromMetadata = common.getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + common.setValueByPath(toObject, ['metadata'], fromMetadata); + } + + const fromModelReference = common.getValueByPath(fromObject, [ + 'modelReference', + ]); + if (fromModelReference != null) { + common.setValueByPath(toObject, ['modelReference'], fromModelReference); + } + + const fromParent = common.getValueByPath(fromObject, ['parent']); + if (fromParent != null) { + common.setValueByPath(toObject, ['parent'], fromParent); + } + + const fromDisplayName = common.getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + common.setValueByPath(toObject, ['displayName'], fromDisplayName); + } + + const fromConfig = common.getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + common.setValueByPath(toObject, ['config'], fromConfig); + } + + return toObject; +} + +export function deleteDatasetRequestParametersToVertex( + fromObject: types.DeleteDatasetRequestParameters, +): Record { + const toObject: Record = {}; + + const fromPromptId = common.getValueByPath(fromObject, ['promptId']); + if (fromPromptId != null) { + common.setValueByPath(toObject, ['_url', 'dataset_id'], fromPromptId); + } + + const fromConfig = common.getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + common.setValueByPath(toObject, ['config'], fromConfig); + } + + return toObject; +} + +export function deletePromptVersionRequestParametersToVertex( + fromObject: types.DeletePromptVersionRequestParameters, +): Record { + const toObject: Record = {}; + + const fromPromptId = common.getValueByPath(fromObject, ['promptId']); + if (fromPromptId != null) { + common.setValueByPath(toObject, ['_url', 'dataset_id'], fromPromptId); + } + + const fromVersionId = common.getValueByPath(fromObject, ['versionId']); + if (fromVersionId != null) { + common.setValueByPath(toObject, ['_url', 'version_id'], fromVersionId); + } + + const fromConfig = common.getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + common.setValueByPath(toObject, ['config'], fromConfig); + } + + return toObject; +} + +export function getDatasetOperationParametersToVertex( + fromObject: types.GetDatasetOperationParameters, +): Record { + const toObject: Record = {}; + + const fromDatasetId = common.getValueByPath(fromObject, ['datasetId']); + if (fromDatasetId != null) { + common.setValueByPath(toObject, ['_url', 'dataset_id'], fromDatasetId); + } + + const fromOperationId = common.getValueByPath(fromObject, ['operationId']); + if (fromOperationId != null) { + common.setValueByPath(toObject, ['_url', 'operation_id'], fromOperationId); + } + + const fromConfig = common.getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + common.setValueByPath(toObject, ['config'], fromConfig); + } + + return toObject; +} + +export function getDatasetParametersToVertex( + fromObject: types.GetDatasetParameters, +): Record { + const toObject: Record = {}; + + const fromName = common.getValueByPath(fromObject, ['name']); + if (fromName != null) { + common.setValueByPath(toObject, ['_url', 'name'], fromName); + } + + const fromConfig = common.getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + common.setValueByPath(toObject, ['config'], fromConfig); + } + + return toObject; +} + +export function getDatasetVersionParametersToVertex( + fromObject: types.GetDatasetVersionParameters, +): Record { + const toObject: Record = {}; + + const fromDatasetId = common.getValueByPath(fromObject, ['datasetId']); + if (fromDatasetId != null) { + common.setValueByPath(toObject, ['_url', 'dataset_id'], fromDatasetId); + } + + const fromDatasetVersionId = common.getValueByPath(fromObject, [ + 'datasetVersionId', + ]); + if (fromDatasetVersionId != null) { + common.setValueByPath( + toObject, + ['_url', 'dataset_version_id'], + fromDatasetVersionId, + ); + } + + const fromConfig = common.getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + common.setValueByPath(toObject, ['config'], fromConfig); + } + + return toObject; +} + +export function listDatasetVersionsRequestParametersToVertex( + fromObject: types.ListDatasetVersionsRequestParameters, +): Record { + const toObject: Record = {}; + + const fromReadMask = common.getValueByPath(fromObject, ['readMask']); + if (fromReadMask != null) { + common.setValueByPath(toObject, ['_url', 'read_mask'], fromReadMask); + } + + const fromDatasetId = common.getValueByPath(fromObject, ['datasetId']); + if (fromDatasetId != null) { + common.setValueByPath(toObject, ['_url', 'dataset_id'], fromDatasetId); + } + + const fromConfig = common.getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + common.setValueByPath( + toObject, + ['config'], + listPromptsConfigToVertex(fromConfig, toObject), + ); + } + + return toObject; +} + +export function listDatasetsRequestParametersToVertex( + fromObject: types.ListDatasetsRequestParameters, +): Record { + const toObject: Record = {}; + + const fromConfig = common.getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + common.setValueByPath( + toObject, + ['config'], + listPromptsConfigToVertex(fromConfig, toObject), + ); + } + + return toObject; +} + +export function listPromptsConfigToVertex( + fromObject: types.ListPromptsConfig, + parentObject: Record, +): Record { + const toObject: Record = {}; + + const fromPageSize = common.getValueByPath(fromObject, ['pageSize']); + if (parentObject !== undefined && fromPageSize != null) { + common.setValueByPath(parentObject, ['_query', 'pageSize'], fromPageSize); + } + + const fromPageToken = common.getValueByPath(fromObject, ['pageToken']); + if (parentObject !== undefined && fromPageToken != null) { + common.setValueByPath(parentObject, ['_query', 'pageToken'], fromPageToken); + } + + const fromFilter = common.getValueByPath(fromObject, ['filter']); + if (parentObject !== undefined && fromFilter != null) { + common.setValueByPath(parentObject, ['_query', 'filter'], fromFilter); + } + + return toObject; +} + +export function restoreVersionRequestParametersToVertex( + fromObject: types.RestoreVersionRequestParameters, +): Record { + const toObject: Record = {}; + + const fromDatasetId = common.getValueByPath(fromObject, ['datasetId']); + if (fromDatasetId != null) { + common.setValueByPath(toObject, ['_url', 'dataset_id'], fromDatasetId); + } + + const fromVersionId = common.getValueByPath(fromObject, ['versionId']); + if (fromVersionId != null) { + common.setValueByPath(toObject, ['_url', 'version_id'], fromVersionId); + } + + const fromConfig = common.getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + common.setValueByPath(toObject, ['config'], fromConfig); + } + + return toObject; +} + +export function updateDatasetParametersToVertex( + fromObject: types.UpdateDatasetParameters, +): Record { + const toObject: Record = {}; + + const fromName = common.getValueByPath(fromObject, ['name']); + if (fromName != null) { + common.setValueByPath(toObject, ['name'], fromName); + } + + const fromDatasetId = common.getValueByPath(fromObject, ['datasetId']); + if (fromDatasetId != null) { + common.setValueByPath(toObject, ['_url', 'dataset_id'], fromDatasetId); + } + + const fromDisplayName = common.getValueByPath(fromObject, ['displayName']); + if (fromDisplayName != null) { + common.setValueByPath(toObject, ['displayName'], fromDisplayName); + } + + const fromMetadata = common.getValueByPath(fromObject, ['metadata']); + if (fromMetadata != null) { + common.setValueByPath(toObject, ['metadata'], fromMetadata); + } + + const fromDescription = common.getValueByPath(fromObject, ['description']); + if (fromDescription != null) { + common.setValueByPath(toObject, ['description'], fromDescription); + } + + const fromEncryptionSpec = common.getValueByPath(fromObject, [ + 'encryptionSpec', + ]); + if (fromEncryptionSpec != null) { + common.setValueByPath(toObject, ['encryptionSpec'], fromEncryptionSpec); + } + + const fromModelReference = common.getValueByPath(fromObject, [ + 'modelReference', + ]); + if (fromModelReference != null) { + common.setValueByPath(toObject, ['modelReference'], fromModelReference); + } + + const fromConfig = common.getValueByPath(fromObject, ['config']); + if (fromConfig != null) { + common.setValueByPath(toObject, ['config'], fromConfig); + } + + return toObject; +} diff --git a/src/genai/memories.ts b/src/genai/memories.ts index 1e74b8a2..95234dab 100644 --- a/src/genai/memories.ts +++ b/src/genai/memories.ts @@ -6,6 +6,7 @@ // Code generated by the Google Gen AI SDK generator DO NOT EDIT. +import * as genaiTypes from '@google/genai'; import * as common from '@google/genai/vertex_internal'; import {ApiClient, BaseModule} from '@google/genai/vertex_internal'; import * as converters from './converters/_memories_converters.js'; @@ -45,8 +46,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -85,8 +90,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'DELETE', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -125,8 +134,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -165,8 +178,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -204,8 +221,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -244,8 +265,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -286,8 +311,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -328,8 +357,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -368,8 +401,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -410,8 +447,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -452,8 +493,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -492,8 +537,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'PATCH', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -532,8 +581,12 @@ export class Memories extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); diff --git a/src/genai/memoryrevisions.ts b/src/genai/memoryrevisions.ts index 864581b8..e7f8207a 100644 --- a/src/genai/memoryrevisions.ts +++ b/src/genai/memoryrevisions.ts @@ -6,6 +6,7 @@ // Code generated by the Google Gen AI SDK generator DO NOT EDIT. +import * as genaiTypes from '@google/genai'; import * as common from '@google/genai/vertex_internal'; import {ApiClient, BaseModule} from '@google/genai/vertex_internal'; import * as converters from './converters/_memoryrevisions_converters.js'; @@ -43,8 +44,12 @@ export class MemoryRevisions extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -85,8 +90,12 @@ export class MemoryRevisions extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); diff --git a/src/genai/prompts.ts b/src/genai/prompts.ts new file mode 100644 index 00000000..bbe53076 --- /dev/null +++ b/src/genai/prompts.ts @@ -0,0 +1,1009 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +import * as genaiTypes from '@google/genai'; +import * as common from '@google/genai/vertex_internal'; +import {ApiClient, BaseModule} from '@google/genai/vertex_internal'; +import * as converters from './converters/_prompts_converters.js'; +import * as types from './types.js'; + +export class Prompts extends BaseModule { + constructor(private readonly apiClient: ApiClient) { + super(); + } + + /* eslint-disable @typescript-eslint/no-explicit-any */ + private async _wait_for_operation( + operation: any, + timeout: number, + ): Promise { + let done = false; + let promptDatasetOperation: any; + + const responseOperationName = operation.name; + if (!responseOperationName) { + throw new Error('Invalid operation name.'); + } + + const datasetId = responseOperationName + .split('/datasets/')[1] + .split('/')[0]; + const operationId = responseOperationName.split('/').pop(); + + if (!operationId) { + throw new Error('Invalid operation name.'); + } + + const startTime = Date.now(); + let sleepDuration = 5000; // ms + const waitMultiplier = 2; + const maxWaitTime = 60000; // ms + let previousTime = Date.now(); + + while (!done) { + if (Date.now() - startTime > timeout * 1000) { + throw new Error( + `Create prompt operation did not complete within the specified timeout of ${timeout} seconds.`, + ); + } + const currentTime = Date.now(); + if (currentTime - previousTime >= sleepDuration) { + sleepDuration = Math.min(sleepDuration * waitMultiplier, maxWaitTime); + previousTime = currentTime; + } + await new Promise((resolve) => setTimeout(resolve, sleepDuration)); + + promptDatasetOperation = await this.getDatasetOperationInternal({ + datasetId: datasetId, + operationId: operationId, + }); + + done = promptDatasetOperation.done || false; + } + + if ( + !promptDatasetOperation || + !promptDatasetOperation.response || + !promptDatasetOperation.response['name'] + ) { + throw new Error('Error creating prompt version resource.'); + } + if (promptDatasetOperation.error) { + throw new Error( + `Error creating prompt version resource: ${JSON.stringify(promptDatasetOperation.error)}`, + ); + } + return promptDatasetOperation.response['name'] as string; + } + + private _createDatasetMetadataFromPrompt( + prompt: any, + variables?: Record[], + ): any { + const promptMetadata: any = {}; + const promptApiSchema: any = {}; + + promptApiSchema.multimodalPrompt = { + promptMessage: prompt.promptData, + }; + + promptApiSchema.apiSchemaVersion = '1.0.0'; + promptMetadata.hasPromptVariable = !!variables; + + if (variables) { + const promptExecutionList: any[] = []; + for (const promptVar of variables) { + const promptInstanceExecution: any = {arguments: {}}; + for (const [key, val] of Object.entries(promptVar)) { + promptInstanceExecution.arguments[key] = { + partList: {parts: [val]}, + }; + } + promptExecutionList.push(promptInstanceExecution); + } + promptApiSchema.executions = promptExecutionList; + } + + if (promptApiSchema.multimodalPrompt.promptMessage) { + const promptMessage = {...promptApiSchema.multimodalPrompt.promptMessage}; + delete promptMessage.variables; + promptApiSchema.multimodalPrompt.promptMessage = promptMessage; + } + + promptMetadata.promptApiSchema = promptApiSchema; + promptMetadata.promptType = 'multimodal_freeform'; + + return promptMetadata; + } + + private _createPromptFromDatasetMetadata(dataset: any): any { + const prompt: any = {}; + if (!dataset.metadata || !dataset.metadata.promptApiSchema) { + return prompt; + } + const apiSchema = dataset.metadata.promptApiSchema; + + if ( + apiSchema.multimodalPrompt && + apiSchema.multimodalPrompt.promptMessage + ) { + prompt.promptData = apiSchema.multimodalPrompt.promptMessage; + } + + if (apiSchema.executions) { + const variables: Record[] = []; + for (const execution of apiSchema.executions) { + const promptVar: Record = {}; + if (execution.arguments) { + for (const [key, val] of Object.entries(execution.arguments)) { + if (val && (val as any).partList && (val as any).partList.parts) { + promptVar[key] = (val as any).partList.parts[0]; + } + } + } + variables.push(promptVar); + } + if (prompt.promptData) { + prompt.promptData.variables = variables; + } + } + + if (dataset.modelReference) { + if (!prompt.promptData) { + prompt.promptData = {}; + } + prompt.promptData.model = dataset.modelReference; + } + + return prompt; + } + + private _raiseForInvalidPrompt(prompt: any): void { + if (!prompt.promptData) { + throw new Error('Prompt data must be provided.'); + } + if (!prompt.promptData.contents) { + throw new Error('Prompt contents must be provided.'); + } + if (!prompt.promptData.model) { + throw new Error('Model name must be provided.'); + } + if (prompt.promptData.contents && prompt.promptData.contents.length > 1) { + throw new Error('Multi-turn prompts are not currently supported.'); + } + } + + async create(params: {prompt: any; config?: any}): Promise { + const {prompt, config} = params; + + this._raiseForInvalidPrompt(prompt); + + const promptMetadata = this._createDatasetMetadataFromPrompt( + prompt, + prompt.promptData.variables, + ); + + const createPromptDatasetOperation = + await this.createDatasetResourceInternal({ + name: `projects/${this.apiClient.clientOptions.project}/locations/${this.apiClient.clientOptions.location}`, + displayName: config?.promptDisplayName || `prompt_${Date.now()}`, + metadataSchemaUri: + 'gs://google-cloud-aiplatform/schema/dataset/metadata/text_prompt_1.0.0.yaml', + metadata: promptMetadata, + modelReference: prompt.promptData.model, + encryptionSpec: config?.encryptionSpec, + }); + + const datasetResourceName = await this._wait_for_operation( + createPromptDatasetOperation, + config?.timeout || 90, + ); + + const datasetId = datasetResourceName.split('/').pop(); + if (!datasetId) { + throw new Error('Invalid dataset resource name.'); + } + + const datasetResource = await this.getDatasetResourceInternal({ + name: datasetId, + }); + + prompt._dataset = datasetResource; + return prompt; + } + + async createVersion(params: {prompt: any; config?: any}): Promise { + const {prompt, config} = params; + + this._raiseForInvalidPrompt(prompt); + + const promptMetadata = this._createDatasetMetadataFromPrompt( + prompt, + prompt.promptData.variables, + ); + + const createPromptDatasetOperation = + await this.createDatasetResourceInternal({ + name: `projects/${this.apiClient.clientOptions.project}/locations/${this.apiClient.clientOptions.location}`, + displayName: config?.promptDisplayName || `prompt_${Date.now()}`, + metadataSchemaUri: + 'gs://google-cloud-aiplatform/schema/dataset/metadata/text_prompt_1.0.0.yaml', + metadata: promptMetadata, + modelReference: prompt.promptData.model, + encryptionSpec: config?.encryptionSpec, + }); + + const datasetResourceName = await this._wait_for_operation( + createPromptDatasetOperation, + config?.timeout || 90, + ); + + const datasetId = datasetResourceName.split('/').pop(); + if (!datasetId) { + throw new Error('Invalid dataset resource name.'); + } + + const datasetResource = await this.getDatasetResourceInternal({ + name: datasetId, + }); + + prompt._dataset = datasetResource; + + const createDatasetVersionOperation = + await this.createDatasetVersionResourceInternal({ + datasetName: datasetId, + displayName: + config?.versionDisplayName || `prompt_version_${Date.now()}`, + }); + + const datasetVersionResourceName = await this._wait_for_operation( + createDatasetVersionOperation, + config?.timeout || 90, + ); + + const versionId = datasetVersionResourceName.split('/').pop(); + if (!versionId) { + throw new Error('Invalid dataset version resource name.'); + } + + const datasetVersionResource = await this.getDatasetVersionResourceInternal( + { + datasetId: datasetId, + datasetVersionId: versionId, + }, + ); + + const updatedPrompt = this._createPromptFromDatasetMetadata( + datasetVersionResource, + ); + updatedPrompt._dataset = datasetResource; + updatedPrompt._dataset_version = datasetVersionResource; + + return updatedPrompt; + } + + async get(params: {promptId: string; config?: any}): Promise { + const {promptId} = params; + + const promptDatasetResource = await this.getDatasetResourceInternal({ + name: promptId, + }); + const prompt = this._createPromptFromDatasetMetadata(promptDatasetResource); + prompt._dataset = promptDatasetResource; + + return prompt; + } + + async getVersion(params: { + promptId: string; + versionId: string; + config?: any; + }): Promise { + const {promptId, versionId} = params; + + const promptDatasetResource = await this.getDatasetResourceInternal({ + name: promptId, + }); + const prompt = this._createPromptFromDatasetMetadata(promptDatasetResource); + prompt._dataset = promptDatasetResource; + + const promptVersionResource = await this.getDatasetVersionResourceInternal({ + datasetId: promptId, + datasetVersionId: versionId, + }); + prompt._dataset_version = promptVersionResource; + + return prompt; + } + + async list(params?: {config?: any}): Promise { + const config = params?.config; + const response = await this.listPromptsInternal({config}); + const promptRefs: any[] = []; + + if (response.datasets) { + for (const dataset of response.datasets) { + if (dataset.name) { + promptRefs.push({ + model: dataset.modelReference, + promptId: dataset.name.split('/').pop(), + }); + } + } + } + return promptRefs; + } + + async listVersions(params: {promptId: string; config?: any}): Promise { + const {promptId, config} = params; + const response = await this.listVersionsInternal({ + datasetId: promptId, + config, + }); + const versionRefs: any[] = []; + + if (response.datasetVersions) { + for (const datasetVersion of response.datasetVersions) { + if (datasetVersion.name) { + versionRefs.push({ + model: datasetVersion.modelReference, + versionId: datasetVersion.name.split('/').pop(), + promptId: promptId, + }); + } + } + } + return versionRefs; + } + + private async _wait_for_project_operation( + operation: any, + timeout: number, + ): Promise { + let done = false; + const startTime = Date.now(); + let sleepDuration = 5000; // ms + const waitMultiplier = 2; + const maxWaitTime = 60000; // ms + let previousTime = Date.now(); + + if (!operation.name) { + throw new Error('Invalid operation name.'); + } + + while (!done) { + if (Date.now() - startTime > timeout * 1000) { + throw new Error( + `Delete operation did not complete within the specified timeout of ${timeout} seconds.`, + ); + } + const currentTime = Date.now(); + if (currentTime - previousTime >= sleepDuration) { + sleepDuration = Math.min(sleepDuration * waitMultiplier, maxWaitTime); + previousTime = currentTime; + } + await new Promise((resolve) => setTimeout(resolve, sleepDuration)); + + const response = await this.apiClient.request({ + path: operation.name, + httpMethod: 'GET', + }); + const opStatus = (await response.json()) as any; + done = opStatus.done || false; + + if (opStatus.error) { + throw new Error( + `Error in delete operation: ${JSON.stringify(opStatus.error)}`, + ); + } + } + } + + async delete(params: {promptId: string; config?: any}): Promise { + const {promptId, config} = params; + + const deletePromptOperation = await this.deleteDatasetInternal({ + promptId: promptId, + config: config, + }); + + await this._wait_for_project_operation( + deletePromptOperation, + config?.timeout || 90, + ); + } + + async deleteVersion(params: { + promptId: string; + versionId: string; + config?: any; + }): Promise { + const {promptId, versionId, config} = params; + + const deleteVersionOperation = await this.deleteDatasetVersionInternal({ + promptId: promptId, + versionId: versionId, + config: config, + }); + + await this._wait_for_project_operation( + deleteVersionOperation, + config?.timeout || 90, + ); + } + + async restoreVersion(params: { + promptId: string; + versionId: string; + config?: any; + }): Promise { + const {promptId, versionId} = params; + + const restorePromptOperation = await this.restoreVersionInternal({ + datasetId: promptId, + versionId: versionId, + }); + + await this._wait_for_project_operation(restorePromptOperation, 90); + + const datasetVersionResource = await this.getDatasetVersionResourceInternal( + { + datasetId: promptId, + datasetVersionId: versionId, + }, + ); + + const updatedPrompt = this._createPromptFromDatasetMetadata( + datasetVersionResource, + ); + updatedPrompt._dataset_version = datasetVersionResource; + return updatedPrompt; + } + + async update(params: { + promptId: string; + prompt: any; + config?: any; + }): Promise { + const {promptId, prompt, config} = params; + + this._raiseForInvalidPrompt(prompt); + + const promptMetadata = this._createDatasetMetadataFromPrompt( + prompt, + prompt.promptData.variables, + ); + + if (!prompt.promptData) { + throw new Error('Prompt data is required to update a prompt.'); + } + + const updatedDatasetResource = await this.updateDatasetResourceInternal({ + name: `projects/${this.apiClient.clientOptions.project}/locations/${this.apiClient.clientOptions.location}`, + datasetId: promptId, + displayName: config?.promptDisplayName, + metadata: promptMetadata, + modelReference: prompt.promptData.model, + encryptionSpec: config?.encryptionSpec, + config: config, + }); + + const datasetId = updatedDatasetResource.name?.split('/').pop(); + if (!datasetId) { + throw new Error('Failed to update dataset resource or get dataset ID.'); + } + + const createDatasetVersionOperation = + await this.createDatasetVersionResourceInternal({ + datasetName: datasetId, + displayName: + config?.versionDisplayName || `prompt_version_${Date.now()}`, + }); + + const datasetVersionResourceName = await this._wait_for_operation( + createDatasetVersionOperation, + config?.timeout || 90, + ); + + const versionId = datasetVersionResourceName.split('/').pop(); + + const datasetVersionResource = await this.getDatasetVersionResourceInternal( + { + datasetId: datasetId, + datasetVersionId: versionId, + }, + ); + + const updatedPrompt = this._createPromptFromDatasetMetadata( + datasetVersionResource, + ); + updatedPrompt._dataset = updatedDatasetResource; + updatedPrompt._dataset_version = datasetVersionResource; + + return updatedPrompt; + } + + private async createDatasetResourceInternal( + params: types.CreateDatasetParameters, + ): Promise { + let response: Promise; + + let path: string = ''; + let queryParams: Record = {}; + if (this.apiClient.isVertexAI()) { + const body = converters.createDatasetParametersToVertex(params); + path = common.formatMap( + 'datasets', + body['_url'] as Record, + ); + queryParams = body['_query'] as Record; + delete body['_url']; + delete body['_query']; + delete body['config']; + + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, + }) + .then((httpResponse) => { + return httpResponse.json(); + }) as Promise; + + return response.then((resp) => { + return resp as types.DatasetOperation; + }); + } else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + + private async createDatasetVersionResourceInternal( + params: types.CreateDatasetVersionParameters, + ): Promise { + let response: Promise; + + let path: string = ''; + let queryParams: Record = {}; + if (this.apiClient.isVertexAI()) { + const body = converters.createDatasetVersionParametersToVertex(params); + path = common.formatMap( + 'datasets/{name}/datasetVersions', + body['_url'] as Record, + ); + queryParams = body['_query'] as Record; + delete body['_url']; + delete body['_query']; + delete body['config']; + + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'POST', + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, + }) + .then((httpResponse) => { + return httpResponse.json(); + }) as Promise; + + return response.then((resp) => { + return resp as types.DatasetOperation; + }); + } else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + + private async getDatasetResourceInternal( + params: types.GetDatasetParameters, + ): Promise { + let response: Promise; + + let path: string = ''; + let queryParams: Record = {}; + if (this.apiClient.isVertexAI()) { + const body = converters.getDatasetParametersToVertex(params); + path = common.formatMap( + 'datasets/{name}', + body['_url'] as Record, + ); + queryParams = body['_query'] as Record; + delete body['_url']; + delete body['_query']; + delete body['config']; + + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, + }) + .then((httpResponse) => { + return httpResponse.json(); + }) as Promise; + + return response.then((resp) => { + return resp as types.Dataset; + }); + } else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + + private async getDatasetVersionResourceInternal( + params: types.GetDatasetVersionParameters, + ): Promise { + let response: Promise; + + let path: string = ''; + let queryParams: Record = {}; + if (this.apiClient.isVertexAI()) { + const body = converters.getDatasetVersionParametersToVertex(params); + path = common.formatMap( + 'datasets/{dataset_id}/datasetVersions/{dataset_version_id}', + body['_url'] as Record, + ); + queryParams = body['_query'] as Record; + delete body['_url']; + delete body['_query']; + delete body['config']; + + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, + }) + .then((httpResponse) => { + return httpResponse.json(); + }) as Promise; + + return response.then((resp) => { + return resp as types.DatasetVersion; + }); + } else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + + private async getDatasetOperationInternal( + params: types.GetDatasetOperationParameters, + ): Promise { + let response: Promise; + + let path: string = ''; + let queryParams: Record = {}; + if (this.apiClient.isVertexAI()) { + const body = converters.getDatasetOperationParametersToVertex(params); + path = common.formatMap( + 'datasets/{dataset_id}/operations/{operation_id}', + body['_url'] as Record, + ); + queryParams = body['_query'] as Record; + delete body['_url']; + delete body['_query']; + delete body['config']; + + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, + }) + .then((httpResponse) => { + return httpResponse.json(); + }) as Promise; + + return response.then((resp) => { + return resp as types.DatasetOperation; + }); + } else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + + private async listPromptsInternal( + params: types.ListDatasetsRequestParameters, + ): Promise { + let response: Promise; + + let path: string = ''; + let queryParams: Record = {}; + if (this.apiClient.isVertexAI()) { + const body = converters.listDatasetsRequestParametersToVertex(params); + path = common.formatMap( + 'datasets', + body['_url'] as Record, + ); + queryParams = body['_query'] as Record; + delete body['_url']; + delete body['_query']; + delete body['config']; + + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, + }) + .then((httpResponse) => { + return httpResponse.json(); + }) as Promise; + + return response.then((resp) => { + const typedResp = new types.ListDatasetsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + + private async listVersionsInternal( + params: types.ListDatasetVersionsRequestParameters, + ): Promise { + let response: Promise; + + let path: string = ''; + let queryParams: Record = {}; + if (this.apiClient.isVertexAI()) { + const body = + converters.listDatasetVersionsRequestParametersToVertex(params); + path = common.formatMap( + 'datasets/{dataset_id}/datasetVersions', + body['_url'] as Record, + ); + queryParams = body['_query'] as Record; + delete body['_url']; + delete body['_query']; + delete body['config']; + + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, + }) + .then((httpResponse) => { + return httpResponse.json(); + }) as Promise; + + return response.then((resp) => { + const typedResp = new types.ListDatasetVersionsResponse(); + Object.assign(typedResp, resp); + return typedResp; + }); + } else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + + private async deleteDatasetInternal( + params: types.DeleteDatasetRequestParameters, + ): Promise { + let response: Promise; + + let path: string = ''; + let queryParams: Record = {}; + if (this.apiClient.isVertexAI()) { + const body = converters.deleteDatasetRequestParametersToVertex(params); + path = common.formatMap( + 'datasets/{dataset_id}', + body['_url'] as Record, + ); + queryParams = body['_query'] as Record; + delete body['_url']; + delete body['_query']; + delete body['config']; + + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, + }) + .then((httpResponse) => { + return httpResponse.json(); + }) as Promise; + + return response.then((resp) => { + return resp as types.DeletePromptOperation; + }); + } else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + + private async deleteDatasetVersionInternal( + params: types.DeletePromptVersionRequestParameters, + ): Promise { + let response: Promise; + + let path: string = ''; + let queryParams: Record = {}; + if (this.apiClient.isVertexAI()) { + const body = + converters.deletePromptVersionRequestParametersToVertex(params); + path = common.formatMap( + 'datasets/{dataset_id}/datasetVersions/{version_id}', + body['_url'] as Record, + ); + queryParams = body['_query'] as Record; + delete body['_url']; + delete body['_query']; + delete body['config']; + + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'DELETE', + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, + }) + .then((httpResponse) => { + return httpResponse.json(); + }) as Promise; + + return response.then((resp) => { + return resp as types.DeletePromptVersionOperation; + }); + } else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + + private async restoreVersionInternal( + params: types.RestoreVersionRequestParameters, + ): Promise { + let response: Promise; + + let path: string = ''; + let queryParams: Record = {}; + if (this.apiClient.isVertexAI()) { + const body = converters.restoreVersionRequestParametersToVertex(params); + path = common.formatMap( + 'datasets/{dataset_id}/datasetVersions/{version_id}:restore', + body['_url'] as Record, + ); + queryParams = body['_query'] as Record; + delete body['_url']; + delete body['_query']; + delete body['config']; + + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'GET', + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, + }) + .then((httpResponse) => { + return httpResponse.json(); + }) as Promise; + + return response.then((resp) => { + return resp as types.RestoreVersionOperation; + }); + } else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } + + private async updateDatasetResourceInternal( + params: types.UpdateDatasetParameters, + ): Promise { + let response: Promise; + + let path: string = ''; + let queryParams: Record = {}; + if (this.apiClient.isVertexAI()) { + const body = converters.updateDatasetParametersToVertex(params); + path = common.formatMap( + 'datasets/{dataset_id}', + body['_url'] as Record, + ); + queryParams = body['_query'] as Record; + delete body['_url']; + delete body['_query']; + delete body['config']; + + response = this.apiClient + .request({ + path: path, + queryParams: queryParams, + body: JSON.stringify(body), + httpMethod: 'PATCH', + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, + }) + .then((httpResponse) => { + return httpResponse.json(); + }) as Promise; + + return response.then((resp) => { + return resp as types.Dataset; + }); + } else { + throw new Error('This method is only supported by the Vertex AI.'); + } + } +} diff --git a/src/genai/sandboxes.ts b/src/genai/sandboxes.ts index 93b47515..99d93fa0 100644 --- a/src/genai/sandboxes.ts +++ b/src/genai/sandboxes.ts @@ -6,6 +6,7 @@ // Code generated by the Google Gen AI SDK generator DO NOT EDIT. +import * as genaiTypes from '@google/genai'; import * as common from '@google/genai/vertex_internal'; import {ApiClient, BaseModule} from '@google/genai/vertex_internal'; import * as converters from './converters/_sandboxes_converters.js'; @@ -41,8 +42,12 @@ export class Sandboxes extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -81,8 +86,12 @@ export class Sandboxes extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'DELETE', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -123,8 +132,12 @@ export class Sandboxes extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -165,8 +178,12 @@ export class Sandboxes extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -205,8 +222,12 @@ export class Sandboxes extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -247,8 +268,12 @@ export class Sandboxes extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); diff --git a/src/genai/sessionevents.ts b/src/genai/sessionevents.ts index 61eec857..96f476fa 100644 --- a/src/genai/sessionevents.ts +++ b/src/genai/sessionevents.ts @@ -6,6 +6,7 @@ // Code generated by the Google Gen AI SDK generator DO NOT EDIT. +import * as genaiTypes from '@google/genai'; import * as common from '@google/genai/vertex_internal'; import {ApiClient, BaseModule} from '@google/genai/vertex_internal'; import * as converters from './converters/_sessionevents_converters.js'; @@ -43,8 +44,12 @@ export class SessionEvents extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -87,8 +92,12 @@ export class SessionEvents extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); diff --git a/src/genai/sessions.ts b/src/genai/sessions.ts index b2401811..3c474fe4 100644 --- a/src/genai/sessions.ts +++ b/src/genai/sessions.ts @@ -6,6 +6,7 @@ // Code generated by the Google Gen AI SDK generator DO NOT EDIT. +import * as genaiTypes from '@google/genai'; import * as common from '@google/genai/vertex_internal'; import {ApiClient, BaseModule} from '@google/genai/vertex_internal'; import * as converters from './converters/_sessions_converters.js'; @@ -45,8 +46,12 @@ export class Sessions extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'POST', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -85,8 +90,12 @@ export class Sessions extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'DELETE', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -125,8 +134,12 @@ export class Sessions extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -165,8 +178,12 @@ export class Sessions extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -207,8 +224,12 @@ export class Sessions extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'GET', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); @@ -247,8 +268,12 @@ export class Sessions extends BaseModule { queryParams: queryParams, body: JSON.stringify(body), httpMethod: 'PATCH', - httpOptions: params.config?.httpOptions, - abortSignal: params.config?.abortSignal, + httpOptions: params.config?.['httpOptions'] as + | genaiTypes.HttpOptions + | undefined, + abortSignal: params.config?.['abortSignal'] as + | AbortSignal + | undefined, }) .then((httpResponse) => { return httpResponse.json(); diff --git a/src/genai/types.ts b/src/genai/types.ts index 81884d33..77fdae09 100644 --- a/src/genai/types.ts +++ b/src/genai/types.ts @@ -7,3 +7,4 @@ // Code generated by the Google Gen AI SDK generator DO NOT EDIT. export * from './types/common.js'; +export * as promptsTypes from './types/prompts.js'; diff --git a/src/genai/types/common.ts b/src/genai/types/common.ts index 8d1e13f4..398bbb62 100644 --- a/src/genai/types/common.ts +++ b/src/genai/types/common.ts @@ -6,6 +6,7 @@ // Code generated by the Google Gen AI SDK generator DO NOT EDIT. +// eslint-disable-next-line @typescript-eslint/no-unused-vars import * as genaiTypes from '@google/genai'; /** The identity type to use for the Reasoning Engine. If not specified, the `service_account` field will be used if set, otherwise the default Vertex AI Reasoning Engine Service Agent in the project will be used. */ @@ -212,6 +213,18 @@ export enum GenerateMemoriesResponseGeneratedMemoryAction { DELETED = 'DELETED', } +/** The method for data driven prompt optimization. */ +export enum OptimizationMethod { + /** + * The default data driven Vertex AI Prompt Optimizer. + */ + VAPO = 'VAPO', + /** + * The data driven prompt optimizer designer for prompts from Android core API. + */ + OPTIMIZATION_TARGET_GEMINI_NANO = 'OPTIMIZATION_TARGET_GEMINI_NANO', +} + /** Represents an environment variable present in a Container or Python Module. */ export declare interface EnvVar { /** Required. Name of the environment variable. Must be a valid C identifier. */ @@ -2461,6 +2474,586 @@ export class ListAgentEngineSessionEventsResponse { sessionEvents?: SessionEvent[]; } +/** Single source entry for the grounding checking. */ +export declare interface SchemaPredictParamsGroundingConfigSourceEntry { + /** The uri of the Vertex AI Search data source. Deprecated. Use vertex_ai_search_datastore instead. */ + enterpriseDatastore?: string; + /** The grounding text passed inline with the Predict API. It can support up to 1 million bytes. */ + inlineContext?: string; + /** The type of the grounding checking source. */ + type?: 'UNSPECIFIED' | 'WEB' | 'ENTERPRISE' | 'VERTEX_AI_SEARCH' | 'INLINE'; + /** The uri of the Vertex AI Search data source. */ + vertexAiSearchDatastore?: string; +} + +/** The configuration for grounding checking. */ +export declare interface SchemaPredictParamsGroundingConfig { + /** If set, skip finding claim attributions (i.e not generate grounding citation). */ + disableAttribution?: boolean; + /** The sources for the grounding checking. */ + sources?: SchemaPredictParamsGroundingConfigSourceEntry[]; +} + +/** A prompt instance's parameters set that contains a set of variable values. */ +export declare interface SchemaPromptInstancePromptExecution { + /** Maps variable names to their value. */ + arguments?: Record; +} + +/** Represents a prompt message. */ +export declare interface SchemaPromptSpecPromptMessage { + /** Generation config. */ + generationConfig?: genaiTypes.GenerationConfig; + /** Tool config. This config is shared for all tools provided in the request. */ + toolConfig?: genaiTypes.FunctionCallingConfig; + /** A list of `Tools` the model may use to generate the next response. A `Tool` 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. */ + tools?: genaiTypes.Tool[]; + /** Per request settings for blocking unsafe content. Enforced on GenerateContentResponse.candidates. */ + safetySettings?: genaiTypes.SafetySetting[]; + /** The content of the current conversation with the model. For single-turn queries, this is a single instance. For multi-turn queries, this is a repeated field that contains conversation history + latest request. */ + contents?: genaiTypes.Content[]; + /** The user provided system instructions for the model. Note: only text should be used in parts and content in each part will be in a separate paragraph. */ + systemInstruction?: genaiTypes.Content; + variables?: Record[]; + /** The model name. */ + model?: string; +} + +/** Prompt variation that embeds preambles to prompt string. */ +export declare interface SchemaPromptSpecMultimodalPrompt { + /** The prompt message. */ + promptMessage?: SchemaPromptSpecPromptMessage; +} + +/** A linked resource attached to the application by the user. */ +export declare interface SchemaPromptSpecAppBuilderDataLinkedResource { + /** A user-friendly name for the data source shown in the UI. */ + displayName?: string; + /** The unique resource name of the data source. The format is determined by the 'type' field. For type "SAVED_PROMPT": projects/{project}/locations/{location}/datasets/{dataset} For type "AI_AGENT": projects/{project}/locations/{location}/agents/{agent} */ + name?: string; + /** The type of the linked resource. e.g., "SAVED_PROMPT", "AI_AGENT" This string corresponds to the name of the LinkedResourceType enum member. See: google3/cloud/console/web/ai/platform/llm/prompts/build/services/specs_repository_service/linked_resources/linked_resource.ts */ + type?: string; +} + +/** Defines data for an application builder. */ +export declare interface SchemaPromptSpecAppBuilderData { + /** Serialized state of the code repository. This string will typically contain a JSON representation of the UI's CodeRepositoryService state (files, folders, content, and any metadata). The UI is responsible for serialization and deserialization. */ + codeRepositoryState?: string; + /** Optional. Framework used to build the application. */ + framework?: Framework; + /** Linked resources attached to the application by the user. */ + linkedResources?: SchemaPromptSpecAppBuilderDataLinkedResource[]; +} + +/** Represents a prompt spec part list. */ +export declare interface SchemaPromptSpecPartList { + /** A list of elements that can be part of a prompt. */ + parts?: genaiTypes.Part[]; +} + +/** Represents a structured prompt. */ +export declare interface SchemaPromptSpecStructuredPrompt { + /** Preamble: The context of the prompt. */ + context?: genaiTypes.Content; + /** Data for app builder use case. */ + appBuilderData?: SchemaPromptSpecAppBuilderData; + /** Preamble: A set of examples for expected model response. */ + examples?: SchemaPromptSpecPartList[]; + /** Preamble: For infill prompt, the prefix before expected model response. */ + infillPrefix?: string; + /** Preamble: For infill prompt, the suffix after expected model response. */ + infillSuffix?: string; + /** Preamble: The input prefixes before each example input. */ + inputPrefixes?: string[]; + /** Preamble: The output prefixes before each example output. */ + outputPrefixes?: string[]; + /** Preamble: The input test data for prediction. Each PartList in this field represents one text-only input set for a single model request. */ + predictionInputs?: SchemaPromptSpecPartList[]; + /** The prompt message. */ + promptMessage?: SchemaPromptSpecPromptMessage; +} + +/** A pair of sentences used as reference in source and target languages. */ +export declare interface SchemaPromptSpecReferenceSentencePair { + /** Source sentence in the sentence pair. */ + sourceSentence?: string; + /** Target sentence in the sentence pair. */ + targetSentence?: string; +} + +/** A list of reference sentence pairs. */ +export declare interface SchemaPromptSpecReferenceSentencePairList { + /** Reference sentence pairs. */ + referenceSentencePairs?: SchemaPromptSpecReferenceSentencePair[]; +} + +export declare interface SchemaPromptSpecTranslationFileInputSource { + /** The file's contents. */ + content?: string; + /** The file's display name. */ + displayName?: string; + /** The file's mime type. */ + mimeType?: string; +} + +export declare interface SchemaPromptSpecTranslationGcsInputSource { + /** Source data URI. For example, `gs://my_bucket/my_object`. */ + inputUri?: string; +} + +export declare interface SchemaPromptSpecTranslationSentenceFileInput { + /** Inlined file source. */ + fileInputSource?: SchemaPromptSpecTranslationFileInputSource; + /** Cloud Storage file source. */ + gcsInputSource?: SchemaPromptSpecTranslationGcsInputSource; +} + +/** The translation example that contains reference sentences from various sources. */ +export declare interface SchemaPromptSpecTranslationExample { + /** The reference sentences from inline text. */ + referenceSentencePairLists?: SchemaPromptSpecReferenceSentencePairList[]; + /** The reference sentences from file. */ + referenceSentencesFileInputs?: SchemaPromptSpecTranslationSentenceFileInput[]; +} + +/** Optional settings for translation prompt. */ +export declare interface SchemaPromptSpecTranslationOption { + /** How many shots to use. */ + numberOfShots?: number; +} + +/** Prompt variation for Translation use case. */ +export declare interface SchemaPromptSpecTranslationPrompt { + /** The translation example. */ + example?: SchemaPromptSpecTranslationExample; + /** The translation option. */ + option?: SchemaPromptSpecTranslationOption; + /** The prompt message. */ + promptMessage?: SchemaPromptSpecPromptMessage; + /** The source language code. */ + sourceLanguageCode?: string; + /** The target language code. */ + targetLanguageCode?: string; +} + +/** The A2 schema of a prompt. */ +export declare interface SchemaPromptApiSchema { + /** The Schema version that represents changes to the API behavior. */ + apiSchemaVersion?: string; + /** A list of execution instances for constructing a ready-to-use prompt. */ + executions?: SchemaPromptInstancePromptExecution[]; + /** Multimodal prompt which embeds preambles to prompt string. */ + multimodalPrompt?: SchemaPromptSpecMultimodalPrompt; + /** The prompt variation that stores preambles in separate fields. */ + structuredPrompt?: SchemaPromptSpecStructuredPrompt; + /** The prompt variation for Translation use case. */ + translationPrompt?: SchemaPromptSpecTranslationPrompt; +} + +/** Represents the text prompt dataset metadata. */ +export declare interface SchemaTextPromptDatasetMetadata { + /** Number of candidates. */ + candidateCount?: string; + /** The Google Cloud Storage URI that stores the prompt data. */ + gcsUri?: string; + /** Grounding checking configuration. */ + groundingConfig?: SchemaPredictParamsGroundingConfig; + /** Whether the prompt dataset has prompt variable. */ + hasPromptVariable?: boolean; + /** Whether or not the user has enabled logit probabilities in the model parameters. */ + logprobs?: boolean; + /** Value of the maximum number of tokens generated set when the dataset was saved. */ + maxOutputTokens?: string; + /** User-created prompt note. Note size limit is 2KB. */ + note?: string; + /** The API schema of the prompt to support both UI and SDK usages. */ + promptApiSchema?: SchemaPromptApiSchema; + /** Type of the prompt dataset. */ + promptType?: string; + /** Seeding enables model to return a deterministic response on a best effort basis. Determinism isn't guaranteed. This field determines whether or not seeding is enabled. */ + seedEnabled?: boolean; + /** The actual value of the seed. */ + seedValue?: string; + /** Customized stop sequences. */ + stopSequences?: string[]; + /** The content of the prompt dataset system instruction. */ + systemInstruction?: string; + /** The Google Cloud Storage URI that stores the system instruction, starting with gs://. */ + systemInstructionGcsUri?: string; + /** Temperature value used for sampling set when the dataset was saved. This value is used to tune the degree of randomness. */ + temperature?: number; + /** The content of the prompt dataset. */ + text?: string; + /** Top K value set when the dataset was saved. This value determines how many candidates with highest probability from the vocab would be selected for each decoding step. */ + topK?: string; + /** Top P value set when the dataset was saved. Given topK tokens for decoding, top candidates will be selected until the sum of their probabilities is topP. */ + topP?: number; +} + +/** Config for creating a dataset resource to store prompts. */ +export declare interface CreateDatasetConfig { + /** Used to override HTTP request options. */ + httpOptions?: genaiTypes.HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for creating a dataset resource to store prompts. */ +export declare interface CreateDatasetParameters { + name?: string; + displayName?: string; + metadataSchemaUri?: string; + metadata?: SchemaTextPromptDatasetMetadata; + description?: string; + encryptionSpec?: genaiTypes.EncryptionSpec; + modelReference?: string; + config?: CreateDatasetConfig; +} + +/** Represents the create dataset operation. */ +export declare interface DatasetOperation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; + /** The result of the dataset operation. */ + response?: Record; +} + +/** Base configuration for Vertex AI. */ +export type VertexBaseConfig = Record; +/** Union of parsed responses. */ +export type ParsedResponseUnion = unknown; +/** Prompt data structure. */ +export type PromptData = Record; + +/** Config for creating a dataset version resource to store prompts. */ +export declare interface CreateDatasetVersionConfig { + /** Used to override HTTP request options. */ + httpOptions?: genaiTypes.HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Represents the create dataset version parameters. */ +export declare interface CreateDatasetVersionParameters { + datasetName?: string; + metadata?: SchemaTextPromptDatasetMetadata; + modelReference?: string; + parent?: string; + displayName?: string; + config?: CreateDatasetVersionConfig; +} + +/** Parameters for getting a dataset resource to store prompts. */ +export declare interface GetDatasetParameters { + name?: string; + config?: VertexBaseConfig; +} + +/** A SavedQuery is a view of the dataset. It references a subset of annotations by problem type and filters. */ +export declare interface SavedQuery { + /** Output only. Filters on the Annotations in the dataset. */ + annotationFilter?: string; + /** Output only. Number of AnnotationSpecs in the context of the SavedQuery. */ + annotationSpecCount?: number; + /** Output only. Timestamp when this SavedQuery was created. */ + createTime?: string; + /** Required. The user-defined name of the SavedQuery. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + displayName?: string; + /** Used to perform a consistent read-modify-write update. If not set, a blind "overwrite" update happens. */ + etag?: string; + /** Some additional information about the SavedQuery. */ + metadata?: unknown; + /** Output only. Resource name of the SavedQuery. */ + name?: string; + /** Required. Problem type of the SavedQuery. Allowed values: * IMAGE_CLASSIFICATION_SINGLE_LABEL * IMAGE_CLASSIFICATION_MULTI_LABEL * IMAGE_BOUNDING_POLY * IMAGE_BOUNDING_BOX * TEXT_CLASSIFICATION_SINGLE_LABEL * TEXT_CLASSIFICATION_MULTI_LABEL * TEXT_EXTRACTION * TEXT_SENTIMENT * VIDEO_CLASSIFICATION * VIDEO_OBJECT_TRACKING */ + problemType?: string; + /** Output only. If the Annotations belonging to the SavedQuery can be used for AutoML training. */ + supportAutomlTraining?: boolean; + /** Output only. Timestamp when SavedQuery was last updated. */ + updateTime?: string; +} + +/** Represents a dataset resource to store prompts. */ +export declare interface Dataset { + /** Required. Additional information about the Dataset. */ + metadata?: SchemaTextPromptDatasetMetadata; + /** Customer-managed encryption key spec for a Dataset. If set, this Dataset and all sub-resources of this Dataset will be secured by this key. */ + encryptionSpec?: genaiTypes.EncryptionSpec; + /** Output only. Timestamp when this Dataset was created. */ + createTime?: string; + /** Output only. The number of DataItems in this Dataset. Only apply for non-structured Dataset. */ + dataItemCount?: string; + /** The description of the Dataset. */ + description?: string; + /** Required. The user-defined name of the Dataset. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + displayName?: string; + /** Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens. */ + etag?: string; + /** The labels with user-defined metadata to organize your Datasets. Label keys and values can be no longer than 64 characters (Unicode codepoints), can only contain lowercase letters, numeric characters, underscores and dashes. International characters are allowed. No more than 64 user labels can be associated with one Dataset (System labels are excluded). See https://goo.gl/xmQnxf for more information and examples of labels. System reserved label keys are prefixed with "aiplatform.googleapis.com/" and are immutable. Following system labels exist for each Dataset: * "aiplatform.googleapis.com/dataset_metadata_schema": output only, its value is the metadata_schema's title. */ + labels?: Record; + /** Output only. The resource name of the Artifact that was created in MetadataStore when creating the Dataset. The Artifact resource name pattern is `projects/{project}/locations/{location}/metadataStores/{metadata_store}/artifacts/{artifact}`. */ + metadataArtifact?: string; + /** Required. Points to a YAML file stored on Google Cloud Storage describing additional information about the Dataset. The schema is defined as an OpenAPI 3.0.2 Schema Object. The schema files that can be used here are found in gs://google-cloud-aiplatform/schema/dataset/metadata/. */ + metadataSchemaUri?: string; + /** Optional. Reference to the public base model last used by the dataset. Only set for prompt datasets. */ + modelReference?: string; + /** Output only. Identifier. The resource name of the Dataset. Format: `projects/{project}/locations/{location}/datasets/{dataset}` */ + name?: string; + /** Output only. Reserved for future use. */ + satisfiesPzi?: boolean; + /** Output only. Reserved for future use. */ + satisfiesPzs?: boolean; + /** All SavedQueries belong to the Dataset will be returned in List/Get Dataset response. The annotation_specs field will not be populated except for UI cases which will only use annotation_spec_count. In CreateDataset request, a SavedQuery is created together if this field is set, up to one SavedQuery can be set in CreateDatasetRequest. The SavedQuery should not contain any AnnotationSpec. */ + savedQueries?: SavedQuery[]; + /** Output only. Timestamp when this Dataset was last updated. */ + updateTime?: string; +} + +/** Parameters for getting a dataset resource to store prompts. */ +export declare interface GetDatasetVersionParameters { + datasetId?: string; + datasetVersionId?: string; + config?: VertexBaseConfig; +} + +/** Represents a dataset version resource to store prompts. */ +export declare interface DatasetVersion { + /** Required. Output only. Additional information about the DatasetVersion. */ + metadata?: SchemaTextPromptDatasetMetadata; + /** Output only. Name of the associated BigQuery dataset. */ + bigQueryDatasetName?: string; + /** Output only. Timestamp when this DatasetVersion was created. */ + createTime?: string; + /** The user-defined name of the DatasetVersion. The name can be up to 128 characters long and can consist of any UTF-8 characters. */ + displayName?: string; + /** Used to perform consistent read-modify-write updates. If not set, a blind "overwrite" update happens. */ + etag?: string; + /** Output only. Reference to the public base model last used by the dataset version. Only set for prompt dataset versions. */ + modelReference?: string; + /** Output only. Identifier. The resource name of the DatasetVersion. Format: `projects/{project}/locations/{location}/datasets/{dataset}/datasetVersions/{dataset_version}` */ + name?: string; + /** Output only. Reserved for future use. */ + satisfiesPzi?: boolean; + /** Output only. Reserved for future use. */ + satisfiesPzs?: boolean; + /** Output only. Timestamp when this DatasetVersion was last updated. */ + updateTime?: string; +} + +/** Config for getting a dataset version operation. */ +export declare interface GetDatasetOperationConfig { + /** Used to override HTTP request options. */ + httpOptions?: genaiTypes.HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for getting a dataset operation. */ +export declare interface GetDatasetOperationParameters { + datasetId?: string; + operationId?: string; + config?: GetDatasetOperationConfig; +} + +/** Config for listing prompt datasets and dataset versions. */ +export declare interface ListPromptsConfig { + /** Used to override HTTP request options. */ + httpOptions?: genaiTypes.HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + pageSize?: number; + pageToken?: string; + /** An expression for filtering the results of the request. + For field names both snake_case and camelCase are supported. */ + filter?: string; +} + +/** Parameters for listing prompt datasets. */ +export declare interface ListDatasetsRequestParameters { + config?: ListPromptsConfig; +} + +/** Response for listing prompt datasets. */ +export class ListDatasetsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: genaiTypes.HttpResponse; + nextPageToken?: string; + /** List of datasets for the project. + */ + datasets?: Dataset[]; +} + +/** Parameters for listing dataset versions. */ +export declare interface ListDatasetVersionsRequestParameters { + readMask?: string; + datasetId?: string; + config?: ListPromptsConfig; +} + +/** Response for listing prompt datasets. */ +export class ListDatasetVersionsResponse { + /** Used to retain the full HTTP response. */ + sdkHttpResponse?: genaiTypes.HttpResponse; + nextPageToken?: string; + /** List of datasets for the project. + */ + datasetVersions?: DatasetVersion[]; +} + +/** Config for deleting a prompt. */ +export declare interface DeletePromptConfig { + /** Used to override HTTP request options. */ + httpOptions?: genaiTypes.HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** Timeout for the delete prompt operation in seconds. Defaults to 90. */ + timeout?: number; +} + +/** Parameters for deleting a prompt dataset. */ +export declare interface DeleteDatasetRequestParameters { + /** ID of the prompt dataset to be deleted. */ + promptId: string; + config?: DeletePromptConfig; +} + +/** Operation for deleting prompts. */ +export declare interface DeletePromptOperation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; +} + +/** Parameters for deleting a prompt version. */ +export declare interface DeletePromptVersionRequestParameters { + /** ID of the prompt to be deleted. */ + promptId: string; + /** ID of the prompt version to be deleted within the provided prompt_id. */ + versionId: string; + config?: DeletePromptConfig; +} + +/** Operation for deleting prompt versions. */ +export declare interface DeletePromptVersionOperation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; +} + +/** Config for restoring a prompt version. */ +export declare interface RestoreVersionConfig { + /** Used to override HTTP request options. */ + httpOptions?: genaiTypes.HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Parameters for restoring a prompt version. */ +export declare interface RestoreVersionRequestParameters { + /** ID of the prompt dataset to be restored. */ + datasetId: string; + /** ID of the prompt dataset version to be restored. */ + versionId: string; + config?: RestoreVersionConfig; +} + +/** Represents the restore version operation. */ +export declare interface RestoreVersionOperation { + /** The server-assigned name, which is only unique within the same service that originally returns it. If you use the default HTTP mapping, the `name` should be a resource name ending with `operations/{unique_id}`. */ + name?: string; + /** Service-specific metadata associated with the operation. It typically contains progress information and common metadata such as create time. Some services might not provide such metadata. Any method that returns a long-running operation should document the metadata type, if any. */ + metadata?: Record; + /** If the value is `false`, it means the operation is still in progress. If `true`, the operation is completed, and either `error` or `response` is available. */ + done?: boolean; + /** The error result of the operation in case of failure or cancellation. */ + error?: Record; +} + +/** Config for creating a dataset resource to store prompts. */ +export declare interface UpdatePromptConfig { + /** Used to override HTTP request options. */ + httpOptions?: genaiTypes.HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The updated display name for the prompt. */ + promptDisplayName?: string; + /** The updated display name for the prompt version. If not set, a default name with a timestamp will be used. */ + versionDisplayName?: string; + /** The timeout for the update_dataset_resource request in seconds. If not set, the default timeout is 90 seconds. */ + timeout?: number; + /** Customer-managed encryption key spec for a prompt dataset. If set, this prompt dataset and all sub-resources of this prompt dataset will be secured by this key. */ + encryptionSpec?: genaiTypes.EncryptionSpec; +} + +/** Parameters for creating a dataset resource to store prompts. */ +export declare interface UpdateDatasetParameters { + name?: string; + datasetId?: string; + displayName?: string; + metadata?: SchemaTextPromptDatasetMetadata; + description?: string; + encryptionSpec?: genaiTypes.EncryptionSpec; + modelReference?: string; + config?: UpdatePromptConfig; +} + +/** Response for the optimize_prompt method. */ +export class OptimizeResponse { + rawTextResponse?: string; + parsedResponse?: ParsedResponseUnion; +} + /** An agent engine instance. */ export declare interface AgentEngine { /** The underlying API client. */ @@ -2744,22 +3337,95 @@ export class CheckQueryJobResponse { outputGcsUri?: string; } -/** A linked resource attached to the application by the user. */ -export declare interface SchemaPromptSpecAppBuilderDataLinkedResource { - /** A user-friendly name for the data source shown in the UI. */ - displayName?: string; - /** The unique resource name of the data source. The format is determined by the 'type' field. For type "SAVED_PROMPT": projects/{project}/locations/{location}/datasets/{dataset} For type "AI_AGENT": projects/{project}/locations/{location}/agents/{agent} */ - name?: string; - /** The type of the linked resource. e.g., "SAVED_PROMPT", "AI_AGENT" This string corresponds to the name of the LinkedResourceType enum member. See: google3/cloud/console/web/ai/platform/llm/prompts/build/services/specs_repository_service/linked_resources/linked_resource.ts */ - type?: string; +/** Represents a prompt. */ +export declare interface Prompt { + promptData?: PromptData; } -/** Defines data for an application builder. */ -export declare interface SchemaPromptSpecAppBuilderData { - /** Serialized state of the code repository. This string will typically contain a JSON representation of the UI's CodeRepositoryService state (files, folders, content, and any metadata). The UI is responsible for serialization and deserialization. */ - codeRepositoryState?: string; - /** Optional. Framework used to build the application. */ - framework?: Framework; - /** Linked resources attached to the application by the user. */ - linkedResources?: SchemaPromptSpecAppBuilderDataLinkedResource[]; +/** Represents a prompt instance variable. */ +export declare interface SchemaPromptInstanceVariableValue { + /** The parts of the variable value. */ + partList?: SchemaPromptSpecPartList; +} + +/** Config for creating a prompt. */ +export declare interface CreatePromptConfig { + /** Used to override HTTP request options. */ + httpOptions?: genaiTypes.HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The display name for the prompt. If not set, a default name with a timestamp will be used. */ + promptDisplayName?: string; + /** The timeout for the create_version request in seconds. If not set, the default timeout is 90 seconds. */ + timeout?: number; + /** Customer-managed encryption key spec for a prompt dataset. If set, this prompt dataset and all sub-resources of this prompt dataset will be secured by this key. */ + encryptionSpec?: genaiTypes.EncryptionSpec; + /** The display name for the prompt version. If not set, a default name with a timestamp will be used. */ + versionDisplayName?: string; +} + +/** Config for creating a prompt version. */ +export declare interface CreatePromptVersionConfig { + /** Used to override HTTP request options. */ + httpOptions?: genaiTypes.HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; + /** The display name for the prompt version. If not set, a default name with a timestamp will be used. */ + versionDisplayName?: string; + /** The timeout for the create_version request in seconds. If not set, the default timeout is 90 seconds. */ + timeout?: number; + /** The display name for the prompt. If not set, a default name with a timestamp will be used. */ + promptDisplayName?: string; + /** Customer-managed encryption key spec for a prompt dataset. If set, this prompt dataset and all sub-resources of this prompt dataset will be secured by this key. */ + encryptionSpec?: genaiTypes.EncryptionSpec; +} + +/** Config for getting a prompt. */ +export declare interface GetPromptConfig { + /** Used to override HTTP request options. */ + httpOptions?: genaiTypes.HttpOptions; + /** Abort signal which can be used to cancel the request. + + NOTE: AbortSignal is a client-only operation. Using it to cancel an + operation will not cancel the request in the service. You will still + be charged usage for any applicable operations. + */ + abortSignal?: AbortSignal; +} + +/** Reference to a prompt. */ +export declare interface PromptRef { + promptId?: string; + model?: string; +} + +/** Reference to a prompt version. */ +export declare interface PromptVersionRef { + promptId?: string; + versionId?: string; + model?: string; +} + +/** VAPO Prompt Optimizer Config. */ +export declare interface OptimizeJobConfig { + /** The gcs path to the config file, e.g. gs://bucket/config.json. */ + configPath?: string; + /** The service account to use for the custom job. Cannot be provided at the same time as service_account_project_number. */ + serviceAccount?: string; + /** The project number used to construct the default service account:{service_account_project_number}-compute@developer.gserviceaccount.comCannot be provided at the same time as "service_account". */ + serviceAccountProjectNumber?: number | string; + /** Whether to wait for the job tocomplete. Ignored for async jobs. */ + waitForCompletion?: boolean; + /** The display name of the optimization job. If not provided, a display name in the format of "vapo-optimizer-{timestamp}" will be used. */ + optimizerJobDisplayName?: string; } diff --git a/src/genai/types/prompts.ts b/src/genai/types/prompts.ts new file mode 100644 index 00000000..56a17921 --- /dev/null +++ b/src/genai/types/prompts.ts @@ -0,0 +1,33 @@ +/** + * @license + * Copyright 2025 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +// Code generated by the Google Gen AI SDK generator DO NOT EDIT. + +// eslint-disable-next-line @typescript-eslint/no-unused-vars +import * as genaiTypes from '@google/genai'; + +/** Applicable guideline for the optimize_prompt method. */ +export declare interface ApplicableGuideline { + applicableGuideline?: string; + suggestedImprovement?: string; + textBeforeChange?: string; + textAfterChange?: string; +} + +/** Response for the optimize_prompt method. */ +export class ParsedResponse { + optimizationType?: string; + applicableGuidelines?: ApplicableGuideline[]; + originalPrompt?: string; + suggestedPrompt?: string; +} + +/** Response for the optimize_prompt method. */ +export class ParsedResponseFewShot { + suggestedModifications?: ApplicableGuideline[]; + originalSystemInstructions?: string; + newSystemInstructions?: string; +} diff --git a/test/genai/prompts_e2e_test.ts b/test/genai/prompts_e2e_test.ts new file mode 100644 index 00000000..6c669f63 --- /dev/null +++ b/test/genai/prompts_e2e_test.ts @@ -0,0 +1,91 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import 'jasmine'; +import {Client} from '../../src/genai/client.js'; + +const PROJECT = process.env['GCLOUD_PROJECT'] || 'vertex-sdk-dev'; +const LOCATION = 'us-central1'; + +xdescribe('Prompts E2E', () => { + let client: Client; + let promptId: string | undefined; + + beforeEach(() => { + jasmine.DEFAULT_TIMEOUT_INTERVAL = 300000; + client = new Client({ + project: PROJECT as string, + location: LOCATION, + }); + }); + + afterAll(async () => { + if (promptId) { + try { + await client.prompts.delete({ + promptId: promptId, + }); + } catch (e) { + // Ignore failure during cleanup to avoid failing the test run + } + } + }); + + it('should create, get, update, and list prompts', async () => { + const prompt = await client.prompts.create({ + prompt: { + promptData: { + contents: [ + { + role: 'user', + parts: [{text: 'Hello, world!'}], + }, + ], + model: 'gemini-2.0-flash-001', + }, + }, + config: { + promptDisplayName: `system_test_prompt_${Date.now()}`, + }, + }); + + expect(prompt).toBeDefined(); + expect(prompt._dataset).toBeDefined(); + + promptId = prompt._dataset?.name?.split('/').pop(); + expect(promptId).toBeDefined(); + + if (promptId) { + const retrievedPrompt = await client.prompts.get({ + promptId: promptId, + }); + expect(retrievedPrompt).toBeDefined(); + + const updatedPrompt = await client.prompts.update({ + promptId: promptId, + prompt: { + promptData: { + contents: [ + { + role: 'user', + parts: [{text: 'Hello, world! (updated)'}], + }, + ], + model: 'gemini-2.0-flash-001', + }, + }, + config: { + versionDisplayName: `updated_version_${Date.now()}`, + }, + }); + expect(updatedPrompt).toBeDefined(); + + const prompts = await client.prompts.list(); + expect(prompts).toBeDefined(); + expect(prompts.length).toBeGreaterThan(0); + } + }); +}); diff --git a/test/genai/prompts_test.ts b/test/genai/prompts_test.ts new file mode 100644 index 00000000..791540ee --- /dev/null +++ b/test/genai/prompts_test.ts @@ -0,0 +1,207 @@ +/** + * @license + * Copyright 2026 Google LLC + * SPDX-License-Identifier: Apache-2.0 + */ + +import 'jasmine'; +import {ReplayClient} from './_replay_client.js'; + +const TEST_PROMPT = { + promptData: { + contents: [ + { + role: 'user', + parts: [{text: 'Hello, {name}! How are you?'}], + }, + ], + model: 'gemini-2.0-flash-001', + variables: [ + {name: {text: 'Alice'}}, + {name: {text: 'Bob'}} + ], + generationConfig: { + temperature: 0.1, + candidateCount: 1, + topP: 0.95, + topK: 40, + responseModalities: ['TEXT'], + responseSchema: { + type: 'OBJECT', + properties: {response: {type: 'STRING'}}, + }, + }, + safetySettings: [ + { + category: 'HARM_CATEGORY_DANGEROUS_CONTENT', + threshold: 'BLOCK_MEDIUM_AND_ABOVE', + method: 'SEVERITY', + }, + ], + systemInstruction: { + parts: [{text: 'Please answer in a short sentence.'}], + }, + tools: [ + { + googleSearchRetrieval: { + dynamicRetrievalConfig: { + mode: 'MODE_DYNAMIC', + }, + }, + }, + ], + toolConfig: {}, + }, +}; + +describe('Prompts', () => { + let client: ReplayClient; + + beforeEach(() => { + jasmine.DEFAULT_TIMEOUT_INTERVAL = 120000; + client = new ReplayClient({ + project: 'vertex-sdk-dev', + location: 'us-central1', + }); + }); + + it('creates a prompt', async () => { + const fetchSpy = client.setupReplay( + 'create_prompt/test_create.vertex.json'); + + const prompt = await client.prompts.create({ + prompt: TEST_PROMPT, + config: { + promptDisplayName: 'my_prompt', + versionDisplayName: 'my_version', + }, + }); + + client.verifyInteraction(0, fetchSpy.calls.argsFor(0)); + expect(prompt).toBeDefined(); + client.verifyAllInteractions(); + }); + + it('gets a prompt', async () => { + const fetchSpy = client.setupReplay( + 'get_prompt_resource/test_get_prompt.vertex.json'); + + const prompt = await client.prompts.get({ + promptId: '6550997480673116160', + }); + + client.verifyInteraction(0, fetchSpy.calls.argsFor(0)); + expect(prompt).toBeDefined(); + client.verifyAllInteractions(); + }); + + it('updates a prompt', async () => { + const fetchSpy = client.setupReplay( + 'update_prompt/test_update_creates_new_version.vertex.json'); + + const prompt = await client.prompts.update({ + promptId: '8005484238453342208', + prompt: { + promptData: { + ...TEST_PROMPT.promptData, + contents: [ + { + role: 'user', + parts: [{text: 'Is this Alice?'}], + }, + ], + }, + }, + config: { + versionDisplayName: 'my_version', + }, + }); + + client.verifyInteraction(0, fetchSpy.calls.argsFor(0)); + expect(prompt).toBeDefined(); + client.verifyAllInteractions(); + }); + + it('lists prompts', async () => { + const fetchSpy = client.setupReplay( + 'list_prompts/test_list_returns_prompts_async.vertex.json'); + + const prompts = await client.prompts.list(); + + client.verifyInteraction(0, fetchSpy.calls.argsFor(0)); + expect(prompts).toBeDefined(); + }); + + it('lists prompt versions', async () => { + const fetchSpy = client.setupReplay( + 'list_prompts/test_list_versions_async.vertex.json'); + + const versions = await client.prompts.listVersions({ + promptId: '3331020504126455808', + }); + + client.verifyInteraction(0, fetchSpy.calls.argsFor(0)); + expect(versions).toBeDefined(); + expect(versions.length).toBeGreaterThan(0); + client.verifyAllInteractions(); + }); + + it('deletes a prompt', async () => { + const fetchSpy = client.setupReplay( + 'delete_prompt/test_delete_dataset_async.vertex.json'); + + // Spy on _wait_for_project_operation to avoid failure due to missing operation name in replay + spyOn(client.prompts as any, '_wait_for_project_operation').and.resolveTo(); + + // Consume the 5 list calls expected by the replay file + for (let i = 0; i < 5; i++) { + await client.prompts.list(); + } + + await client.prompts.delete({ + promptId: '5470670131778551808', + }); + + client.verifyInteraction(5, fetchSpy.calls.argsFor(5)); + }); + + it('restores a prompt version', async () => { + const fetchSpy = client.setupReplay( + 'restore_prompt_version/test_restore_version_async.vertex.json'); + + // Spy on _wait_for_project_operation to avoid timeout in replay mode + spyOn(client.prompts as any, '_wait_for_project_operation').and.resolveTo(); + + const promptV1 = await client.prompts.createVersion({ + prompt: TEST_PROMPT, + config: { + promptDisplayName: 'my_prompt', + versionDisplayName: 'my_prompt_v1', + } + }); + + const promptV2 = await client.prompts.update({ + promptId: promptV1._dataset.name.split('/').pop(), + prompt: { + promptData: { + contents: [{role: 'user', parts: [{text: 'Is this Alice?'}]}], + model: 'gemini-2.0-flash-001', + } + }, + config: { + promptDisplayName: 'my_prompt', + versionDisplayName: 'my_prompt_v2', + } + }); + + const myPromptV1Id = promptV1._dataset_version.name.split('/').pop(); + + const restoredPrompt = await client.prompts.restoreVersion({ + promptId: promptV1._dataset.name.split('/').pop(), + versionId: myPromptV1Id, + }); + + client.verifyInteraction(0, fetchSpy.calls.argsFor(0)); + expect(restoredPrompt).toBeDefined(); + }); +});