OpenAI-DotNet: Tool/Function - Potential Memory Leak and Concurrency Problem.

Why does the Function.FromFunc(..) store a ref to the Instance to a static cache?

Line: functionCache[Name] = this; The this object hast a ref to object instance.

https://github.com/RageAgainstThePixel/OpenAI-DotNet/blob/9124a333235cc64f725357e439faacc2718ac7ce/OpenAI-DotNet/Common/Function.cs#L78-L91

The object instance for the MethodInfo can be an object that’s only valid inside the calling method.

Imagine this example:

public void Test(int id) {
  var myService = new MyService(id); // Instance only valid inside this method!
  var request = new ChatRequest(
      messages: history,
      model: "gpt-4-0125-preview",
      toolChoice: "auto",
      tools: [
          Tool.FromFunc("test", (string search) => myService.GetData(search)), // lambda produces a compile-time generated wrapper class instance where a ref to myService is stored.
      ]
  );
}

This example has two problems:

  • It keeps myService endlessly in memory
  • It has a Concurrency Problem.

Concurrency Problem

Imagine concurrently calling Test(int id) from different threads with different values for id. Eg. inside an ActionMethod that will be called from two HttpRequest simultaneously.

In this case, the first request will store its myService instance in functionCache[Name] and the second will overwrite functionCache[Name] with its myService instance leading to unexpected behavior.

Can we remove/fix the static cache?

Maybe changing Function.Invoke.. to accept instance parameter so that only a MethoInfo gets stored and cached inside the Function.

About this issue

  • Original URL
  • State: closed
  • Created 3 years ago
  • Comments: 18 (11 by maintainers)

Commits related to this issue

Most upvoted comments

Ok, after doing some more digging into this, it looks like each func you’re registering is getting replaced by one of the other ones, bc the keys are not entirely unique in the cache, which explains the behavior you’re seeing. I believe that is the real cause of the problem, and will look into addressing this in the future.

I’ll take a look at the function cache and make sure it is properly getting cleaned up when the associated tool is also removed.

The cache is private static readonly I can not access it to call clear. Even if I were able to call clear, a concurrency problem would remain. I depend on using Tools/Functions concurrently like in the example.

There is a method to clear all tools:

https://github.com/RageAgainstThePixel/OpenAI-DotNet/blob/9124a333235cc64f725357e439faacc2718ac7ce/OpenAI-DotNet/Common/Tool.cs#L118

This method clears the tool cache but not the function cache. The function cache contains the reference to the instance in question.