Blog
`wrapOpenAIClientError` function in libs/langchain-openai source code.

`wrapOpenAIClientError` function in libs/langchain-openai source code.

In this article, we will review wrapOpenAIClientError function in libs/langchain-openai source code. We will look at: 

  1. wrapOpenAIClientError function

  2. OpenAI error codes

wrapOpenAIClientError function

You will find the below code in langchainjs/src/utils/openai.ts

export function wrapOpenAIClientError(e: any) {
  let error;
  if (e.constructor.name === APIConnectionTimeoutError.name) {
    error = new Error(e.message);
    error.name = "TimeoutError";
  } else if (e.constructor.name === APIUserAbortError.name) {
    error = new Error(e.message);
    error.name = "AbortError";
  } else if (e.status === 400 && e.message.includes("tool_calls")) {
    error = addLangChainErrorFields(e, "INVALID_TOOL_RESULTS");
  } else if (e.status === 401) {
    error = addLangChainErrorFields(e, "MODEL_AUTHENTICATION");
  } else if (e.status === 429) {
    error = addLangChainErrorFields(e, "MODEL_RATE_LIMIT");
  } else if (e.status === 404) {
    error = addLangChainErrorFields(e, "MODEL_NOT_FOUND");
  } else {
    error = e;
  }
  return error;
}

This function uses if-else blocks to handle client errors.

The first two checks are based on the constructor.name

if (e.constructor.name === APIConnectionTimeoutError.name) {
    error = new Error(e.message);
    error.name = "TimeoutError";
  } else if (e.constructor.name === APIUserAbortError.name) {
    error = new Error(e.message);
    error.name = "AbortError";
  }

Rest of the blocks are based on the status code:

 else if (e.status === 400 && e.message.includes("tool_calls")) {
    error = addLangChainErrorFields(e, "INVALID_TOOL_RESULTS");
  } else if (e.status === 401) {
    error = addLangChainErrorFields(e, "MODEL_AUTHENTICATION");
  } else if (e.status === 429) {
    error = addLangChainErrorFields(e, "MODEL_RATE_LIMIT");
  } else if (e.status === 404) {
    error = addLangChainErrorFields(e, "MODEL_NOT_FOUND");
  } else

Finally, if no condition is met in the if check, error is simply assigned to the passed parameter that is e as shown below:

error = e

OpenAI error codes

In the error codes section in OpenAI documentation, you will find more information about API errors.

  1. 401 error code: 401 — Invalid Authentication

  2. 429 is for Rate limit reached for requests

  3. 404 is for “not found”

About me

Hey, my name is Ramu Narasinga. I study codebase architecture in large open-source projects.

Email: ramu.narasinga@gmail.com

Build Shadcn CLI from scratch.

References:

  1. https://github.com/langchain-ai/langchainjs/blob/main/libs/langchain-openai/src/utils/openai.ts#L17C17-L17C38

  2. https://platform.openai.com/docs/guides/error-codes