async getEmbeddings()

in firestore-vector-search/functions/src/embeddings/client/text/custom_function.ts [35:80]


  async getEmbeddings(batch: string[]): Promise<number[][]> {
    const res = await fetch(endpoint!, {
      method: 'POST',
      body: JSON.stringify({batch}),
      headers: {
        'Content-Type': 'application/json',
      },
    });

    if (!res.ok) {
      throw new Error(
        `Error getting embeddings from custom endpoint: ${res.statusText}`
      );
    }
    if (!res.headers.get('content-type')?.includes('application/json')) {
      throw new Error(
        'Error getting embeddings from custom endpoint: response is not JSON'
      );
    }
    const data = await res.json();

    const dataSchema = z.object({
      embeddings: z.array(z.array(z.number())),
    });

    let embeddings: number[][] = [];

    try {
      embeddings = dataSchema.parse(data).embeddings;
    } catch (e) {
      throw new Error(
        'Error getting embeddings from custom endpoint: response does not match expected schema'
      );
    }

    if (
      !embeddings ||
      !Array.isArray(embeddings) ||
      embeddings.length !== batch.length
    ) {
      throw new Error(
        'Error getting embeddings from custom endpoint: response does not contain embeddings'
      );
    }
    return embeddings;
  }