This project demonstrates how to build a command-line AI agent using Go and the OpenRouter API.
- Initialize Go module
go mod init your_project_name
- Create
.env
file
vim .env
Add your OpenRouter API key:
OPENROUTER_API_KEY=your_api_key_here
- Install OpenAI Go SDK
go get github.com/openai/openai-go/v2
- Create
main.go
vim main.go
- Define OpenRouter API URL.
- Load API key from
.env
and check if defined. - Create LLM client using OpenAI SDK with base URL and API key.
- Create a
messages
array and append your query usingopenai.UserMessage
. - Choose a model and define chat completion parameters.
- Create a
ctx
and callclient.ChatCompletions.New(ctx, params)
. - Print the AI response.
- Export environment variables
export $(cat .env | xargs)
- Run
go run main.go
Enhance the CLI to wait for user input in a loop:
- Create a scanner:
scanner := bufio.NewScanner(os.Stdin)
- Print a prompt symbol:
fmt.Print(">")
- Read input:
if !scanner.Scan() { break }
input := strings.TrimSpace(scanner.Text())
if input == "" { continue }
- Append input to
messages
array. - Send chat completion request.
- Print AI response.
- Loop back for the next input.
Enhance further with:
- Append AI response to
messages
. - Print message count.
- Limit
messages
array to last 4 messages if it grows too large. - Add colors with
fatih/color
:
go get github.com/fatih/color
- Use colors to differentiate:
- User queries
- AI responses
- Other info
This improves readability and visual distinction in the chat.
go run main.go
Enjoy your interactive CLI AI agent!