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 a request option for custom headers #118

Merged
merged 5 commits into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from all 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/strange-papayas-accept.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@google/generative-ai": minor
---

Add a request option for custom headers
4 changes: 4 additions & 0 deletions packages/main/src/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -56,6 +56,10 @@ export class GoogleGenerativeAIFetchError extends GoogleGenerativeAIError {
}
}

/**
*/
export class GoogleGenerativeAIRequestInputError extends GoogleGenerativeAIError {}

/**
* Details object that may be included in an error response.
* @public
Expand Down
57 changes: 56 additions & 1 deletion packages/main/src/requests/request.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,10 @@ import {
_makeRequestInternal,
constructRequest,
} from "./request";
import { GoogleGenerativeAIFetchError } from "../errors";
import {
GoogleGenerativeAIFetchError,
GoogleGenerativeAIRequestInputError,
} from "../errors";

use(sinonChai);
use(chaiAsPromised);
Expand Down Expand Up @@ -155,6 +158,40 @@ describe("request methods", () => {
);
expect(request.fetchOptions.signal).to.be.instanceOf(AbortSignal);
});
it("passes custom headers", async () => {
const request = await constructRequest(
"model-name",
Task.GENERATE_CONTENT,
"key",
true,
"",
{
customHeaders: new Headers({ customerHeader: "customerHeaderValue" }),
},
);
expect(
(request.fetchOptions.headers as Headers).get("customerHeader"),
).to.equal("customerHeaderValue");
});
it("passes custom x-goog-api-client header", async () => {
await expect(
constructRequest("model-name", Task.GENERATE_CONTENT, "key", true, "", {
customHeaders: new Headers({
"x-goog-api-client": "client/version",
}),
}),
).to.be.rejectedWith(GoogleGenerativeAIRequestInputError);
});
it("passes apiClient and custom x-goog-api-client header", async () => {
await expect(
constructRequest("model-name", Task.GENERATE_CONTENT, "key", true, "", {
apiClient: "client/version",
customHeaders: new Headers({
"x-goog-api-client": "client/version2",
}),
}),
).to.be.rejectedWith(GoogleGenerativeAIRequestInputError);
});
});
describe("_makeRequestInternal", () => {
it("no error", async () => {
Expand Down Expand Up @@ -309,5 +346,23 @@ describe("request methods", () => {
}
expect(fetchStub).to.be.calledOnce;
});
it("has invalid custom header", async () => {
const fetchStub = stub();
await expect(
_makeRequestInternal(
"model-name",
Task.GENERATE_CONTENT,
"key",
true,
"",
{
customHeaders: new Headers({
"x-goog-api-client": "client/version",
}),
},
fetchStub as typeof fetch,
),
).to.be.rejectedWith(GoogleGenerativeAIRequestInputError);
});
});
});
38 changes: 37 additions & 1 deletion packages/main/src/requests/request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { RequestOptions } from "../../types";
import {
GoogleGenerativeAIError,
GoogleGenerativeAIFetchError,
GoogleGenerativeAIRequestInputError,
} from "../errors";

export const DEFAULT_BASE_URL = "https://generativelanguage.googleapis.com";
Expand Down Expand Up @@ -76,6 +77,36 @@ export async function getHeaders(url: RequestUrl): Promise<Headers> {
headers.append("Content-Type", "application/json");
headers.append("x-goog-api-client", getClientHeaders(url.requestOptions));
headers.append("x-goog-api-key", url.apiKey);

let customHeaders = url.requestOptions.customHeaders;
if (customHeaders) {
if (!(customHeaders instanceof Headers)) {
try {
customHeaders = new Headers(customHeaders);
} catch (e) {
throw new GoogleGenerativeAIRequestInputError(
`unable to convert customHeaders value ${JSON.stringify(
customHeaders,
)} to Headers: ${e.message}`,
);
}
}

for (const [headerName, headerValue] of customHeaders.entries()) {
if (headerName === "x-goog-api-key") {
throw new GoogleGenerativeAIRequestInputError(
`Cannot set reserved header name ${headerName}`,
);
} else if (headerName === "x-goog-api-client") {
throw new GoogleGenerativeAIRequestInputError(
`Header name ${headerName} can only be set using the apiClient field`,
);
}

headers.append(headerName, headerValue);
}
}

return headers;
}

Expand Down Expand Up @@ -168,7 +199,12 @@ export async function _makeRequestInternal(
}
} catch (e) {
let err = e;
if (!(e instanceof GoogleGenerativeAIFetchError)) {
if (
!(
e instanceof GoogleGenerativeAIFetchError ||
e instanceof GoogleGenerativeAIRequestInputError
)
) {
err = new GoogleGenerativeAIError(
`Error fetching from ${url.toString()}: ${e.message}`,
);
Expand Down
4 changes: 4 additions & 0 deletions packages/main/types/requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,6 +136,10 @@ export interface RequestOptions {
* Base endpoint url. Defaults to "https://generativelanguage.googleapis.com"
*/
baseUrl?: string;
/**
* Custom HTTP request headers.
*/
customHeaders?: Headers | Record<string, string>;
}

/**
Expand Down
Loading