gopilot

package module
v1.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 27, 2025 License: MIT Imports: 8 Imported by: 0

README

GoPilot: AI-Powered Function Router for Go

Gopilot Logo

Development Status Go Version go-pilot go-pilot

⚠️ Note: This project is under active development and currently supports only the Gemini LLM.

Overview

GoPilot is an intelligent automation platform that enables natural language interaction with your Go functions. It automatically routes user queries to the appropriate functions, handles parameter mapping, and manages execution flow - all through simple conversational inputs.

Key Features
  • 🤖 Natural Language Processing: Process user queries in natural language
  • 🎯 Automatic Function Routing: Map queries to the most appropriate function
  • 🔄 Type-Safe Parameter Mapping: Convert dynamic inputs to strongly-typed parameters
  • 🛡️ Validation Built-in: Automatic validation of required parameters
  • 🔌 Easy Integration: Simple API for registering and executing functions
  • 🎨 Flexible Response Handling: Support for various response types and formats

Installation

go get github.com/SadikSunbul/gopilot

Quick Start

Here's a simple example that demonstrates how to use GoPilot:

package main

import (
    "context"
    "fmt"
    "log"
    
    "github.com/SadikSunbul/gopilot"
    "github.com/SadikSunbul/gopilot/clients"
    "github.com/SadikSunbul/gopilot/pkg/generator"
)

// Define your function parameters
type WeatherParams struct {
    City string `json:"city" description:"The name of the city to get weather information for" required:"true"`
}

// Define your function response
type WeatherResponse struct {
    City      string `json:"city"`
    Temp      int    `json:"temp"`
    Condition string `json:"condition"`
}

// Implement your function logic
func GetWeather(params WeatherParams) (WeatherResponse, error) {
    if params.City == "" {
        return WeatherResponse{}, fmt.Errorf("city cannot be empty")
    }
    
    // Your weather API integration here
    return WeatherResponse{
        City:      params.City,
        Temp:      25,
        Condition: "sunny",
    }, nil
}

func main() {
    // Initialize Gemini client
    client, err := clients.NewGeminiClient(context.Background(), "your-api-key", "gemini-2.0-flash")
    if err != nil {
        log.Fatal(err)
    }
    defer client.Close()

    // Create GoPilot instance
    gp, err := gopilot.NewGopilot(client)
    if err != nil {
        log.Fatal("failed to initialize gopilot:", err)
    }

    // Register your function
    weatherFn := &gopilot.Function[WeatherParams, WeatherResponse]{
        Name:        "weather-agent",
        Description: "Gets weather information for a specified city",
        Parameters:  generator.GenerateParameterSchema(WeatherParams{}),
        Execute:     GetWeather,
    }
    
    if err := gp.FunctionRegister(weatherFn); err != nil {
        log.Fatal(err)
    }

    // Set system prompt (required)
    gp.SetSystemPrompt(nil)

    // Process user query
    input := "What's the weather like in Istanbul?"
    
    // Option 1: Generate and Execute separately
    response, err := gp.Generate(input)
    if err != nil {
        log.Fatal(err)
    }
    
    result, err := gp.FunctionExecute(response.Agent, response.Parameters)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("Result: %+v\n", result)

    // Option 2: Generate and Execute in one step
    result, err = gp.GenerateAndExecute(input)
    if err != nil {
        log.Fatal(err)
    }
    
    fmt.Printf("Result: %+v\n", result)
}

Advanced Usage

Complex Parameter Types

GoPilot supports nested and complex parameter types:

type TranslateParams struct {
    Text string `json:"text" description:"The text to translate" required:"true"`
    Path struct {
        From    string `json:"from" description:"Source language code" required:"true"`
        To      string `json:"to" description:"Target language code" required:"true"`
        Options struct {
            Style string `json:"style" description:"Translation style"`
        } `json:"options" description:"Additional options"`
    } `json:"path" description:"Translation configuration" required:"true"`
}

type TranslateResponse struct {
    Original   string `json:"original"`
    Translated string `json:"translated"`
    From       string `json:"from"`
    To         string `json:"to"`
    Style      string `json:"style,omitempty"`
}

func Translate(params TranslateParams) (TranslateResponse, error) {
    // Your translation logic here
}

// Register the translation function
translateFn := &gopilot.Function[TranslateParams, TranslateResponse]{
    Name:        "translate-agent",
    Description: "Translates text between languages",
    Parameters:  generator.GenerateParameterSchema(TranslateParams{}),
    Execute:     Translate,
}
Interactive CLI Example

Here's how to create an interactive CLI application:

reader := bufio.NewReader(os.Stdin)
fmt.Println("Welcome! Type 'exit' to exit.")

for {
    fmt.Print("\nQuestion: ")
    input, err := reader.ReadString('\n')
    if err != nil {
        log.Fatal(err)
    }

    input = strings.TrimSpace(input)
    if input == "exit" {
        break
    }

    result, err := gp.GenerateAndExecute(input)
    if err != nil {
        log.Printf("Error: %v\n", err)
        continue
    }

    fmt.Printf("Result: %+v\n", result)
}

Best Practices

  1. Parameter Validation

    • Always validate required parameters
    • Use descriptive error messages
    • Add proper documentation using struct tags
  2. Error Handling

    • Return specific error types
    • Handle both function-specific and system errors
    • Provide context in error messages
  3. Function Registration

    • Use descriptive function names
    • Provide clear function descriptions
    • Document parameter requirements
  4. Type Safety

    • Use strongly-typed parameters and responses
    • Leverage Go's type system for validation
    • Avoid interface{} when possible

Contributing

We welcome contributions! Please see our Contributing Guidelines for details.

Security

For security concerns, please review our Security Policy.

License

This project is licensed under the MIT License - see the LICENSE file for details.

Support

Acknowledgments

  • Thanks to all contributors who have helped shape GoPilot
  • Special thanks to the Go community for their support and feedback

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Execute added in v1.2.0

func Execute[T any, R any](r *Registry, name string, params T) (R, error)

Execute runs a registered function with the given parameters

func ExecuteWithParams added in v1.2.0

func ExecuteWithParams[T any, R any](fn func(T) (R, error), params map[string]interface{}) (interface{}, error)

ExecuteWithParams is a helper function to execute a function with typed parameters

func RegisterTyped added in v1.2.0

func RegisterTyped[T any, R any](r *Registry, fn *Function[T, R]) error

RegisterTyped adds a new typed function to the registry

Types

type Function

type Function[T any, R any] struct {
	Name        string                               `json:"name"`
	Description string                               `json:"description"`
	Parameters  map[string]generator.ParameterSchema `json:"parameters"`
	Execute     func(params T) (R, error)
}

Function represents a registered function in the system

func Get added in v1.2.0

func Get[T any, R any](r *Registry, name string) (*Function[T, R], error)

Get retrieves a function from the registry

func UnsupportedFunction added in v1.2.0

func UnsupportedFunction() *Function[UnsupportedParams, UnsupportedResponse]

UnsupportedFunction creates a new unsupported function handler

func (*Function[T, R]) ExecuteWithJson added in v1.2.0

func (f *Function[T, R]) ExecuteWithJson(jsonParams string) (interface{}, error)

ExecuteWithJson executes the function with JSON string parameters

func (*Function[T, R]) ExecuteWithMap added in v1.2.0

func (f *Function[T, R]) ExecuteWithMap(params map[string]interface{}) (interface{}, error)

ExecuteWithMap executes the function with a parameter map

func (*Function[T, R]) GetDescription added in v1.2.0

func (f *Function[T, R]) GetDescription() string

GetDescription returns the function description

func (*Function[T, R]) GetName added in v1.2.0

func (f *Function[T, R]) GetName() string

GetName returns the function name

func (*Function[T, R]) GetParameters added in v1.2.0

func (f *Function[T, R]) GetParameters() map[string]generator.ParameterSchema

GetParameters returns the function parameters

type FunctionWrapper added in v1.2.0

type FunctionWrapper interface {
	GetName() string
	GetDescription() string
	GetParameters() map[string]generator.ParameterSchema
	ExecuteWithMap(map[string]interface{}) (interface{}, error)
}

FunctionWrapper is an interface that all functions must implement

type Gopilot

type Gopilot struct {
	// contains filtered or unexported fields
}

func NewGopilot

func NewGopilot(llm LLMProvider) (*Gopilot, error)

func (*Gopilot) FunctionExecute

func (g *Gopilot) FunctionExecute(name string, params interface{}) (interface{}, error)

FunctionExecute executes a registered function

func (*Gopilot) FunctionGet

func (g *Gopilot) FunctionGet(name string) (FunctionWrapper, error)

FunctionGet retrieves a registered function

func (*Gopilot) FunctionRegister

func (g *Gopilot) FunctionRegister(fn FunctionWrapper) error

FunctionRegister registers a new function

func (*Gopilot) FunctionsList

func (g *Gopilot) FunctionsList() []FunctionWrapper

FunctionsList returns all registered functions

func (*Gopilot) Generate

func (g *Gopilot) Generate(input string) (*clients.LLMResponse, error)

Generate generates a response from the LLM

func (*Gopilot) GenerateAndExecute

func (g *Gopilot) GenerateAndExecute(input string) (interface{}, error)

GenerateAndExecute generates a response and executes the corresponding function

func (*Gopilot) SetSystemPrompt

func (g *Gopilot) SetSystemPrompt(importantRules []string, unsupportedFunction ...FunctionWrapper)

SetSystemPrompt configures the system prompt

type LLMProvider

type LLMProvider interface {
	// Generate generates a response based on the given prompt
	Generate(prompt string) (*clients.LLMResponse, error)

	SetSystemPrompt(systemPrompt string)
}

LLMProvider defines the basic interface that any LLM provider must implement

type ParamsMapper added in v1.2.0

type ParamsMapper struct{}

ParamsMapper helps convert generic parameters to strongly typed structs

func (*ParamsMapper) Map added in v1.2.0

func (pm *ParamsMapper) Map(params map[string]interface{}, target interface{}) error

Map converts generic parameters to a strongly typed struct

type Registry

type Registry struct {
	// contains filtered or unexported fields
}

Registry represents a thread-safe function registry

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new function registry

func (*Registry) ExecuteFunction added in v1.2.0

func (r *Registry) ExecuteFunction(name string, params map[string]interface{}) (interface{}, error)

ExecuteFunction executes a registered function with the given parameters

func (*Registry) Get added in v1.2.0

func (r *Registry) Get(name string) (FunctionWrapper, bool)

Get retrieves a function from the registry

func (*Registry) List added in v1.2.0

func (r *Registry) List() []FunctionWrapper

List returns all registered functions

func (*Registry) Register added in v1.2.0

func (r *Registry) Register(fn FunctionWrapper) error

Register adds a new function to the registry

type UnsupportedParams added in v1.2.0

type UnsupportedParams struct {
	Message string `json:"message" description:"Contains a simple explanation of the error." required:"true"`
}

UnsupportedParams represents parameters for unsupported function

type UnsupportedResponse added in v1.2.0

type UnsupportedResponse struct {
	Message string `json:"message"`
}

UnsupportedResponse represents the response from unsupported function

Directories

Path Synopsis
pkg

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL