Implementing OpenAI Function Calling with Langchain Chains

langchain-fc

Last week, OpenAI released it's new function calling feature. If you already use Langchain chains in your application, you might be wondering how to integrate OpenAI functions in your code. I initially struggled with this because the docs on Langchain's website were missing key information. Hopefully, the team will update the docs soon.

In the meantime, here are the two ways I found to implement function calling with Langchain chains:

1. Using Langchain’s parser for functions output

Langchain offers an output parser that returns the invoked function's arguments as a dict from the LLMChain.

langchainfc1
langchainfc2

Note: This method omits the name of the function to be called. So, it's ideal when you already know which function needs to be invoked.

2. Extracting and parsing the data manually

Alternatively, if need the function's name to call it in your code, set return_final_only to False in LLMChain's arguments. Then, extract the name and args from the output and manually parse the args into dict.

langchainfc3
langchainfc4

Hope this helps!