Add support for Azure OpenAI Endpoint in OpenAIEmbeddingProvider (#1517)

This commit is contained in:
Andrij David 2024-06-27 17:24:06 +02:00 • committed by GitHub
parent 6407458d76
commit 02784804ab
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
2 changed files with 22 additions and 4 deletions

3
core/index.d.ts vendored
View file

@ -720,6 +720,9 @@ export interface EmbedOptions {
apiBase?: string;
apiKey?: string;
model?: string;
engine?: string;
apiType?: string;
apiVersion?: string;
requestOptions?: RequestOptions;
}

View file

@ -13,11 +13,25 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
model: "text-embedding-3-small",
};
async embed(chunks: string[]) {
if (!this.options.apiBase?.endsWith("/")) {
this.options.apiBase += "/";
private _getEndpoint() {
if (!this.options.apiBase) {
throw new Error("No API base URL provided. Please set the 'apiBase' option in config.json");
}
this.options.apiBase = this.options.apiBase.endsWith("/")
? this.options.apiBase
: `${this.options.apiBase}/`;
if (this.options.apiType === "azure") {
return new URL(
`openai/deployments/${this.options.engine}/embeddings?api-version=${this.options.apiVersion}`,
this.options.apiBase,
);
}
return new URL("embedding", this.options.apiBase);
}
async embed(chunks: string[]) {
const batchedChunks = [];
for (
let i = 0;
@ -33,7 +47,7 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
batchedChunks.map(async (batch) => {
const fetchWithBackoff = () =>
withExponentialBackoff<Response>(() =>
this.fetch(new URL("embeddings", this.options.apiBase), {
this.fetch(this._getEndpoint(), {
method: "POST",
body: JSON.stringify({
input: batch,
@ -42,6 +56,7 @@ class OpenAIEmbeddingsProvider extends BaseEmbeddingsProvider {
headers: {
Authorization: `Bearer ${this.options.apiKey}`,
"Content-Type": "application/json",
"api-key": this.options.apiKey ?? "", // For Azure
},
}),
);