llm

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Feb 1, 2025 License: Apache-2.0 Imports: 5 Imported by: 0

README

go-llm

Large Language Model API interface. This is a simple API interface for large language models which run on Ollama and Anthopic.

The module includes the ability to utilize:

  • Maintaining a session of messages
  • Tool calling support
  • Streaming responses

There is a command-line tool included in the module which can be used to interact with the API. For example,

# Display help
docker run ghcr.io/mutablelogic/go-llm:latest --help

# Interact with Claude to retrieve news headlines, assuming
# you have an API key for Anthropic and NewsAPI
docker run \
  --interactive -e ANTHROPIC_API_KEY -e NEWSAPI_KEY \
  ghcr.io/mutablelogic/go-llm:latest \
  chat claude-3-5-haiku-20241022

Programmatic Usage

See the documentation here for integration into your own Go programs. To create an Ollama agent,

import (
  "github.com/mutablelogic/go-llm/pkg/ollama"
)

func main() {
  // Create a new agent
  agent, err := ollama.New("https://ollama.com/api/v1/")
  if err != nil {
    panic(err)
  }
  // ...
}

To create an Anthropic agent,

import (
  "github.com/mutablelogic/go-llm/pkg/anthropic"
)

func main() {
  // Create a new agent
  agent, err := anthropic.New(os.Getev("ANTHROPIC_API_KEY"))
  if err != nil {
    panic(err)
  }
  // ...
}

You create a chat session with a model as follows,

import (
  "github.com/mutablelogic/go-llm"
)

func session(ctx context.Context, agent llm.Agent) error {
  // Create a new chat session
  session := agent.Model("claude-3-5-haiku-20241022").Context()

  // Repeat forever
  for {
    err := session.FromUser(ctx, "hello")
    if err != nil {
      return err
    }

    // Print the response
    fmt.Println(session.Text())
  }
}

Contributing & Distribution

This module is currently in development and subject to change. Please do file feature requests and bugs here. The license is Apache 2 so feel free to redistribute. Redistributions in either source code or binary form must reproduce the copyright notice, and please link back to this repository for more information:

go-llm
https://github.com/mutablelogic/go-llm/
Copyright (c) 2025 David Thorpe, All rights reserved.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type Agent

type Agent interface {
	// Return the name of the agent
	Name() string

	// Return the models
	Models(context.Context) ([]Model, error)
}

An LLM Agent is a client for the LLM service

type Attachment

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

Attachment for messages

func ReadAttachment

func ReadAttachment(r io.Reader) (*Attachment, error)

ReadAttachment returns an attachment from a reader object. It is the responsibility of the caller to close the reader.

func (*Attachment) Data

func (a *Attachment) Data() []byte

func (*Attachment) Filename

func (a *Attachment) Filename() string

type Context

type Context interface {
	ContextContent

	// Generate a response from a user prompt (with attachments and
	// other options)
	FromUser(context.Context, string, ...Opt) error

	// Generate a response from a tool, passing the results
	// from the tool call
	FromTool(context.Context, ...ToolResult) error
}

Context is fed to the agent to generate a response

type ContextContent

type ContextContent interface {
	// Return the current session role, which can be system, assistant, user, tool, tool_result, ...
	Role() string

	// Return the current session text, or empty string if no text was returned
	Text() string

	// Return the current session tool calls, or empty if no tool calls were made
	ToolCalls() []ToolCall
}

ContextContent is the content of the last context message

type Err

type Err int

Errors

const (
	ErrSuccess Err = iota
	ErrNotFound
	ErrBadParameter
	ErrNotImplemented
	ErrConflict
)

func (Err) Error

func (e Err) Error() string

func (Err) With

func (e Err) With(args ...interface{}) error

func (Err) Withf

func (e Err) Withf(format string, args ...interface{}) error

type Model

type Model interface {
	// Return the name of the model
	Name() string

	// Return am empty session context object for the model,
	// setting session options
	Context(...Opt) Context

	// Convenience method to create a session context object
	// with a user prompt
	UserPrompt(string, ...Opt) Context

	// Embedding vector generation
	Embedding(context.Context, string, ...Opt) ([]float64, error)
}

An Model can be used to generate a response to a user prompt, which is passed to an agent. The interaction occurs through a session context object.

type Opt

type Opt func(*Opts) error

A generic option type, which can set options on an agent or session

func WithAgent

func WithAgent(agent Agent) Opt

Set agent

func WithAttachment

func WithAttachment(r io.Reader) Opt

Create an attachment

func WithStream

func WithStream(fn func(ContextContent)) Opt

Set chat streaming function

func WithSystemPrompt

func WithSystemPrompt(v string) Opt

Set system prompt

func WithTemperature

func WithTemperature(v float64) Opt

The temperature of the model. Increasing the temperature will make the model answer more creatively.

func WithToolKit

func WithToolKit(toolkit ToolKit) Opt

Set toolkit of tools

func WithTopK

func WithTopK(v uint) Opt

Reduces the probability of generating nonsense. A higher value (e.g. 100) will give more diverse answers, while a lower value (e.g. 10) will be more conservative.

func WithTopP

func WithTopP(v float64) Opt

Works together with top-k. A higher value (e.g., 0.95) will lead to more diverse text, while a lower value (e.g., 0.5) will generate more focused and conservative text.

type Opts

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

set of options

func ApplyOpts

func ApplyOpts(opts ...Opt) (*Opts, error)

ApplyOpts returns a structure of options

func (*Opts) Agents

func (o *Opts) Agents() []Agent

Return the array of registered agents

func (*Opts) Attachments

func (o *Opts) Attachments() []*Attachment

Return attachments

func (*Opts) Get

func (o *Opts) Get(key string) any

Get an option value

func (*Opts) GetBool

func (o *Opts) GetBool(key string) bool

Get an option value as a boolean

func (*Opts) GetDuration

func (o *Opts) GetDuration(key string) time.Duration

Get an option value as a duration

func (*Opts) GetFloat64

func (o *Opts) GetFloat64(key string) float64

Get an option value as a float64

func (*Opts) GetString

func (o *Opts) GetString(key string) string

Get an option value as a string

func (*Opts) GetUint64

func (o *Opts) GetUint64(key string) uint64

Get an option value as an unsigned integer

func (*Opts) Has

func (o *Opts) Has(key string) bool

Has an option value

func (*Opts) Set

func (o *Opts) Set(key string, value any)

Set an option value

func (*Opts) StreamFn

func (o *Opts) StreamFn() func(ContextContent)

Return the stream function

func (*Opts) SystemPrompt

func (o *Opts) SystemPrompt() string

Return the system prompt

func (*Opts) ToolKit

func (o *Opts) ToolKit() ToolKit

Return the set of tools

type Tool

type Tool interface {
	// The name of the tool
	Name() string

	// The description of the tool
	Description() string

	// Run the tool with a deadline and return the result
	// TODO: Change 'any' to ToolResult
	Run(context.Context) (any, error)
}

Definition of a tool

type ToolCall

type ToolCall interface {
	// The tool name
	Name() string

	// The tool identifier
	Id() string

	// Decode the calling parameters
	Decode(v any) error
}

A call-out to a tool

type ToolKit

type ToolKit interface {
	// Register a tool in the toolkit
	Register(Tool) error

	// Return all the tools
	Tools(Agent) []Tool

	// Run the tool calls in parallel and return the results
	Run(context.Context, ...ToolCall) ([]ToolResult, error)
}

ToolKit is a collection of tools

type ToolResult

type ToolResult interface {
	// The call associated with the result
	Call() ToolCall

	// The result, which can be encoded into json
	Value() any
}

Results from calling tools

Directories

Path Synopsis
cmd
agent command
pkg
anthropic
anthropic implements an API client for anthropic (https://docs.anthropic.com/en/api/getting-started)
anthropic implements an API client for anthropic (https://docs.anthropic.com/en/api/getting-started)
newsapi
newsapi implements an API client for NewsAPI (https://newsapi.org/docs)
newsapi implements an API client for NewsAPI (https://newsapi.org/docs)
ollama
ollama implements an API client for ollama https://github.com/ollama/ollama/blob/main/docs/api.md
ollama implements an API client for ollama https://github.com/ollama/ollama/blob/main/docs/api.md

Jump to

Keyboard shortcuts

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