Skip links

Interacting with OpenAI API using Golang

I normally use Python’s LangChain framework to communicate with OpenAI API. For a change, I wanted to see if Go has any libraries to access OpenAI and other LLMs. Interestingly I found that LangChainGo is a port of LangChain for Golang!

I decided to implement a simple Completetion request in both streaming and non-streaming modes. Turned out to be pretty straightforward. I am not implementing any fancy GUI for this example. It just prints onto the console.

Here is the code that interacts with OpenAI in non-streaming (sync) mode:

Non-streaming Mode
Non-streaming Mode

The corresponding output is this (there is a small delay before the whole output is printed):

The Output
The Output

Here is the code that works in async (streaming) mode:

Streaming Mode
Streaming Mode

When you run this function, the output is printed in chunks as expected. The final output is shown below:

Streaming Mode Output
Streaming Mode Output

As you can see, the code abstraction is pretty clean and intuitive. The good news is that LangChainGo supports many other LLMs too. 

The source code can be downloaded here.

Leave a comment