estellm

package module
v0.0.3 Latest Latest
Warning

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

Go to latest
Published: Mar 11, 2025 License: MIT Imports: 30 Imported by: 0

README

estellm

estellm is a tool for describing Agentic Workflow.

GoDoc Go Report Card License

Installation

go get github.com/mashiike/estellm

Usage

The simplest example of a prompt is as follows.

{{ define "config" }}
{
    type: "generate_text",
    description: "This is an example of chain-of-thought (COT) prompting, where the model is guided to think step-by-step to reach a conclusion.", 
    default: true,
    model_provider: "openai",
    model_id: "gpt-4o-mini",
    payload_schema: {
        type: "object",
        properties: {
            numbers: {
                type: "array",
                items: {
                    type: "integer",
                    minimum: 1,
                    maximum: 100
                },
            },
        },
        required: ["numbers"]
    },
}
{{ end }}

You are an excellent calculation agent. Please check if the user's answer is correct.
<role:user/>The sum of the odd numbers in this group will be even: 4, 8, 9, 15, 12, 2, 1.
<role:assistant/>Adding all the odd numbers (9, 15, 1) results in 25. The answer is False.
<role:user/>The sum of the odd numbers in this group will be even: 17, 10, 19, 4, 8, 12, 24.
<role:assistant/>Adding all the odd numbers (17, 19) results in 36. The answer is True.
<role:user/>The sum of the odd numbers in this group will be even: 16, 11, 14, 4, 8, 13, 24.
<role:assistant/>Adding all the odd numbers (11, 13) results in 24. The answer is True.
<role:user/>The sum of the odd numbers in this group will be even: 17, 9, 10, 12, 13, 4, 2.
<role:assistant/>Adding all the odd numbers (17, 9, 13) results in 39. The answer is False.
<role:user/>The sum of the odd numbers in this group will be even: {{ .payload.numbers | join ", " }}.
<role:assistant/>Adding all the odd numbers

You can render and execute this prompt by providing the following JSON.

{
  "numbers": [15,5,13,7,1]
}

Rendering this prompt with the above payload will look like this.

$ cat _example/simple/payload.json| go run cmd/estellm/main.go --project _example/simple render
{"time":"2025-03-11T12:19:50.234501+09:00","level":"INFO","msg":"load prompts","prompts":"_example/simple/prompts","includes":"_example/simple/includes"}


You are an excellent calculation agent. Please check if the user's answer is correct.
<role:user/>The sum of the odd numbers in this group will be even: 4, 8, 9, 15, 12, 2, 1.
<role:assistant/>Adding all the odd numbers (9, 15, 1) results in 25. The answer is False.
<role:user/>The sum of the odd numbers in this group will be even: 17, 10, 19, 4, 8, 12, 24.
<role:assistant/>Adding all the odd numbers (17, 19) results in 36. The answer is True.
<role:user/>The sum of the odd numbers in this group will be even: 16, 11, 14, 4, 8, 13, 24.
<role:assistant/>Adding all the odd numbers (11, 13) results in 24. The answer is True.
<role:user/>The sum of the odd numbers in this group will be even: 17, 9, 10, 12, 13, 4, 2.
<role:assistant/>Adding all the odd numbers (17, 9, 13) results in 39. The answer is False.
<role:user/>The sum of the odd numbers in this group will be even: 15, 5, 13, 7, 1.
<role:assistant/>Adding all the odd numbers

And you can execute it as follows.

$ cat _example/simple/payload.json| estellm --project _example/simple exec       
{"time":"2025-03-11T12:16:35.504186+09:00","level":"INFO","msg":"load prompts","prompts":"_example/simple/prompts","includes":"_example/simple/includes"}
The odd numbers in the group are 15, 5, 13, 7, and 1. 

Calculating the sum:

15 + 5 + 13 + 7 + 1 = 41.

The sum is 41, which is odd. Therefore, the answer is False.

The command help is as follows.

$ estellm --help
Usage: estellm <command> [flags]

Estellm is a tool for llm agents flow control.

Flags:
  -h, --help                      Show context-sensitive help.
      --log-format="json"         Log format ($LOG_FORMAT)
      --[no-]color                Enable color output
      --debug                     Enable debug mode ($DEBUG)
      --ext-var=KEY=VALUE;...     External variables external string values for Jsonnet ($EXT_VAR)
      --ext-code=KEY=VALUE;...    External code external string values for Jsonnet ($EXT_CODE)
      --project="./"              Project directory ($ESTELLM_PROJECT)
      --prompts="./prompts"       Prompts directory ($ESTELLM_PROMPTS)
      --includes="./includes"     Includes directory ($ESTELLM_INCLUDES)

Commands:
  exec [<prompt-name>] [flags]
    Execute the estellm

  render [<prompt-name> [<target>]] [flags]
    Render prompt/config the estellm

  docs [flags]
    Show agents documentation

  version [flags]
    Show version

Run "estellm <command> --help" for more information on a command.

Advanced Usage

For more details, refer to the prompts in Advanced Usage. This example represents the following workflow.

flowchart TD
    A0[genimage]
    A1[genimage_prompt]
    A2[question]
    A3[sdxl]
    A4{selector}
    A5[standard]
    A6[thinking]
    A7[weather]
    A1 --> A0
    A2 -.->|tool_call| A7
    A4 --> A1
    A4 --> A3
    A4 --> A5
    A4 --> A6
    A5 -.->|tool_call| A7
    A6 -.->|tool_call| A7

You can generate this diagram with the following command.

$estellm --project _example/advanced docs
ref Template Function

One of the powerful features of estellm is the ability to coordinate execution between prompts. Let's take the following two prompts as an example.

_example/advanced/prompts/genimage_prompt.md

{{ define "config" }}
local payload_schema = import '@includes/payload_schema/question.libsonnet';
{
    type: "generate_text",
    description: "This agent is used for image generation purposes. If the question indicates the intention to generate an image, use this agent to generate the image.", 
    model_provider: "bedrock",
    model_id: "anthropic.claude-3-5-sonnet-20241022-v2:0",
    payload_schema: payload_schema,
    depends_on: ["selector"],
}
{{ end }}

Your task is to interpret the user's question and output a prompt to generate an appropriate image.
Follow the rules below for outputting the prompt.
<rule>
  * The prompt must be output in English.
  * The prompt must be within 4000 characters. There are no exceptions.
  * The prompt must include the following elements:
    * Image quality, subject information
    * If it is a person, information about clothing, hairstyle, expression, accessories, etc.
    * Information about the art style
    * Information about the background
    * Information about the composition
    * Information about lighting and filters
</rule>
Start the prompt immediately without any preamble.
<role:user/> {{ .payload.question }}

_example/advanced/prompts/genimage_prompt.md

{{ define "config" }}
{
    type: "generate_image", 
    model_provider: "openai",
    model_id: "dall-e-3",
    description: "This agent generates images using DALL-E 3."
}
{{ end }}

{{ (ref `genimage_prompt`).result }}

By using the ref template function, estellm interprets the dependencies of these prompts and executes them in the correct order.

$ cat _example/advanced/payload_generate_image.json| go run cmd/estellm/main.go --project _example/advanced exec genimage_prompt
{"time":"2025-03-11T14:09:48.135067+09:00","level":"INFO","msg":"load prompts","prompts":"_example/advanced/prompts","includes":"_example/advanced/includes"}
<prompt type="provided">(photorealistic, highly detailed) A vibrant red apple with smooth, glossy skin, displaying perfect ripeness, slight natural variations in color, small white speckles, (masterful photography, 8k resolution), sitting on a minimalist white surface, soft side lighting creating gentle shadows and highlights, macro photography composition with shallow depth of field, slight bokeh effect in background, natural daylight streaming from the left side, subtle reflection on the surface, ultra-sharp focus on the apple's texture, color grading emphasizing deep reds and natural tones</prompt><prompt type="revised">A photorealistic image in 8k resolution showing a vibrant red apple with glossy, ripe skin. The surface of the apple has slight natural variations in color, complemented by small white speckles. The apple is placed on a minimalist white surface, with soft side lighting creating gentle shadows and highlights. The composition takes on the style of macro photography, with a shallow depth of field and a slight bokeh effect in the background. Natural daylight is streaming from the left side, creating a subtle reflection on the surface. The focus is ultra-sharp on the apple's texture, while the color grading emphasizes the deep reds and natural tones.</prompt>
![binary](generated/pReJ0mToYt.png)

The generated image is usually saved in the generated directory. You can change this with the --file-output flag.

The contents of the ref template function are as follows.

{
  "config": {
    "dependents": 。
      "fuga"
    ],
    "description": "[this is a privious agent description]",
    "type": "constant"
    //... and more 
  },
  "result": {
    "_raw": "\n\n[This is a privious agent response]\n\n"
    // if json response, parsed key-value pairs are here
  }
}

.config contains the parsed JSON data of the referenced prompt. .result contains the execution result.

agent types

estellm supports multiple types of agents.

generate_text

The most basic agent that generates text using LLM.

{{ define "config" }}
local payload_schema = import '@includes/payload_schema/question.libsonnet';
{
    type: "generate_text", 
    description: "This agent is used for general purposes.",
    model_provider: "openai",
    model_id: "gpt-4o-mini",
    payload_schema: payload_schema,
    tools: [
        "weather"
    ],
}
{{ end }}

You are an AI agent that answers user questions politely. Please answer the user's question.
<role:user/> {{ .payload.question }}

In the config section, specify the model to use with model_provider and model_id. Specify the input data schema with payload_schema. You can also specify other prompts as tools with tools if they support Function Calling. The config section can be written in jsonnet. Paths can be imported using aliases like @includes and @prompts.

generate_image

An image generation agent that generates images using models like SDXL or DALL-E.

{{ define "config" }}
{
    type: "generate_image", 
    model_provider: "bedrock",
    model_id: "stability.stable-diffusion-xl-v1",
}
{{ end }}

{
  "prompt":"1 girl,standing pose,cute,cute eyes,detailed hair,anime,highlight hair,front sun light,beautiful hair,illustration,face up,smile,white teeth, school uniform, blue ribbon,gentle smiling expression of a woman,black hair,break,Blue eyes, acing front,",
  "negative_prompt": "worst quality,ugly,bad anatomy,jpeg artifacts"
}
  • The type of prompt required by the image generation AI depends on the target.
decision

A decision-making agent. It generates JSON using LLM according to the specified prompt and then interprets the JSON to decide which agent to execute next.

{{ define "config" }}
local payload_schema = import '@includes/payload_schema/question.libsonnet';
{
    type: "decision",
    default: true, 
    model_provider: "bedrock",
    model_id: "anthropic.claude-3-haiku-20240307-v1:0",
    payload_schema: payload_schema, 
    fallback_agent: "standard",
    fallback_threashold: 0.5,
    description: "Analyze the user's question and select the appropriate agent."
}
{{ end }}

Your task is to analyze the user's question and select the appropriate agent.

The answer should be in JSON format according to the schema below.
<output_schema>
{{ decisionSchema (dependentNames) | toJson }}
</output_schema>
Please write the reasoning in English.

The available agents are as follows.
<agents>
{{- range $i, $v :=  dependentNames}}
{{- $conf := (get (dependents) $v).config }}
    <agent name="{{ $v }}"> {{ $conf.description }} </agent>
{{- end }}
</agents>

Start the answer immediately without any preamble and output only the correct JSON.
<role:user/> {{ .payload | toJson }}

This agent uses functions like decisionSchema, dependents, and dependentNames to construct the prompt. dependents returns a slice with the same content as ref for those dependent on this prompt. dependentNames returns a slice of the names of the prompts dependent on this prompt. decisionSchema takes a []string of choices and returns the JSON schema expected by this agent.

By writing the JSON according to decisionSchema and the policy on how to select, you can use LLM to make decisions.

constant

Outputs the rendered content as is. It is intended to be used at workflow merge points.

{{ define "config" }}
{
    type: "constant", 
    description: "Fetches weather information.",
    payload_schema: {
        type: "object",
        properties: {
            location: { 
                type: "string",
                example: "Tokyo",
                description: "The name of the location to fetch the weather for",
            },
        },
        required: ["location"],
    },   
}
{{ end }}

{{- if eq .payload.location "Tokyo" -}}
Cloudy
{{- else -}}
Sunny
{{- end -}}

Usage (as a library)

package main

import (
	"context"
	"embed"
	"log"
	"os"

	"github.com/mashiike/estellm"
	_ "github.com/mashiike/estellm/agent/gentext"
	_ "github.com/mashiike/estellm/provider/openai"
)

//go:embed prompts
var promptsFS embed.FS

func main() {
	ctx := context.Background()
	mux, err := estellm.NewAgentMux(ctx, estellm.WithPromptsFS(promptsFS))
	if err != nil {
		log.Fatalf("new agent mux: %v", err)
	}
	payload := map[string]interface{}{
		"numbers": []int{15, 5, 13, 7, 1},
	}
	req, err := estellm.NewRequest("simple", payload)
	if err != nil {
		log.Fatalf("new request: %v", err)
	}
	w := estellm.NewTextStreamingResponseWriter(os.Stdout)
	if err := mux.Execute(ctx, req, w); err != nil {
		log.Fatalf("execute: %v", err)
	}
}

You can also implement Agent and ModelProvider independently.

type MyAgent struct {
	estellm.Agent 
}

estellm.RegisterAgent("myagent", func(ctx context.Context, p *estellm.Prompt) (estellm.Agent, error) {
	return &MyAgent{}, nil
})
type MyModelProvider struct {
	estellm.ModelProvider 
}

estellm.RegisterModelProvider("mymodelprovider", &MyModelProvider{})

License

MIT

Documentation

Index

Constants

View Source
const (
	RoleUser      = "user"
	RoleAssistant = "assistant"
)
View Source
const (
	PartTypeText      = "text"
	PartTypeBinary    = "binary"
	PartTypeReasoning = "reasoning"
)

Variables

View Source
var (
	ErrInvalidMessageRole    = errors.New("invalid message role")
	ErrInvalidMessageContent = errors.New("invalid message content")
)
View Source
var (
	ErrModelProviderNameEmpty = errors.New("model provider name is empty")
	ErrModelNotFound          = errors.New("model not found")
)
View Source
var (
	ErrInvalidConfig          = errors.New("invalid config")
	ErrAgentTypeEmpty         = errors.New("agent type is empty")
	ErrAgentAlreadyRegistered = errors.New("agent already registered")
	ErrAgentTypeNotFound      = errors.New("agent type not found")
)

Errors returned by the registry.

View Source
var (
	ErrTemplateBlockNotFound = fmt.Errorf("template block not found")
)
View Source
var Version = "v0.0.0"

Functions

func ConfigLoadPhaseTemplateFuncs

func ConfigLoadPhaseTemplateFuncs(reg *Registry) template.FuncMap

ConfigLoadPhaseTemplateFuncs returns the template functions for the config load phase.

func FinishReasonStrings

func FinishReasonStrings() []string

FinishReasonStrings returns a slice of all String values of the enum

func PreRenderPhaseTemplateFuncs

func PreRenderPhaseTemplateFuncs(reg *Registry, cfg *Config) template.FuncMap

func PromptExecutionPhaseTemplateFuncs

func PromptExecutionPhaseTemplateFuncs(p *Prompt, req *Request) template.FuncMap

func RegisterAgent

func RegisterAgent(name string, f NewAgentFunc) error

RegisterAgent registers a new agent. to the default registry.

func RegisterModelProvider

func RegisterModelProvider(name string, provider ModelProvider) error

func ResponseWriterToWriter

func ResponseWriterToWriter(w ResponseWriter) io.Writer

func SetAgentMarmaidNodeWrapper

func SetAgentMarmaidNodeWrapper(name string, f func(string) string) error

func SetAgentTemplateFuncs

func SetAgentTemplateFuncs(name string, funcs template.FuncMap) error

SetAgentTemplateFuncs sets template functions for the agent type.

func SetNextAgents

func SetNextAgents(w ResponseWriter, agents ...string)

func UserModelProviderMiddlewares

func UserModelProviderMiddlewares(middlewares ...func(ModelProvider) ModelProvider)

Types

type Agent

type Agent interface {
	Execute(ctx context.Context, req *Request, w ResponseWriter) error
}

type AgentFunc

type AgentFunc func(ctx context.Context, req *Request, w ResponseWriter) error

func (AgentFunc) Execute

func (f AgentFunc) Execute(ctx context.Context, req *Request, w ResponseWriter) error

type AgentMux

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

func NewAgentMux

func NewAgentMux(ctx context.Context, optFns ...NewAgentMuxOption) (*AgentMux, error)

func (*AgentMux) Execute

func (mux *AgentMux) Execute(ctx context.Context, req *Request, w ResponseWriter) error

func (*AgentMux) Render

func (mux *AgentMux) Render(ctx context.Context, req *Request) (string, error)

func (*AgentMux) RenderBlock

func (mux *AgentMux) RenderBlock(ctx context.Context, blockName string, req *Request) (string, error)

func (*AgentMux) RenderConfig

func (mux *AgentMux) RenderConfig(_ context.Context, name string, isJsonnet bool) (string, error)

func (*AgentMux) ToMarkdown

func (mux *AgentMux) ToMarkdown() string

func (*AgentMux) Use

func (mux *AgentMux) Use(middleware ...func(next Agent) Agent)

func (*AgentMux) Validate

func (mux *AgentMux) Validate() error

type AgentTool

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

func NewAgentTool

func NewAgentTool(name, description string, inputSchema map[string]any, agent Agent) *AgentTool

func (*AgentTool) Call

func (t *AgentTool) Call(ctx context.Context, input any, w ResponseWriter) error

func (*AgentTool) Description

func (t *AgentTool) Description() string

func (*AgentTool) InputSchema

func (t *AgentTool) InputSchema() map[string]any

func (*AgentTool) Name

func (t *AgentTool) Name() string

type BatchResponseWriter

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

func NewBatchResponseWriter

func NewBatchResponseWriter() *BatchResponseWriter

func (*BatchResponseWriter) Finish

func (w *BatchResponseWriter) Finish(reason FinishReason, msg string) error

func (*BatchResponseWriter) Metadata

func (w *BatchResponseWriter) Metadata() metadata.Metadata

func (*BatchResponseWriter) Response

func (w *BatchResponseWriter) Response() *Response

func (*BatchResponseWriter) WritePart

func (w *BatchResponseWriter) WritePart(parts ...ContentPart) error

func (*BatchResponseWriter) WriteRole

func (w *BatchResponseWriter) WriteRole(role string) error

type Config

type Config struct {
	Raw              string            `json:"-"`
	PromptPath       string            `json:"-"`
	Enabled          *bool             `json:"enabled"`
	Default          bool              `json:"default"`
	Description      string            `json:"description"`
	Name             string            `json:"name"`
	Type             string            `json:"type"`
	DependsOn        []string          `json:"depends_on"`
	PayloadSchema    map[string]any    `json:"payload_schema,omitempty"`
	Tools            []string          `json:"tools,omitempty"`
	RequestMetadata  metadata.Metadata `json:"request_metadata,omitempty"`
	ResponseMetadata metadata.Metadata `json:"response_metadata,omitempty"`
	// contains filtered or unexported fields
}

func (*Config) AppendDependents

func (cfg *Config) AppendDependents(dependents ...string)

func (*Config) AppendDependsOn

func (cfg *Config) AppendDependsOn(dependsOn ...string)

func (*Config) Clone

func (cfg *Config) Clone() *Config

func (*Config) Decode

func (cfg *Config) Decode(v any) error

func (*Config) Dependents

func (cfg *Config) Dependents() []string

func (*Config) RawAsMap

func (cfg *Config) RawAsMap() map[string]any

type ContentPart

type ContentPart struct {
	Type     string `json:"type"`
	Text     string `json:"text,omitempty"`
	MIMEType string `json:"mime_type,omitempty"`
	Data     []byte `json:"data,omitempty"`
}

func BinaryPart

func BinaryPart(mimeType string, data []byte) ContentPart

func ParseSrcURL

func ParseSrcURL(srcURL string) (ContentPart, error)

func ReasoningPart

func ReasoningPart(text string) ContentPart

func TextPart

func TextPart(text string) ContentPart

type DataValidateError

type DataValidateError struct {
	Result *gojsonschema.Result
}

func (*DataValidateError) Error

func (e *DataValidateError) Error() string

type FinishReason

type FinishReason uint32
const (
	FinishReasonEndTurn FinishReason = iota
	FinishReasonMaxTokens
	FinishReasonStopSequence
	FinishReasonGuardrailIntervened
	FinishReasonContentFiltered
)

func FinishReasonString

func FinishReasonString(s string) (FinishReason, error)

FinishReasonString retrieves an enum value from the enum constants string name. Throws an error if the param is not part of the enum.

func FinishReasonValues

func FinishReasonValues() []FinishReason

FinishReasonValues returns all values of the enum

func (FinishReason) IsAFinishReason

func (i FinishReason) IsAFinishReason() bool

IsAFinishReason returns "true" if the value is listed in the enum definition. "false" otherwise

func (FinishReason) MarshalJSON

func (i FinishReason) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaler interface for FinishReason

func (FinishReason) String

func (i FinishReason) String() string

func (*FinishReason) UnmarshalJSON

func (i *FinishReason) UnmarshalJSON(data []byte) error

UnmarshalJSON implements the json.Unmarshaler interface for FinishReason

type GenerateImageRequest

type GenerateImageRequest struct {
	Metadata    metadata.Metadata `json:"metadata"`
	ModelID     string            `json:"model_id"`
	ModelParams map[string]any    `json:"model_params"`
	System      string            `json:"system"`
	Messages    []Message         `json:"messages"`
}

type GenerateTextRequest

type GenerateTextRequest struct {
	Metadata    metadata.Metadata `json:"metadata"`
	ModelID     string            `json:"model_id"`
	ModelParams map[string]any    `json:"model_params"`
	System      string            `json:"system"`
	Messages    []Message         `json:"messages"`
	Tools       ToolSet           `json:"tools"`
}

type Loader

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

func NewLoader

func NewLoader() *Loader

func (*Loader) ExtCodes

func (l *Loader) ExtCodes(extCodes map[string]string)

func (*Loader) ExtVars

func (l *Loader) ExtVars(extVars map[string]string)

func (*Loader) Includes

func (l *Loader) Includes(fsys fs.FS)

func (*Loader) Load

func (l *Loader) Load(ctx context.Context, fsys fs.FS, promptPath string) (*Prompt, error)

func (*Loader) LoadFS

func (l *Loader) LoadFS(ctx context.Context, fsys fs.FS) (map[string]*Prompt, map[string][]string, error)

func (*Loader) NativeFunctions

func (l *Loader) NativeFunctions(nativeFunctions ...*jsonnet.NativeFunction)

func (*Loader) PromptPathPatterns

func (l *Loader) PromptPathPatterns(patterns []string)

func (*Loader) Registry

func (l *Loader) Registry(reg *Registry)

func (*Loader) TemplateFuncs

func (l *Loader) TemplateFuncs(fmap template.FuncMap)

func (*Loader) ValueGenerator

func (l *Loader) ValueGenerator(gen ValueGenerator)

type Message

type Message struct {
	Role  string        `json:"role"`
	Parts []ContentPart `json:"parts"`
}

type MessageDecoder

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

func NewMessageDecoder

func NewMessageDecoder(r io.Reader) *MessageDecoder

func (*MessageDecoder) Decode

func (d *MessageDecoder) Decode() (string, []Message, error)

type MessageEncoder

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

func NewMessageEncoder

func NewMessageEncoder(w io.Writer) *MessageEncoder

func (*MessageEncoder) Encode

func (e *MessageEncoder) Encode(system string, messages []Message) error

func (*MessageEncoder) EncodeContentPart

func (e *MessageEncoder) EncodeContentPart(part ContentPart) error

func (*MessageEncoder) EncodeMessage

func (e *MessageEncoder) EncodeMessage(msg Message) error

func (*MessageEncoder) Flush

func (e *MessageEncoder) Flush() error

func (*MessageEncoder) NoRole

func (e *MessageEncoder) NoRole()

func (*MessageEncoder) SetBinaryOutputDir

func (e *MessageEncoder) SetBinaryOutputDir(dir string)

func (*MessageEncoder) SkipReasoning

func (e *MessageEncoder) SkipReasoning()

func (*MessageEncoder) TextOnly

func (e *MessageEncoder) TextOnly()

type ModelProvider

type ModelProvider interface {
	GenerateText(ctx context.Context, req *GenerateTextRequest, w ResponseWriter) error
	GenerateImage(ctx context.Context, req *GenerateImageRequest, w ResponseWriter) error
}

func GetModelProvider

func GetModelProvider(ctx context.Context, name string) (ModelProvider, error)

type ModelProviderManager

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

func NewModelProviderManager

func NewModelProviderManager() *ModelProviderManager

func WithModelProviderManager

func WithModelProviderManager(ctx context.Context) (context.Context, *ModelProviderManager)

func (*ModelProviderManager) Clone

func (*ModelProviderManager) Exists

func (m *ModelProviderManager) Exists(name string) bool

func (*ModelProviderManager) Get

func (*ModelProviderManager) List

func (m *ModelProviderManager) List() []string

func (*ModelProviderManager) Register

func (m *ModelProviderManager) Register(name string, provider ModelProvider) error

func (*ModelProviderManager) Use

func (m *ModelProviderManager) Use(middlewares ...func(ModelProvider) ModelProvider)

type NewAgentFunc

type NewAgentFunc func(context.Context, *Prompt) (Agent, error)

type NewAgentMuxOption

type NewAgentMuxOption func(*newAgentMuxOptions)

func WithExtCodes

func WithExtCodes(codes map[string]string) NewAgentMuxOption

func WithExtVars

func WithExtVars(vars map[string]string) NewAgentMuxOption

func WithIncludesFS

func WithIncludesFS(fsys fs.FS) NewAgentMuxOption

func WithLogger

func WithLogger(logger *slog.Logger) NewAgentMuxOption

func WithNativeFunctions

func WithNativeFunctions(functions ...*jsonnet.NativeFunction) NewAgentMuxOption

func WithPromptsFS

func WithPromptsFS(fsys fs.FS) NewAgentMuxOption

func WithRegistry

func WithRegistry(registry *Registry) NewAgentMuxOption

func WithTemplateFuncs

func WithTemplateFuncs(fmap template.FuncMap) NewAgentMuxOption

type Prompt

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

func (*Prompt) Blocks

func (p *Prompt) Blocks() []string

func (*Prompt) Config

func (p *Prompt) Config() *Config

func (*Prompt) Decode

func (p *Prompt) Decode(ctx context.Context, req *Request) (string, []Message, error)

func (*Prompt) DecodeBlock

func (p *Prompt) DecodeBlock(ctx context.Context, blockName string, req *Request) (string, []Message, error)

func (*Prompt) Name

func (p *Prompt) Name() string

func (*Prompt) PreRendered

func (p *Prompt) PreRendered() string

func (*Prompt) Render

func (p *Prompt) Render(ctx context.Context, req *Request) (string, error)

func (*Prompt) RenderBlock

func (p *Prompt) RenderBlock(_ context.Context, blockName string, req *Request) (string, error)

func (*Prompt) SetRelatedPrompts

func (p *Prompt) SetRelatedPrompts(prompts map[string]*Prompt)

type ReasoningMirrorResponseWriter

type ReasoningMirrorResponseWriter struct {
	ResponseWriter
	// contains filtered or unexported fields
}

func NewReasoningMirrorResponseWriter

func NewReasoningMirrorResponseWriter(w ResponseWriter, mirrors ...ResponseWriter) *ReasoningMirrorResponseWriter

func (*ReasoningMirrorResponseWriter) Finish

func (w *ReasoningMirrorResponseWriter) Finish(reason FinishReason, msg string) error

func (*ReasoningMirrorResponseWriter) WritePart

func (w *ReasoningMirrorResponseWriter) WritePart(parts ...ContentPart) error

type Registry

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

Registry is a registry of agents.

func DefaultRegistory

func DefaultRegistory() *Registry

DefaultRegistory returns the default registry.

func NewRegistry

func NewRegistry() *Registry

NewRegistry creates a new registry.

func (*Registry) Exists

func (r *Registry) Exists(name string) bool

Exists returns true if the agent type is registered.

func (*Registry) NewAgent

func (r *Registry) NewAgent(ctx context.Context, p *Prompt) (Agent, error)

NewAgent creates a new agent.

func (*Registry) Register

func (r *Registry) Register(name string, f NewAgentFunc) error

Register registers a new agent.

func (*Registry) SetMarmaidNodeWrapper

func (r *Registry) SetMarmaidNodeWrapper(name string, f func(string) string) error

func (*Registry) SetTemplateFuncs

func (r *Registry) SetTemplateFuncs(name string, funcs template.FuncMap) error

type Request

type Request struct {
	Name              string               `json:"name"`
	Payload           any                  `json:"payload"`
	Metadata          metadata.Metadata    `json:"metadata"`
	PreviousResults   map[string]*Response `json:"previous_results,omitempty"`
	IncludeUpstream   bool                 `json:"include_upstream,omitempty"`
	IncludeDownstream bool                 `json:"include_downstream,omitempty"`
	Tools             ToolSet              `json:"tools,omitempty"`
}

func NewRequest

func NewRequest(name string, payload any) (*Request, error)

func (*Request) Clone

func (r *Request) Clone() *Request

func (*Request) TemplateData

func (r *Request) TemplateData() map[string]any

type Response

type Response struct {
	Metadata      metadata.Metadata `json:"metadata,omitempty"`
	Message       Message           `json:"message,omitempty"`
	FinishReason  FinishReason      `json:"finish_reason,omitempty"`
	FinishMessage string            `json:"finish_message,omitempty"`
	// contains filtered or unexported fields
}

func (*Response) Clone

func (r *Response) Clone() *Response

func (*Response) String

func (r *Response) String() string

type ResponseWriter

type ResponseWriter interface {
	Metadata() metadata.Metadata
	WriteRole(role string) error
	WritePart(parts ...ContentPart) error
	Finish(reason FinishReason, msg string) error
}

type SchemaValueGenerator

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

func NewSchemaValueGenerator

func NewSchemaValueGenerator(r *rand.Rand) *SchemaValueGenerator

func (*SchemaValueGenerator) Generate

func (g *SchemaValueGenerator) Generate(schema map[string]interface{}) (any, error)

type TextStreamingResponseWriter

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

func NewTextStreamingResponseWriter

func NewTextStreamingResponseWriter(w io.Writer) *TextStreamingResponseWriter

func (*TextStreamingResponseWriter) DumpMetadata

func (w *TextStreamingResponseWriter) DumpMetadata()

func (*TextStreamingResponseWriter) Finish

func (w *TextStreamingResponseWriter) Finish(reason FinishReason, msg string) error

func (*TextStreamingResponseWriter) Metadata

func (*TextStreamingResponseWriter) SetBinaryOutputDir

func (w *TextStreamingResponseWriter) SetBinaryOutputDir(dir string)

func (*TextStreamingResponseWriter) SkipReasoning

func (w *TextStreamingResponseWriter) SkipReasoning()

func (*TextStreamingResponseWriter) WritePart

func (w *TextStreamingResponseWriter) WritePart(parts ...ContentPart) error

func (*TextStreamingResponseWriter) WriteRole

func (w *TextStreamingResponseWriter) WriteRole(_ string) error

type Tool

type Tool interface {
	Name() string
	Description() string
	InputSchema() map[string]any
	Call(ctx context.Context, input any, w ResponseWriter) error
}

type ToolSet

type ToolSet []Tool

func (ToolSet) Append

func (ts ToolSet) Append(tools ...Tool) ToolSet

func (ToolSet) MarshalJSON

func (ts ToolSet) MarshalJSON() ([]byte, error)

func (*ToolSet) UnmarshalJSON

func (ts *ToolSet) UnmarshalJSON(_ []byte) error

type ValueGenerator

type ValueGenerator interface {
	Generate(schema map[string]interface{}) (any, error)
}

Directories

Path Synopsis
_example
agent
cmd
interanal
provider

Jump to

Keyboard shortcuts

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