load1n9 / openai

Unofficial Deno wrapper for the Open Ai api
MIT License
73 stars 23 forks source link

ChatCompletionMessage union types dissallow proper FunctionAwareAssistantCompletionMessage and AssistantCompletionMessage usage #24

Closed MikP0 closed 1 year ago

MikP0 commented 1 year ago

When passing function and function_call to the createChatCompletion() we should expect to have function_call object inside content of a message, however it's impossible to determine whether the openAI response is AssistantCompletionMessage or FunctionAwareAssistantCompletionMessage as both share the same role:

interface AssistantCompletionMessage {
  content: string;
  name?: string;
  role: "assistant";
}

interface FunctionAwareAssistantCompletionMessage {
  content: string | null;
  role: "assistant";
  function_call?: {
    "name": string;
    "arguments": string;
  };
}

And it seems impossible to narrow the type from that point, so properties name from AssistantCompletionMessage and property function_call from FunctionAwareAssistantCompletionMessage can't be accessed. image

Moreover, those types are not exported, so you can't really create a Type Guard yourself.

lino-levan commented 1 year ago

You should be able to narrow the type further by checking of the object has a key. I'm away from my computer at the moment but something like

if ("function_call" in completionMessage) {

}

We should probably export the types anyways though.

MikP0 commented 1 year ago

That's a great point, thanks @lino-levan ! I have created a Pull Request with the exports - if you're interested https://github.com/load1n9/openai/pull/25