Skip to content

Commit 929df39

Browse files
Ark-kuncopybara-github
authored andcommitted
feat: Added support for Grounding
PiperOrigin-RevId: 607166015
1 parent 67a2e96 commit 929df39

File tree

3 files changed

+144
-9
lines changed

3 files changed

+144
-9
lines changed

src/functions/generate_content.ts

+4-1
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ export async function generateContent(
6969
safety_settings: request.safety_settings ?? safety_settings,
7070
tools: request.tools ?? [],
7171
};
72-
72+
const apiVersion = request.tools ? 'v1beta1' : 'v1';
7373
const response: Response | undefined = await postRequest({
7474
region: location,
7575
project: project,
@@ -78,6 +78,7 @@ export async function generateContent(
7878
token: await token,
7979
data: generateContentRequest,
8080
apiEndpoint: apiEndpoint,
81+
apiVersion: apiVersion,
8182
}).catch(e => {
8283
throw new GoogleGenerativeAIError('exception posting request', e);
8384
});
@@ -119,6 +120,7 @@ export async function generateContentStream(
119120
safety_settings: request.safety_settings ?? safety_settings,
120121
tools: request.tools ?? [],
121122
};
123+
const apiVersion = request.tools ? 'v1beta1' : 'v1';
122124
const response = await postRequest({
123125
region: location,
124126
project: project,
@@ -127,6 +129,7 @@ export async function generateContentStream(
127129
token: await token,
128130
data: generateContentRequest,
129131
apiEndpoint: apiEndpoint,
132+
apiVersion: apiVersion,
130133
}).catch(e => {
131134
throw new GoogleGenerativeAIError('exception posting request', e);
132135
});

src/types/content.ts

+107-6
Original file line numberDiff line numberDiff line change
@@ -487,11 +487,14 @@ export declare interface GenerateContentResponse {
487487
/**
488488
* A response candidate generated from the model.
489489
* @property {Content} - content. {@link Content}
490-
* @property {number} - [index]. The index of the candidate in the {@link GenerateContentResponse}
490+
* @property {number} - [index]. The index of the candidate in the {@link
491+
* GenerateContentResponse}
491492
* @property {FinishReason} - [finishReason]. {@link FinishReason}
492493
* @property {string} - [finishMessage].
493494
* @property {SafetyRating[]} - [safetyRatings]. Array of {@link SafetyRating}
494495
* @property {CitationMetadata} - [citationMetadata]. {@link CitationMetadata}
496+
* @property {GroundingMetadata} - [groundingMetadata]. {@link
497+
* GroundingMetadata}
495498
*/
496499
export declare interface GenerateContentCandidate {
497500
content: Content;
@@ -500,6 +503,7 @@ export declare interface GenerateContentCandidate {
500503
finishMessage?: string;
501504
safetyRatings?: SafetyRating[];
502505
citationMetadata?: CitationMetadata;
506+
groundingMetadata?: GroundingMetadata;
503507
functionCall?: FunctionCall;
504508
}
505509

@@ -525,6 +529,57 @@ export declare interface CitationSource {
525529
license?: string;
526530
}
527531

532+
/**
533+
* A collection of grounding attributions for a piece of content.
534+
* @property {string[]} - [webSearchQueries]. Web search queries for the
535+
* following-up web search.
536+
* @property {GroundingAttribution[]} - [groundingAttributions]. Array of {@link
537+
* GroundingAttribution}
538+
*/
539+
export declare interface GroundingMetadata {
540+
webSearchQueries?: string[];
541+
groundingAttributions?: GroundingAttribution[];
542+
}
543+
544+
/**
545+
* Grounding attribution.
546+
* @property {GroundingAttributionWeb} - [web] Attribution from the web.
547+
* @property {GroundingAttributionSegment} - [segment] Segment of the content
548+
* this attribution belongs to.
549+
* @property {number} - [confidenceScore] Confidence score of the attribution.
550+
* Ranges from 0 to 1. 1 is the most confident.
551+
*/
552+
export declare interface GroundingAttribution {
553+
web?: GroundingAttributionWeb;
554+
segment?: GroundingAttributionSegment;
555+
confidenceScore?: number;
556+
}
557+
558+
/**
559+
* Segment of the content this attribution belongs to.
560+
* @property {number} - [part_index] The index of a Part object within its
561+
* parent Content object.
562+
* @property {number} - [startIndex] Start index in the given Part, measured in
563+
* bytes. Offset from the start of the Part, inclusive, starting at zero.
564+
* @property {number} - [endIndex] End index in the given Part, measured in
565+
* bytes. Offset from the start of the Part, exclusive, starting at zero.
566+
*/
567+
export declare interface GroundingAttributionSegment {
568+
partIndex?: number;
569+
startIndex?: number;
570+
endIndex?: number;
571+
}
572+
573+
/**
574+
* Attribution from the web.
575+
* @property {string} - [uri] URI reference of the attribution.
576+
* @property {string} - [title] Title of the attribution.
577+
*/
578+
export declare interface GroundingAttributionWeb {
579+
uri?: string;
580+
title?: string;
581+
}
582+
528583
/**
529584
* A predicted FunctionCall returned from the model that contains a string
530585
* representating the FunctionDeclaration.name with the parameters and their
@@ -586,9 +641,9 @@ export declare interface FunctionDeclaration {
586641
}
587642

588643
/**
589-
* A Tool is a piece of code that enables the system to interact with
590-
* external systems to perform an action, or set of actions, outside of
591-
* knowledge and scope of the model.
644+
* A FunctionDeclarationsTool is a piece of code that enables the system to
645+
* interact with external systems to perform an action, or set of actions,
646+
* outside of knowledge and scope of the model.
592647
* @property {object} - function_declarations One or more function declarations
593648
* to be passed to the model along with the current user query. Model may decide
594649
* to call a subset of these functions by populating
@@ -598,8 +653,54 @@ export declare interface FunctionDeclaration {
598653
* generate the final response back to the user. Maximum 64 function
599654
* declarations can be provided.
600655
*/
601-
export declare interface Tool {
602-
function_declarations: FunctionDeclaration[];
656+
export declare interface FunctionDeclarationsTool {
657+
function_declarations?: FunctionDeclaration[];
658+
}
659+
660+
export declare interface RetrievalTool {
661+
retrieval?: Retrieval;
662+
}
663+
664+
export declare interface GoogleSearchRetrievalTool {
665+
googleSearchRetrieval?: GoogleSearchRetrieval;
666+
}
667+
668+
export declare type Tool =
669+
| FunctionDeclarationsTool
670+
| RetrievalTool
671+
| GoogleSearchRetrievalTool;
672+
673+
/**
674+
* Defines a retrieval tool that model can call to access external knowledge.
675+
* @property {VertexAISearch} - [vertexAiSearch] Set to use data source powered
676+
by Vertex AI Search.
677+
* @property {boolean} - [disableAttribution] Disable using the result from
678+
this tool in detecting grounding attribution. This does not affect how the
679+
result is given to the model for generation.
680+
*/
681+
export declare interface Retrieval {
682+
vertexAiSearch?: VertexAISearch;
683+
disableAttribution?: boolean;
684+
}
685+
686+
/**
687+
* Tool to retrieve public web data for grounding, powered by Google.
688+
* @property {boolean} - [disableAttribution] Disable using the result from this
689+
* tool in detecting grounding attribution. This does not affect how the result
690+
* is given to the model for generation.
691+
*/
692+
export declare interface GoogleSearchRetrieval {
693+
disableAttribution?: boolean;
694+
}
695+
696+
/**
697+
* Retrieve from Vertex AI Search datastore for grounding. See
698+
https://cloud.google.com/vertex-ai-search-and-conversation
699+
* @property {string} - [datastore] Fully-qualified Vertex AI Search's datastore
700+
resource ID. projects/<>/locations/<>/collections/<>/dataStores/<>
701+
*/
702+
export declare interface VertexAISearch {
703+
datastore: string;
603704
}
604705

605706
/**

system_test/end_to_end_sample_test.ts

+33-2
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,13 @@
1616
*/
1717

1818
// @ts-ignore
19-
import {ClientError, TextPart, VertexAI} from '../src';
19+
import {
20+
ClientError,
21+
FunctionDeclarationsTool,
22+
GoogleSearchRetrievalTool,
23+
TextPart,
24+
VertexAI,
25+
} from '../src';
2026
import {FunctionDeclarationSchemaType} from '../src/types';
2127

2228
const PROJECT = process.env.GCLOUD_PROJECT;
@@ -53,7 +59,7 @@ const MULTI_PART_BASE64_REQUEST = {
5359

5460
const FUNCTION_CALL_NAME = 'get_current_weather';
5561

56-
const TOOLS_WITH_FUNCTION_DECLARATION = [
62+
const TOOLS_WITH_FUNCTION_DECLARATION: FunctionDeclarationsTool[] = [
5763
{
5864
function_declarations: [
5965
{
@@ -75,6 +81,14 @@ const TOOLS_WITH_FUNCTION_DECLARATION = [
7581
},
7682
];
7783

84+
const TOOLS_WITH_GOOGLE_SEARCH_RETRIEVAL: GoogleSearchRetrievalTool[] = [
85+
{
86+
googleSearchRetrieval: {
87+
disableAttribution: false,
88+
},
89+
},
90+
];
91+
7892
const WEATHER_FORECAST = 'super nice';
7993
const FUNCTION_RESPONSE_PART = [
8094
{
@@ -404,6 +418,23 @@ describe('generateContent', () => {
404418
`sys test failure on generateContentStream in preview for aggregated response: ${aggregatedResp}`
405419
);
406420
});
421+
xit('should return grounding metadata when passed GoogleSearchRetriever or Retriever', async () => {
422+
const generativeTextModel = vertex_ai.getGenerativeModel({
423+
model: 'gemini-pro',
424+
//tools: TOOLS_WITH_GOOGLE_SEARCH_RETRIEVAL,
425+
});
426+
const result = await generativeTextModel.generateContent({
427+
contents: [{role: 'user', parts: [{text: 'Why is the sky blue?'}]}],
428+
tools: TOOLS_WITH_GOOGLE_SEARCH_RETRIEVAL,
429+
});
430+
const response = result.response;
431+
const groundingMetadata = response.candidates[0].groundingMetadata;
432+
expect(groundingMetadata).toBeDefined();
433+
if (groundingMetadata) {
434+
// expect(groundingMetadata.groundingAttributions).toBeTruthy();
435+
expect(groundingMetadata.webSearchQueries).toBeTruthy();
436+
}
437+
});
407438
});
408439

409440
describe('sendMessage', () => {

0 commit comments

Comments
 (0)