Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add GenerateContentRequest as an optional param to CountTokensRequest #148

Merged
merged 5 commits into from
May 31, 2024
Merged
Show file tree
Hide file tree
Changes from 4 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/dirty-wolves-sin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@google/generative-ai": minor
---

Expand the model's countTokens method to alternatively accept a GenerateContentRequest.
DellaBitta marked this conversation as resolved.
Show resolved Hide resolved
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@
**Signature:**

```typescript
contents: Content[];
contents?: Content[];
```
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<!-- Do not edit this file. It is automatically generated by API Documenter. -->

[Home](./index.md) &gt; [@google/generative-ai](./generative-ai.md) &gt; [CountTokensRequest](./generative-ai.counttokensrequest.md) &gt; [generateContentRequest](./generative-ai.counttokensrequest.generatecontentrequest.md)

## CountTokensRequest.generateContentRequest property

**Signature:**

```typescript
generateContentRequest?: GenerateContentRequest;
```
7 changes: 5 additions & 2 deletions docs/reference/main/generative-ai.counttokensrequest.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,9 @@

## CountTokensRequest interface

Params for calling [GenerativeModel.countTokens()](./generative-ai.generativemodel.counttokens.md)
Params for calling [GenerativeModel.countTokens()](./generative-ai.generativemodel.counttokens.md)<!-- -->.

The request must contain either a [Content](./generative-ai.content.md) array or a [GenerateContentRequest](./generative-ai.generatecontentrequest.md)<!-- -->, but not both. If both are provided then a [GoogleGenerativeAIRequestInputError](./generative-ai.googlegenerativeairequestinputerror.md) is thrown.

**Signature:**

Expand All @@ -16,5 +18,6 @@ export interface CountTokensRequest

| Property | Modifiers | Type | Description |
| --- | --- | --- | --- |
| [contents](./generative-ai.counttokensrequest.contents.md) | | [Content](./generative-ai.content.md)<!-- -->\[\] | |
| [contents?](./generative-ai.counttokensrequest.contents.md) | | [Content](./generative-ai.content.md)<!-- -->\[\] | _(Optional)_ |
| [generateContentRequest?](./generative-ai.counttokensrequest.generatecontentrequest.md) | | [GenerateContentRequest](./generative-ai.generatecontentrequest.md) | _(Optional)_ |

2 changes: 1 addition & 1 deletion docs/reference/main/generative-ai.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@
| [CitationSource](./generative-ai.citationsource.md) | A single citation source. |
| [Content](./generative-ai.content.md) | Content type for both prompts and response candidates. |
| [ContentEmbedding](./generative-ai.contentembedding.md) | A single content embedding. |
| [CountTokensRequest](./generative-ai.counttokensrequest.md) | Params for calling [GenerativeModel.countTokens()](./generative-ai.generativemodel.counttokens.md) |
| [CountTokensRequest](./generative-ai.counttokensrequest.md) | <p>Params for calling [GenerativeModel.countTokens()](./generative-ai.generativemodel.counttokens.md)<!-- -->.</p><p>The request must contain either a [Content](./generative-ai.content.md) array or a [GenerateContentRequest](./generative-ai.generatecontentrequest.md)<!-- -->, but not both. If both are provided then a [GoogleGenerativeAIRequestInputError](./generative-ai.googlegenerativeairequestinputerror.md) is thrown.</p> |
| [CountTokensResponse](./generative-ai.counttokensresponse.md) | Response from calling [GenerativeModel.countTokens()](./generative-ai.generativemodel.counttokens.md)<!-- -->. |
| [EmbedContentRequest](./generative-ai.embedcontentrequest.md) | Params for calling [GenerativeModel.embedContent()](./generative-ai.generativemodel.embedcontent.md) |
| [EmbedContentResponse](./generative-ai.embedcontentresponse.md) | Response from calling [GenerativeModel.embedContent()](./generative-ai.generativemodel.embedcontent.md)<!-- -->. |
Expand Down
31 changes: 31 additions & 0 deletions packages/main/src/models/generative-model.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { expect, use } from "chai";
import { GenerativeModel } from "./generative-model";
import * as sinonChai from "sinon-chai";
import {
CountTokensRequest,
FunctionCallingMode,
HarmBlockThreshold,
HarmCategory,
Expand Down Expand Up @@ -319,4 +320,34 @@ describe("GenerativeModel", () => {
);
restore();
});
it("countTokens errors if contents and generateContentRequest are both defined", async () => {
const genModel = new GenerativeModel(
"apiKey",
{
model: "my-model",
},
{
apiVersion: "v2000",
},
);
const mockResponse = getMockResponse(
"unary-success-basic-reply-short.json",
);
const makeRequestStub = stub(request, "makeRequest").resolves(
mockResponse as Response,
);
const countTokensRequest: CountTokensRequest = {
contents: [{ role: "user", parts: [{ text: "hello" }] }],
generateContentRequest: {
contents: [{ role: "user", parts: [{ text: "hello" }] }],
},
};
await expect(
genModel.countTokens(countTokensRequest),
).to.eventually.be.rejectedWith(
"CountTokensRequest must have one of contents or generateContentRequest, not both.",
);
expect(makeRequestStub).to.not.be.called;
restore();
});
});
4 changes: 3 additions & 1 deletion packages/main/src/models/generative-model.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,7 @@ import { ChatSession } from "../methods/chat-session";
import { countTokens } from "../methods/count-tokens";
import { batchEmbedContents, embedContent } from "../methods/embed-content";
import {
formatCountTokensInput,
formatEmbedContentInput,
formatGenerateContentInput,
formatSystemInstruction,
Expand Down Expand Up @@ -157,7 +158,8 @@ export class GenerativeModel {
async countTokens(
request: CountTokensRequest | string | Array<string | Part>,
): Promise<CountTokensResponse> {
const formattedParams = formatGenerateContentInput(request);
const formattedParams = formatCountTokensInput(request, this.model);
// countTokens() appends the model to the CountTokensRequest proto.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think this comment should be for the previous line? countTokens doesn't append anything. It uses the model param to build the request url.

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

It adds it to the request body, but I'll remove the comment.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

countTokens() doesn't, but formatCountTokensInput() does, right? That's why I think it would be best to attach it to the previous line? countTokens() just calls makeRequest() and returns response.json().

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

countTokens() also adds it to the proto request object here.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hm, that seems to have been there since initial commit but I can't remember why it was needed. I don't know if countTokens is special or if I forgot to remove the model there when I removed it from generateContent and the other methods, let me double check. If it's just left over from the beginning we should probably remove it to avoid unexpected behavior.

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think this blocks this PR though.

return countTokens(
this.apiKey,
this.model,
Expand Down
32 changes: 31 additions & 1 deletion packages/main/src/requests/request-helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,11 +17,16 @@

import {
Content,
CountTokensRequest,
CountTokensRequestInternal,
EmbedContentRequest,
GenerateContentRequest,
Part,
} from "../../types";
import { GoogleGenerativeAIError } from "../errors";
import {
GoogleGenerativeAIError,
GoogleGenerativeAIRequestInputError,
} from "../errors";

export function formatSystemInstruction(
input?: string | Part | Content,
Expand Down Expand Up @@ -104,6 +109,31 @@ function assignRoleToPartsAndValidateSendMessageRequest(
return functionContent;
}

export function formatCountTokensInput(
params: CountTokensRequest | string | Array<string | Part>,
model: string,
): CountTokensRequestInternal {
let formattedRequest: CountTokensRequestInternal = {};
const containsGenerateContentRequest =
(params as CountTokensRequest).generateContentRequest != null;
if ((params as CountTokensRequest).contents) {
if (containsGenerateContentRequest) {
throw new GoogleGenerativeAIRequestInputError(
"CountTokensRequest must have one of contents or generateContentRequest, not both.",
);
}
formattedRequest = { ...(params as CountTokensRequest) };
} else if (containsGenerateContentRequest) {
formattedRequest = { ...(params as CountTokensRequest) };
formattedRequest.generateContentRequest.model = model;
} else {
// Array or string
const content = formatNewContent(params as string | Array<string | Part>);
formattedRequest.contents = [content];
}
return formattedRequest;
}

export function formatGenerateContentInput(
params: GenerateContentRequest | string | Array<string | Part>,
): GenerateContentRequest {
Expand Down
20 changes: 20 additions & 0 deletions packages/main/test-integration/node/count-tokens.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@
import { expect, use } from "chai";
import * as chaiAsPromised from "chai-as-promised";
import { GoogleGenerativeAI, HarmBlockThreshold, HarmCategory } from "../..";
import { CountTokensRequest } from "../../types";

use(chaiAsPromised);

Expand Down Expand Up @@ -46,4 +47,23 @@ describe("countTokens", function () {
expect(response1.totalTokens).to.equal(3);
expect(response2.totalTokens).to.equal(3);
});
it("counts tokens with GenerateContentRequest", async () => {
const genAI = new GoogleGenerativeAI(process.env.GEMINI_API_KEY || "");
const model = genAI.getGenerativeModel({
model: "gemini-1.5-flash-latest",
safetySettings: [
{
category: HarmCategory.HARM_CATEGORY_HARASSMENT,
threshold: HarmBlockThreshold.BLOCK_ONLY_HIGH,
},
],
});
const countTokensRequest: CountTokensRequest = {
generateContentRequest: {
contents: [{ role: "user", parts: [{ text: "count me" }] }],
},
};
const response = await model.countTokens(countTokensRequest);
expect(response.totalTokens).to.equal(3);
});
});
27 changes: 25 additions & 2 deletions packages/main/types/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,6 +54,14 @@ export interface GenerateContentRequest extends BaseParams {
systemInstruction?: string | Part | Content;
}

/**
* Request sent to `generateContent` endpoint.
* @internal
*/
export interface GenerateContentRequestInternal extends GenerateContentRequest {
model?: string;
}

/**
* Safety setting that can be sent as part of request parameters.
* @public
Expand Down Expand Up @@ -95,11 +103,26 @@ export interface StartChatParams extends BaseParams {
}

/**
* Params for calling {@link GenerativeModel.countTokens}
* Params for calling {@link GenerativeModel.countTokens}.
*
* The request must contain either a {@link Content} array or a
* {@link GenerateContentRequest}, but not both. If both are provided
* then a {@link GoogleGenerativeAIRequestInputError} is thrown.
*
* @public
hsubox76 marked this conversation as resolved.
Show resolved Hide resolved
*/
export interface CountTokensRequest {
contents: Content[];
generateContentRequest?: GenerateContentRequest;
contents?: Content[];
}

/**
* Params for calling {@link GenerativeModel.countTokens}
hsubox76 marked this conversation as resolved.
Show resolved Hide resolved
* @internal
*/
export interface CountTokensRequestInternal {
generateContentRequest?: GenerateContentRequestInternal;
contents?: Content[];
}

/**
Expand Down
Loading