jpf

package module
v0.12.0-beta.1 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2026 License: MIT Imports: 12 Imported by: 6 modules, 7 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Go Ref Unit Tests Integration Tests

Providing essential building blocks and robust LLM interaction interfaces, jpf enables you to craft custom AI solutions without the bloat.

Features

  • Retry and Feedback Handling: Resilient mechanisms for retrying tasks and incorporating feedback into interactions.
  • Customizable Models: Seamlessly integrate LLMs from multiple providers using unified interfaces — OpenAI (Chat Completions or Responses API), Google Gemini, and Anthropic Claude are supported out of the box.
  • Token Usage Tracking: Stay informed of API token consumption for cost-effective development.
  • Stream Responses: Keep your users engaged with responses that are streamed back as they are generated.
  • Easy-to-use Caching: Reduce the calls made to models by composing a caching layer onto an existing model.
  • Out-of-the-box Logging: Simply add logging messages to your models, helping you track down issues.
  • Industry Standard Context Management: All potentially slow interfaces support Go's context.Context for timeouts and cancellation.
  • Rate Limit Management: Compose models together to set local rate limits to prevent API errors.
  • Tool / Function calling: Let your models call tools with static or streamed requests.
  • Agent Framework: Compose a ReAct-style agent on top of any model, complete with tool calling, skills, deferred (async) tool execution, and JSON-serialisable sessions for saving / resuming across process boundaries.
  • MIT License: Use the code for anything, anywhere, for free.

Installation

Install jpf in your Go project via:

go get github.com/JoshPattman/jpf

Learn more about JPF in the Quickstart section.

Quickstart

There are multiple examples available in the examples directory.

Build a model

  • A model is capable of responding to a set of messages, and are the core engine behind all of your AI features.
  • Models are built through composition, adding functionality that runs on your machine.
func BuildModel() jpf.Model {
	// Create a new gpt-4o model attached to the OpenAI API.
	model := models.NewRemote(
		models.OpenAIChatCompletions, // Defines the API format and the default URL (URL can be overriden) - also supports models.OpenAIResponses and models.Google
		"gpt-4o", // Model name on API
		os.Getenv("OPENAI_KEY"), // API key
		models.WithTemperature(0.5) // Optional params - many more are supported
	)
	// Locally rate limit the model calls to 1 every 5 seconds
	model = models.RateLimit(model, rate.NewLimiter(rate.Every(time.Second*5), 1))
	// Make the model retry non-200 requests up to 5 times
	model = models.Retry(model, 5)
	// Cache model requests in memory - file and database are also supported
	cache := caches.NewRAM()
	model = models.Cache(model, cache)
	return model
}

Build a pipeline

  • A pipeline is a wrapper around a model that takes and returns structured data.
  • Pipelines may retry using various strategies when a validation error (attempting to parse the output) occurs.
  • Pipelines are particularly useful when making one / a few calls to an LLM to perform a fixed task, for example:
    • Translate some text
    • Answer a question about some text
    • Summarise a document
// Define the structured data to provide to the pipeline
type TaskInput struct {
	Name string
}
// Define the structured data to read from the pipeline
type TaskOutput struct {
	IsCelebrity bool `json:"is_celebrity"`
}

// Define a custom validator that will not accpet that santa is not a celebrity
type CustomValidator struct{}

func (c *CustomValidator) ValidateParsedResponse(in TaskInput, out TaskOutput) error {
	if strings.ToLower(in.Name) == "santa" && !out.IsCelebrity {
		return errors.New("santa is a celebrity")
	}
	return nil
}

func BuildPipeline(model jpf.Model) jpf.Pipeline[TaskInput, TaskOutput] {
	// Encode the data to system/user prompt pair, where both are a text/template
	encoder := encoders.NewTemplate[TaskInput]("The user will give you a name. Respond with a json object with a single key, 'is_celebrity'.", "{{ .Name }}")
	// Parse the output message into a struct using json
	parser := parsers.NewJson[TaskOutput]()
	// Only provide the text between { and } to the json parser - cut off extra stuff like backticks
	parser = parsers.SubstringJsonObject(parser)
	// When retrying, will provide fedback by simply formatting the error
	feedback := feedbacks.NewErrString()
	// Create a pipeline that retries up to 5 times on parsing or validation errors
	return pipelines.NewFeedbackRetry(
		encoder,
		parser,
		feedback,
		model,
		5,
		pipelines.WithValidator(&CustomValidator{}), // Optional - omit if no further validation is required
	)
}

Use the pipeline

func IsCelebrity(name string) (bool, error) {
	// Realistically in production code, you would not build the models here,
	// instead you would inject them (or at least inject the builders),
	// as this allows for higher testability and customisability.
	model := BuildModel()
	pipeline := BuildPipeline(model)
	// Calling a pipeline gives a result (with the parsed value and usage), and an error
	resp, err := pipeline.Call(context.Background(), TaskInput{name})
	if err != nil {
		return false, err
	}
	fmt.Println(resp.Usage)
	return resp.Result.IsCelebrity, nil
}

Build an agent

  • An agent wraps a model in a ReAct loop, calling tools across multiple turns until it decides it is done.
  • Give it a []agents.Tool, each with a jpf.ToolSchema describing it to the model, and a Call that runs it.
  • Leaving a tool's Call as nil defers it instead of running it inline - the agent pauses and hands you back the pending calls (via agent.CurrentDeferredToolCalls()) to resolve however you like (e.g. a background job), then you Resume it with the results. See the deferred-agent example for a full save / resume flow.
  • An agent's session (prompts, message history, active skills, pending deferred calls) can be round-tripped through JSON with agents.AgentSessionDTO, so an agent can be persisted and picked back up by a different process.
  • Skills (agent.SetSkillCatalogue) are optional blocks of context an agent can activate / deactivate for itself via built-in tools, so you can offer it extra guidance without bloating every request with all of it up front.
func BuildAgent(model jpf.Model) *agents.Agent {
	agent := agents.NewAgent(model)
	agent.SetToolCatalogue([]agents.Tool{
		{
			Schema: jpf.ToolSchema{
				Name:        "ping_user",
				Description: "Ping the user, only use when asked to ping",
				Args:        nil,
			},
			Call: func(_ context.Context, m map[string]any) (string, error) {
				fmt.Println("PING")
				return "the user has been pinged", nil
			},
		},
	})
	return agent
}

Run the agent

func RunAgent(agent *agents.Agent) {
	// Run drives the agent until it stops calling tools, hits its iteration
	// limit, or defers a tool call. The callback is fired for every message
	// added to the conversation along the way.
	err := agent.Run(
		context.Background(),
		"Ping me",
		func(m jpf.Message) { fmt.Printf("%v\n", m) },
	)
	if err != nil {
		panic(err)
	}
}

FAQ

  • I want to change my model's temperature/structured output/output tokens/... after I have built it!
    • The intention is to provide functions that need to use an LLM with a builder function instead of a built object. This way, you can use the builder function multiple times with different parameters.
    • Take a look at the examples to see this concept.
    • This design decision was made as it prevents you from injecting unnecessary LLM-related data into business logic.
  • Why does this not support MCP tools on the OpenAI API / Other advanced API features?
    • Relying on API features like MCP tools (and full API agents), or vector stores is not ideal for two reasons: (a) it makes it harder to move between API/model providers (b) it gives you less flexibility and control.
    • These features are not particularly hard to add locally, so you should aim to do so to ensure your application is as robust as possible to API change.
    • If a way to abstract the advanced feature such that it becomes provider-agnostic is found, adding it into JPF will be considered.

Author

Developed by Josh Pattman. Learn more at GitHub.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrInvalidResponse = errors.New("llm produced an invalid response")
)

Functions

This section is empty.

Types

type Agent

type Agent interface {
	Session() AgentSession
	SetSession(AgentSession)
	SetMaxIterations(int)
	SetToolCatalogue([]Tool)
	SetSkillCatalogue([]Skill)
	Run(context.Context, string, ...AgentResponseOpt) error
	Resume(context.Context, []DeferredCallResult, ...AgentResponseOpt) error
}

type AgentResponseKwargs

type AgentResponseKwargs struct {
	Streamer AgentStreamer
}

func GetAgentResponseKwargs

func GetAgentResponseKwargs(opts []AgentResponseOpt) AgentResponseKwargs

type AgentResponseOpt

type AgentResponseOpt func(*AgentResponseKwargs)

func WithStreamActions

func WithStreamActions(streamer AgentStreamer) AgentResponseOpt

type AgentSession

type AgentSession struct {
	// The prompt that tells the agent how to interact with the agent loop and react loop,
	// usually does not need to be changed.
	AgentPrompt string
	// The prompt telling the agent specifically about its task,
	// if not specified will tell the agent to be a generalist.
	TaskPrompt string
	// The prompt telling the agent how to act / speak,
	// if not specified will speak neutrally and refer to itself as AI Assistant.
	PersonalityPrompt string
	// The messages, excluding system and other special messages.
	CoreMessages []Message
	// The current tool calls that have been deferred, with their validated args.
	CurrentDeferredToolCalls []DeferredToolCall
	// The names of the skills that should currently be active.
	ActiveSkillNames []string
}

An agent session describes the state of an agent at the current point in time, avoiding any specific logic or details of skills.

func DefaultAgentSession

func DefaultAgentSession() AgentSession

func (AgentSession) Clone

func (a AgentSession) Clone() AgentSession

type AgentStreamer

type AgentStreamer interface {
	OnMessageComplete(Message)
}

type AssistantMessage added in v0.10.0

type AssistantMessage struct {
	Content   string
	ToolCalls []ToolCall
}

AssistantMessage represents a message from the model to the user.

func (AssistantMessage) Eq added in v0.10.0

func (m AssistantMessage) Eq(other Message) bool

func (AssistantMessage) String added in v0.10.0

func (m AssistantMessage) String() string

type DeferredCallResult

type DeferredCallResult struct {
	CallID  string
	Content string
	Err     error
}

DeferredCallResult is what results from your code (not the agent framework) calling the tool.

type DeferredToolCall

type DeferredToolCall struct {
	ToolName string
	CallID   string
	Args     ToolArgs
}

DeferredToolCall describes a call to a named tool that the agent framework cannot run, so it has deferred to your code.

type DeveloperMessage added in v0.10.0

type DeveloperMessage struct {
	Content string
}

DeveloperMessage represents a message from the developer (basically system) to the model.

func (DeveloperMessage) Eq added in v0.10.0

func (m DeveloperMessage) Eq(other Message) bool

func (DeveloperMessage) String added in v0.10.0

func (m DeveloperMessage) String() string

type Encoder added in v0.9.0

type Encoder[T any] interface {
	BuildInputMessages(T) ([]Message, error)
}

Encoder encodes a structured piece of data into a set of messages for an LLM.

type FeedbackGenerator added in v0.6.0

type FeedbackGenerator interface {
	FormatFeedback(AssistantMessage, error) string
}

FeedbackGenerator takes an error and converts it to a piece of text feedback to send to the LLM.

type ImageAttachment added in v0.7.0

type ImageAttachment struct {
	Source image.Image
}

ImageAttachment is an image that is attached as additional information to a message.

func (*ImageAttachment) ToBase64Encoded added in v0.7.0

func (i *ImageAttachment) ToBase64Encoded(useCompression bool) (string, error)

type Message

type Message interface {
	String() string
	Eq(Message) bool
	// contains filtered or unexported methods
}

Message is a sum type of the different messages that can be sent to Models.

type Model

type Model interface {
	// Responds to a set of input messages.
	Respond(context.Context, []Message, ...ModelResponseOpt) (ModelResponse, error)
}

Model defines an interface to an LLM.

type ModelLogger added in v0.7.0

type ModelLogger interface {
	ModelLog(ModelLoggingInfo) error
}

ModelLogger specifies a method of logging a call to a model.

type ModelLoggingInfo added in v0.6.0

type ModelLoggingInfo struct {
	InputMessages []Message
	ResultMessage AssistantMessage
	Usage         Usage
	Err           error
	Duration      time.Duration
}

ModelLoggingInfo contains all information about a model interaction to be logged. It includes input messages, output messages, usage statistics, and any error that occurred.

type ModelResponse added in v0.8.0

type ModelResponse struct {
	// The response to the input messages.
	Message AssistantMessage
	// The usage of making this call.
	// This may be the sum of multiple LLM calls.
	Usage Usage
}

func (ModelResponse) IncludingUsage added in v0.8.0

func (r ModelResponse) IncludingUsage(u Usage) ModelResponse

Utility to include another usage object in this response object

func (ModelResponse) OnlyUsage added in v0.8.0

func (r ModelResponse) OnlyUsage() ModelResponse

Utility to allow you to return the usage but 0 value messages when an error occurs.

type ModelResponseCache added in v0.6.0

type ModelResponseCache interface {
	GetCachedResponse(ctx context.Context, salt string, inputs []Message) (bool, AssistantMessage, error)
	SetCachedResponse(ctx context.Context, salt string, inputs []Message, out AssistantMessage) error
}

type ModelResponseKwargs added in v0.10.0

type ModelResponseKwargs struct {
	Streamer     ModelStreamer
	OutputFormat any
	ToolSchemas  []ToolSchema
}

func GetModelResponseKwargs added in v0.10.0

func GetModelResponseKwargs(opts ...ModelResponseOpt) ModelResponseKwargs

type ModelResponseOpt added in v0.10.0

type ModelResponseOpt func(*ModelResponseKwargs)

func WithOutputFormat added in v0.10.0

func WithOutputFormat(format any) ModelResponseOpt

Set the output format (structured output). This should be a struct, as it will be processed into the correct API model output format by the model itself.

func WithStreamResponse added in v0.9.0

func WithStreamResponse(streamer ModelStreamer) ModelResponseOpt

Stream the model's response to the streamer. This will override any previously set streamers.

func WithToolSchemas added in v0.10.0

func WithToolSchemas(schemas ...ToolSchema) ModelResponseOpt

Add the provided tool schemas (additive, not replace) to the model. If there is at least one tool schema, tool calling will be enabled, so the model needs to support tool calling in this case.

type ModelStreamer added in v0.10.0

type ModelStreamer interface {
	OnMessageBegin()
	OnMessageText(text string)
	OnMessageReset()
}

type Parser added in v0.9.0

type Parser[U any] interface {
	ParseResponseText(string) (U, error)
}

Parser converts the LLM response into a structured piece of output data. When the LLM response is invalid, it should return ErrInvalidResponse (or an error joined on that).

type Pipeline added in v0.9.0

type Pipeline[T, U any] interface {
	Call(context.Context, T) (PipelineResponse[U], error)
}

Pipeline transforms input of type T into output of type U using an LLM. It handles the encoding of input, interaction with the LLM, and decoding of output.

type PipelineResponse added in v0.10.0

type PipelineResponse[U any] struct {
	// The parsed and validated result.
	Result U
	// The usage of making this call.
	// This may be the sum of multiple LLM calls.
	Usage Usage
}

func (PipelineResponse[U]) IncludingUsage added in v0.10.0

func (r PipelineResponse[U]) IncludingUsage(u Usage) PipelineResponse[U]

Utility to include another usage object in this response object

func (PipelineResponse[U]) OnlyUsage added in v0.10.0

func (r PipelineResponse[U]) OnlyUsage() PipelineResponse[U]

Utility to allow you to return the usage but 0 value messages when an error occurs.

type Skill

type Skill struct {
	Name        string
	Description string
	Content     string
}

type SystemMessage added in v0.10.0

type SystemMessage struct {
	Content string
}

SystemMessage represents a message from the system to the model, to set up its task, personality.

func (SystemMessage) Eq added in v0.10.0

func (m SystemMessage) Eq(other Message) bool

func (SystemMessage) String added in v0.10.0

func (m SystemMessage) String() string

type Tool

type Tool struct {
	// How should the LLM call the tool?
	Schema ToolSchema
	// How should the agent framework run the tool.
	// If not specified, the agent framework will break the loop and defer.
	Call func(context.Context, ToolArgs) (ToolResult, error)
}

Tool describes a tool that is available to the agent, encompassing both directly executable and deferred tools.

type ToolArgs

type ToolArgs map[string]any

ToolArgs are the arguments an LLM has tried to call a tool with.

func (ToolArgs) AlignWithSchema

func (args ToolArgs) AlignWithSchema(schema ToolSchema) error

Takes the raw arguments (from json decoding) and modifies / validates them in-place to make them work for the schema. For example, converts floats to ints when the schema specifies int. Does NOT check for extra args the llm supplied that were not asked for.

func (ToolArgs) Clone

func (args ToolArgs) Clone() ToolArgs

func (ToolArgs) OptionalBool

func (args ToolArgs) OptionalBool(key string, defaultVal bool) (bool, bool)

func (ToolArgs) OptionalFloat

func (args ToolArgs) OptionalFloat(key string, defaultVal float64) (float64, bool)

func (ToolArgs) OptionalInt

func (args ToolArgs) OptionalInt(key string, defaultVal int) (int, bool)

func (ToolArgs) OptionalString

func (args ToolArgs) OptionalString(key string, defaultVal string) (string, bool)

func (ToolArgs) RequiredBool

func (args ToolArgs) RequiredBool(key string) bool

func (ToolArgs) RequiredFloat

func (args ToolArgs) RequiredFloat(key string) float64

func (ToolArgs) RequiredInt

func (args ToolArgs) RequiredInt(key string) int

func (ToolArgs) RequiredString

func (args ToolArgs) RequiredString(key string) string

type ToolCall added in v0.10.0

type ToolCall struct {
	ID   string
	Tool string
	Args ToolArgs
}

type ToolParam

type ToolParam struct {
	Name        string
	Description string
	Type        ToolParamType
	Required    bool
}

ToolParam describes a parameter that an agent may pass to a tool.

type ToolParamType

type ToolParamType uint8

ToolParamType defines a type for a parameter of a tool call.

const (
	ToolParamInt ToolParamType = iota
	ToolParamFloat
	ToolParamString
)

type ToolResult

type ToolResult struct {
	Content string
}

ToolResult is what a Tool.Call returns when it is run by the agent framework.

type ToolResultMessage added in v0.10.0

type ToolResultMessage struct {
	CallID string
	Result string
}

ToolResultMessage represents a result from calling a tool.

func (ToolResultMessage) Eq added in v0.10.0

func (m ToolResultMessage) Eq(other Message) bool

func (ToolResultMessage) String added in v0.10.0

func (m ToolResultMessage) String() string

type ToolSchema added in v0.10.0

type ToolSchema struct {
	Name        string
	Description string
	Params      []ToolParam
}

ToolSchema specifies how an LLM should call a tool.

type Usage

type Usage struct {
	InputTokens     int
	OutputTokens    int
	SuccessfulCalls int
	FailedCalls     int
}

Usage defines how many tokens were used when making calls to LLMs.

func (Usage) Add

func (u Usage) Add(u2 Usage) Usage

type UserMessage added in v0.10.0

type UserMessage struct {
	Content string
	Images  []ImageAttachment
}

UserMessage represents a message from the user to the model.

func (UserMessage) Eq added in v0.10.0

func (m UserMessage) Eq(other Message) bool

func (UserMessage) String added in v0.10.0

func (m UserMessage) String() string

type Validator added in v0.9.0

type Validator[T, U any] interface {
	ValidateParsedResponse(T, U) error
}

Validator takes a parsed LLM response and validates it against the input. When the LLM response is invalid, it should return ErrInvalidResponse (or an error joined on that).

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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