Building an AI-Powered CLI with Golang and Google Gemini - DEV ...
I recently built an AI-powered CLI with Golang named GenCLI, from which you can ask questions in text format or give it an image and ask for details about it from the terminal. If that sounds interesting to you, this blog is for you. In this guide, we will build a CLI completely from scratch and give it AI power using Google's Gemini API. If you want to check out GenCLI, here is the link. It's open source.
Setting Up the Project
To get started, create a folder and open it in your favorite IDE/Editor. Initialize the project by running the command go mod init <path>
. This will create a go.mod
file.
![Building CLI applications in Go with Cobra - Mattermost](http://mattermost.com/wp-content/uploads/2022/09/05_CLI_Apps_Go@2x.png)
Although you can create and do everything manually for building a CLI, using the Cobra Package can help speed up the process and reduce errors. Install the Cobra CLI tool using the command below:
Creating Sub-Commands
Instead of writing logic directly to root.go
, it's recommended to create a sub-command for the CLI. To create a sub-command, use the add
command provided by Cobra CLI.
Working with Google's Gemini API
First, install the Gemini Golang SDK package to communicate with Google's Gemini API. Obtain an API Key from https://aistudio.google.com/app/apikey and set it as an environment variable.
![Auto-Completing CLI Arguments in Golang with Cobra | raftt Blog](https://www.raftt.io/assets/627bf36ecef36c976239c7b6/64bfd552f6d099c467ad219b_Auto-Completing%20CLI%20Arguments%20in%20Golang%E2%80%99s%20with%20Cobra.png)
Making the Prompt Dynamic
To make the prompt dynamic, modify the code to accept user input via the terminal. Update the ARG:
field in the searchCmd
struct and adjust the getResponse
function accordingly.
Publishing the CLI
To publish the package, push your changes to GitHub and request adding the package to pkg.go.dev
. Once approved, you can download the CLI using the go install
command.
![Using Vertex AI Gemini from GAPIC libraries (C#) | by Mete Atamel ...](https://miro.medium.com/v2/resize:fit:1080/0*KrbRuu5wgOHtgL0P.png)
That's it for building an AI-Powered CLI with Golang and Google Gemini. Thank you for reading through this detailed guide!