Notebooks
A
Azure
Embedding Long Inputs

Embedding Long Inputs

azure-openai-samplesBasic_Samplesdotnetembeddingscsharp

Embedding texts that are longer than the model's maximum context length

OpenAI's embedding models cannot embed text that exceeds a maximum length. The maximum length varies by model, and is measured by tokens, not string length. If you are unfamiliar with tokenization, check out How to count tokens with tiktoken.

This notebook shows how to handle texts that are longer than a model's maximum context length. We'll demonstrate using embeddings from text-embedding-ada-002, but the same ideas can be applied to other models and tasks. To learn more about embeddings, check out the OpenAI Embeddings Guide.

Installation

Install the Azure Open AI SDK using the below command.

[1]
[ ]
[3]

Run this cell, it will prompt you for the apiKey, endPoint, and embedding deployment

[4]

Import namesapaces and create an instance of OpenAiClient using the azureOpenAIEndpoint and the azureOpenAIKey

[5]
[6]
[7]

Run the following cell

It will display and error like:

	Azure.RequestFailedException: This model's maximum context length is 8191 tokens, however you requested 10000 tokens (10000 in your prompt; 0 for the completion). Please reduce your prompt; or completion length.

Status: 400 (model_error)

Content:

{

  "error": {

    "message": "This model's maximum context length is 8191 tokens, however you requested 10000 tokens (10000 in your prompt; 0 for the completion). Please reduce your prompt; or completion length.",

    "type": "invalid_request_error",

    "param": null,

    "code": null

  }

}

This shows that we have crossed the limit of 8191 tokens.

[9]
Azure.RequestFailedException: This model's maximum context length is 8191 tokens, however you requested 10000 tokens (10000 in your prompt; 0 for the completion). Please reduce your prompt; or completion length.

Status: 400 (model_error)



Content:

{

  "error": {

    "message": "This model's maximum context length is 8191 tokens, however you requested 10000 tokens (10000 in your prompt; 0 for the completion). Please reduce your prompt; or completion length.",

    "type": "invalid_request_error",

    "param": null,

    "code": null

  }

}





Headers:

Access-Control-Allow-Origin: REDACTED

X-Content-Type-Options: REDACTED

apim-request-id: REDACTED

X-Request-ID: REDACTED

ms-azureml-model-error-reason: REDACTED

ms-azureml-model-error-statuscode: REDACTED

x-ms-client-request-id: 89940e48-7900-40f3-ba70-68eef1b6a149

x-ms-region: REDACTED

Strict-Transport-Security: REDACTED

Date: Tue, 07 Nov 2023 12:16:57 GMT

Content-Length: 294

Content-Type: application/json



   at Azure.Core.HttpPipelineExtensions.ProcessMessageAsync(HttpPipeline pipeline, HttpMessage message, RequestContext requestContext, CancellationToken cancellationToken)

   at Azure.AI.OpenAI.OpenAIClient.GetEmbeddingsAsync(EmbeddingsOptions embeddingsOptions, CancellationToken cancellationToken)

   at Submission#8.<<Initialize>>d__0.MoveNext()

--- End of stack trace from previous location ---

   at Microsoft.CodeAnalysis.Scripting.ScriptExecutionState.RunSubmissionsAsync[TResult](ImmutableArray`1 precedingExecutors, Func`2 currentExecutor, StrongBox`1 exceptionHolderOpt, Func`2 catchExceptionOpt, CancellationToken cancellationToken)

Clearly we want to avoid these errors, particularly when handling programmatically with a large number of embeddings. Yet, we still might be faced with texts that are longer than the maximum context length. Below we describe and provide recipes for the main approaches to handling these longer texts: (1) simply truncating the text to the maximum allowed length, and (2) chunking the text and embedding each chunk individually.

1. Truncating the input text

The simplest solution is to truncate the input text to the maximum allowed length. Because the context length is measured in tokens, we have to first tokenize the text before truncating it. The API accepts inputs both in the form of text or tokens, so as long as you are careful that you are using the appropriate encoding, there is no need to convert the tokens back into string form. Below is an example of such a truncation function.

[10]

2. Chunking the input text

Though truncation works, discarding potentially relevant text is a clear drawback. Another approach is to divide the input text into chunks and then embed each chunk individually. Then, we can either use the chunk embeddings separately, or combine them in some way, such as averaging (weighted by the size of each chunk).

Now we define a function that encodes a string into tokens and then breaks it up into chunks.

Finally, we can write a function that safely handles embedding requests, even when the input text is longer than the maximum context length, by chunking the input tokens and embedding each chunk individually. The average flag can be set to True to return the weighted average of the chunk embeddings, or False to simply return the unmodified list of chunk embeddings.

[11]
[12]

In some cases, it may make sense to split chunks on paragraph boundaries or sentence boundaries to help preserve the meaning of the text.