syndicate

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: May 31, 2025 License: Apache-2.0 Imports: 12 Imported by: 0

README ΒΆ

Syndicate SDK Logo

Go Report Card GitHub Workflow Status codecov GoDoc Release

Syndicate

A clean, simple Go SDK for building AI agent applications with LLMs, tools, and workflows.

Eliminate the complexity of managing LLM APIs directly. Perfect for prototypes, MVPs, and applications that need straightforward AI agent integration.

πŸš€ Quick Start

go get github.com/Dieg0Code/syndicate-go
package main

import (
    "context"
    "fmt"
    syndicate "github.com/Dieg0Code/syndicate-go"
    openai "github.com/sashabaranov/go-openai"
)

func main() {
    client := syndicate.NewOpenAIClient("YOUR_API_KEY")

    agent, _ := syndicate.NewAgent(
        syndicate.WithClient(client),
        syndicate.WithName("Assistant"),
        syndicate.WithSystemPrompt("You are a helpful AI assistant."),
        syndicate.WithModel(openai.GPT4),
        syndicate.WithMemory(syndicate.NewSimpleMemory()),
    )

    response, _ := agent.Chat(context.Background(),
        syndicate.WithUserName("User"),
        syndicate.WithInput("Hello! What can you help me with?"),
    )

    fmt.Println(response)
}

✨ Key Features

  • πŸ€– Agent Orchestration: Create agents that work independently or in simple sequential pipelines
  • πŸ› οΈ Tool Integration: Connect agents to external APIs with automatic JSON schema generation
  • πŸ’Ύ Flexible Memory: From simple in-memory to custom database backends
  • πŸ”„ Sequential Workflows: Chain agents for multi-step processing
  • πŸ“ Structured Prompts: Build consistent, maintainable agent instructions
  • ⚑ Clean API: Functional options pattern for readable, maintainable code

🎯 Ideal For

  • βœ… Prototypes & MVPs - Get AI features running quickly
  • βœ… Small to medium applications - Clean integration without overhead
  • βœ… Learning AI development - Simple, well-documented patterns
  • βœ… Custom tool integration - Easy to extend with your APIs
  • βœ… Sequential workflows - Chain agents for multi-step tasks

Not ideal for: Complex branching workflows, high-scale production systems requiring advanced observability, or enterprise-grade orchestration needs.

πŸ“‹ Examples

Single Agent with Tools
// Define your tool schema
type OrderSchema struct {
    Items   []string `json:"items" description:"Items to order" required:"true"`
    Address string   `json:"address" description:"Delivery address" required:"true"`
}

// Create a tool with functional options
tool, _ := syndicate.NewTool(
    syndicate.WithToolName("ProcessOrder"),
    syndicate.WithToolDescription("Process customer orders"),
    syndicate.WithToolSchema(OrderSchema{}),
    syndicate.WithToolExecuteHandler(func(args json.RawMessage) (interface{}, error) {
        var order OrderSchema
        if err := json.Unmarshal(args, &order); err != nil {
            return nil, err
        }
        // Process the order...
        return "Order processed successfully", nil
    }),
)

// Create agent with tool
agent, _ := syndicate.NewAgent(
    syndicate.WithClient(client),
    syndicate.WithName("OrderAgent"),
    syndicate.WithSystemPrompt("You process customer orders."),
    syndicate.WithTools(tool),
    syndicate.WithMemory(syndicate.NewSimpleMemory()),
)
Sequential Multi-Agent Pipeline
// Create specialized agents
orderAgent, _ := syndicate.NewAgent(
    syndicate.WithClient(client),
    syndicate.WithName("OrderProcessor"),
    syndicate.WithSystemPrompt("You validate and process orders."),
    syndicate.WithMemory(syndicate.NewSimpleMemory()),
)

summaryAgent, _ := syndicate.NewAgent(
    syndicate.WithClient(client),
    syndicate.WithName("OrderSummarizer"),
    syndicate.WithSystemPrompt("You create order summaries."),
    syndicate.WithMemory(syndicate.NewSimpleMemory()),
)

// Create sequential pipeline
pipeline, _ := syndicate.NewSyndicate(
    syndicate.WithAgents(orderAgent, summaryAgent),
    syndicate.WithPipeline("OrderProcessor", "OrderSummarizer"),
)

// Execute pipeline
result, _ := pipeline.ExecutePipeline(context.Background(),
    syndicate.WithPipelineUserName("Customer"),
    syndicate.WithPipelineInput("I want 2 pizzas delivered to 123 Main St"),
)
Custom Memory Backend
// Create database-backed memory
func NewDatabaseMemory(db *sql.DB, agentID string) (syndicate.Memory, error) {
    return syndicate.NewMemory(
        syndicate.WithAddHandler(func(msg syndicate.Message) {
            data, _ := json.Marshal(msg)
            db.Exec("INSERT INTO messages (agent_id, data) VALUES (?, ?)", agentID, data)
        }),
        syndicate.WithGetHandler(func() []syndicate.Message {
            rows, _ := db.Query("SELECT data FROM messages WHERE agent_id = ?", agentID)
            var messages []syndicate.Message
            // Parse rows into messages...
            return messages
        }),
    )
}

// Use custom memory
dbMemory, _ := NewDatabaseMemory(db, "agent-123")
agent, _ := syndicate.NewAgent(
    syndicate.WithClient(client),
    syndicate.WithName("PersistentAgent"),
    syndicate.WithMemory(dbMemory),
    // ... other options
)

πŸ—οΈ Architecture

Agent: Individual AI entity with specific capabilities and memory
Tool: External function/API that agents can call
Memory: Conversation storage (in-memory, database, Redis, etc.)
Syndicate: Orchestrator that manages sequential multi-agent workflows
Pipeline: Sequential execution of multiple agents

πŸ“š Advanced Usage

Tool Integration

Tools allow agents to interact with external systems. You can create tools easily using the functional options pattern:

tool, err := syndicate.NewTool(
    syndicate.WithToolName("ToolName"),
    syndicate.WithToolDescription("Tool description"),
    syndicate.WithToolSchema(YourSchema{}),
    syndicate.WithToolExecuteHandler(func(args json.RawMessage) (interface{}, error) {
        // Your implementation here
        return result, nil
    }),
)

Alternatively, you can implement the Tool interface directly:

type Tool interface {
    GetDefinition() ToolDefinition
    Execute(args json.RawMessage) (interface{}, error)
}

The SDK automatically generates JSON schemas from Go structs using reflection and struct tags.

Memory Management

All memory implementations satisfy this interface:

type Memory interface {
    Add(message Message)
    Get() []Message
}
  • Use syndicate.NewSimpleMemory() for development
  • Use syndicate.NewMemory() with handlers for custom backends
Prompt Building

Create structured prompts with the builder, now with comprehensive markdown support:

prompt := syndicate.NewPromptBuilder().
    // Basic sections and text
    CreateSection("Role").
    AddText("Role", "You are a customer service agent.").

    // Formatting options
    CreateSection("Instructions").
    AddHeader("Instructions", "Important Guidelines", 2).
    AddBoldText("Instructions", "Follow these rules carefully:").
    AddBulletItem("Instructions", "Be helpful and professional").
    AddBulletItem("Instructions", "Use clear, concise language").
    AddListItem("Instructions", "Verify customer information first").
    AddListItem("Instructions", "Solve the customer's problem").
    AddBlockquote("Instructions", "Customer satisfaction is our priority").

    // Code examples
    CreateSection("Examples").
    AddText("Examples", "Here's how to greet a customer:").
    AddCodeBlock("Examples", `function greet(name) {
    return "Hello " + name + ", how can I help you today?";
}`, "javascript").

    // Tables and links
    CreateSection("Resources").
    AddLink("Resources", "Customer Knowledge Base", "https://example.com/kb").
    AddHorizontalRule("Resources").
    AddTable("Resources",
        []string{"Resource Type", "URL", "Description"},
        [][]string{
            {"FAQ", "https://example.com/faq", "Frequently asked questions"},
            {"Policy", "https://example.com/policy", "Company policies"},
        }).

    Build()

The PromptBuilder combines XML-style hierarchical structure with markdown formatting for optimal LLM prompting.

Basic table example:

// Basic table example
pb := syndicate.NewPromptBuilder().
    CreateSection("Tables").
    AddText("Tables", "Here's a simple table:").
    AddTable("Tables",
        []string{"Name", "Age", "Role"},  // Headers
        [][]string{                        // Rows
            {"John", "30", "Developer"},
            {"Jane", "28", "Designer"},
            {"Bob", "35", "Manager"},
        })

This produces a markdown table like:

<Tables>
Here's a simple table:
| Name | Age | Role |
| --- | --- | --- |
| John | 30 | Developer |
| Jane | 28 | Designer |
| Bob | 35 | Manager |
</Tables>

πŸ”§ Configuration

Supported LLM Providers: OpenAI, DeepSeek
Go Version: 1.24+
Architecture: Sequential pipelines, simple agent orchestration
Dependencies: Minimal external dependencies

πŸ“– Documentation

πŸ“¦ Dependencies

🀝 Contributing

Contributions welcome! Please read our contributing guidelines and submit issues or pull requests.

πŸ“œ License

Apache License 2.0 - See LICENSE file for details.

Documentation ΒΆ

Overview ΒΆ

Package syndicate provides an SDK for interfacing with OpenAI's API, offering agents that process inputs, manage tool execution, and maintain memory.

Index ΒΆ

Constants ΒΆ

View Source
const (
	RoleSystem    = "system"
	RoleDeveloper = "developer"
	RoleUser      = "user"
	RoleAssistant = "assistant"
	RoleTool      = "tool"
)

Role constants define standard message roles across different providers

View Source
const (
	FinishReasonStop      = "stop"
	FinishReasonLength    = "length"
	FinishReasonToolCalls = "tool_calls"
)

FinishReason constants define standard reasons for completion.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func GenerateRawSchema ΒΆ

func GenerateRawSchema(v any) (json.RawMessage, error)

GenerateRawSchema wraps GenerateSchema and returns the JSON marshalled schema. Before marshalling, it validates the generated schema using ValidateDefinition.

func ValidateDefinition ΒΆ

func ValidateDefinition(def *Definition) error

ValidateDefinition recursively validates the generated JSON Schema definition. It ensures that required fields exist, arrays have items defined, that enum values are not empty, and that if AdditionalProperties is set, it conforms to accepted types (bool, Definition, or *Definition).

Types ΒΆ

type Agent ΒΆ

type Agent interface {
	Chat(ctx context.Context, options ...ChatOption) (string, error)
	GetName() string
}

Agent defines the interface for processing inputs and managing tools.

func NewAgent ΒΆ added in v0.2.0

func NewAgent(options ...AgentOption) (Agent, error)

NewAgent creates a new agent with the provided options.

type AgentOption ΒΆ added in v0.3.0

type AgentOption func(*agent) error

AgentOption defines a function that configures an Agent.

func WithClient ΒΆ added in v0.3.0

func WithClient(client LLMClient) AgentOption

WithClient sets the LLM client for the agent.

func WithDescription ΒΆ added in v0.3.0

func WithDescription(description string) AgentOption

WithDescription sets the description for the agent.

func WithJSONResponseFormat ΒΆ added in v0.3.0

func WithJSONResponseFormat(schemaName string, structSchema any) AgentOption

WithJSONResponseFormat configures the agent to use a JSON schema for response formatting.

func WithMemory ΒΆ added in v0.3.0

func WithMemory(memory Memory) AgentOption

WithMemory sets the memory implementation for the agent.

func WithModel ΒΆ added in v0.3.0

func WithModel(model string) AgentOption

WithModel sets the model for the agent.

func WithName ΒΆ added in v0.3.0

func WithName(name string) AgentOption

WithName sets the name for the agent.

func WithSystemPrompt ΒΆ added in v0.3.0

func WithSystemPrompt(prompt string) AgentOption

WithSystemPrompt sets the system prompt for the agent.

func WithTemperature ΒΆ added in v0.3.0

func WithTemperature(temperature float32) AgentOption

WithTemperature sets the temperature for the agent.

func WithTimeout ΒΆ added in v0.3.0

func WithTimeout(timeout time.Duration) AgentOption

WithTimeout sets the context timeout for API requests.

func WithTool ΒΆ added in v0.3.0

func WithTool(tool Tool) AgentOption

WithTool adds a tool to the agent.

func WithTools ΒΆ added in v0.3.0

func WithTools(tools ...Tool) AgentOption

WithTools adds multiple tools to the agent.

type ChatCompletionRequest ΒΆ

type ChatCompletionRequest struct {
	Model          string           `json:"model"`
	Messages       []Message        `json:"messages"`
	Tools          []ToolDefinition `json:"tools,omitempty"`
	Temperature    float32          `json:"temperature"`
	ResponseFormat *ResponseFormat  `json:"response_format,omitempty"`
}

ChatCompletionRequest represents a unified chat completion request.

type ChatCompletionResponse ΒΆ

type ChatCompletionResponse struct {
	Choices []Choice `json:"choices"`
	Usage   Usage    `json:"usage"`
}

ChatCompletionResponse represents a unified response structure from the LLM.

type ChatOption ΒΆ added in v0.3.0

type ChatOption func(*chatRequest)

ChatOption defines a function that configures a chat request.

func WithAdditionalMessages ΒΆ added in v0.3.0

func WithAdditionalMessages(messages ...[]Message) ChatOption

WithAdditionalMessages adds additional messages to the chat request.

func WithChatTimeout ΒΆ added in v0.3.0

func WithChatTimeout(timeout time.Duration) ChatOption

WithChatTimeout sets a specific timeout for this chat request. Overrides the agent's default timeout for this request only.

func WithImages ΒΆ added in v0.3.0

func WithImages(imageURLs ...string) ChatOption

WithImages sets the image URLs for the chat request.

func WithInput ΒΆ added in v0.3.0

func WithInput(input string) ChatOption

WithInput sets the input text for the chat request.

func WithUserName ΒΆ added in v0.3.0

func WithUserName(userName string) ChatOption

WithUserName sets the user name for the chat request.

type Choice ΒΆ

type Choice struct {
	Message      Message `json:"message"`
	FinishReason string  `json:"finish_reason"`
}

Choice represents a single completion option.

type DataType ΒΆ

type DataType string

DataType represents a JSON data type in the generated schema.

const (
	Object  DataType = "object"
	Number  DataType = "number"
	Integer DataType = "integer"
	String  DataType = "string"
	Array   DataType = "array"
	Null    DataType = "null"
	Boolean DataType = "boolean"
)

Supported JSON data types.

type DeepseekR1Client ΒΆ

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

DeepseekR1Client implementa LLMClient usando el SDK de DeepseekR1.

func (*DeepseekR1Client) CreateChatCompletion ΒΆ

CreateChatCompletion envΓ­a la solicitud de chat a DeepseekR1. Se ignoran tools y ResponseFormat, ya que DeepseekR1 no los soporta.

type Definition ΒΆ

type Definition struct {
	Type                 DataType              `json:"type,omitempty"`
	Description          string                `json:"description,omitempty"`
	Enum                 []string              `json:"enum,omitempty"`
	Properties           map[string]Definition `json:"properties,omitempty"`
	Required             []string              `json:"required,omitempty"`
	Items                *Definition           `json:"items,omitempty"`
	AdditionalProperties any                   `json:"additionalProperties,omitempty"`
}

Definition is a struct for describing a JSON Schema. It includes type, description, enumeration values, properties, required fields, and additional items.

func (*Definition) MarshalJSON ΒΆ

func (d *Definition) MarshalJSON() ([]byte, error)

MarshalJSON provides custom JSON marshalling for the Definition type. It ensures that the Properties map is initialized before marshalling.

type Embedder ΒΆ

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

Embedder is responsible for generating embeddings using the OpenAI API.

func (*Embedder) GenerateEmbedding ΒΆ

func (e *Embedder) GenerateEmbedding(ctx context.Context, data string, model ...openai.EmbeddingModel) ([]float32, error)

GenerateEmbedding generates an embedding for the provided data string. It accepts an optional embedding model; if provided, that model overrides the default. Returns a slice of float32 representing the embedding vector or an error if any.

type EmbedderBuilder ΒΆ

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

EmbedderBuilder provides a fluent API to configure and build an Embedder instance.

func NewEmbedderBuilder ΒΆ

func NewEmbedderBuilder() *EmbedderBuilder

NewEmbedderBuilder initializes a new EmbedderBuilder with default settings.

func (*EmbedderBuilder) Build ΒΆ

func (b *EmbedderBuilder) Build() (*Embedder, error)

Build constructs the Embedder instance based on the current configuration. Returns an error if the required OpenAI client is not configured.

func (*EmbedderBuilder) SetClient ΒΆ

func (b *EmbedderBuilder) SetClient(client *openai.Client) *EmbedderBuilder

SetClient configures the OpenAI client for the Embedder.

func (*EmbedderBuilder) SetModel ΒΆ

SetModel configures the embedding model to be used by the Embedder.

type ExecuteAgentOption ΒΆ added in v0.3.0

type ExecuteAgentOption func(*executeAgentRequest)

ExecuteAgentOption defines options for executing a single agent.

func WithExecuteAdditionalMessages ΒΆ added in v0.3.0

func WithExecuteAdditionalMessages(messages ...[]Message) ExecuteAgentOption

WithExecuteAdditionalMessages adds additional messages for agent execution.

func WithExecuteImages ΒΆ added in v0.3.0

func WithExecuteImages(imageURLs ...string) ExecuteAgentOption

WithExecuteImages sets image URLs for agent execution.

func WithExecuteInput ΒΆ added in v0.3.0

func WithExecuteInput(input string) ExecuteAgentOption

WithExecuteInput sets the input for agent execution.

func WithExecuteUserName ΒΆ added in v0.3.0

func WithExecuteUserName(userName string) ExecuteAgentOption

WithExecuteUserName sets the user name for agent execution.

func WithGlobalHistoryContext ΒΆ added in v0.3.0

func WithGlobalHistoryContext() ExecuteAgentOption

WithGlobalHistoryContext includes global history in the agent execution.

type JSONSchema ΒΆ

type JSONSchema struct {
	Name   string          `json:"name"`
	Schema json.RawMessage `json:"schema"`
	Strict bool            `json:"strict"`
}

JSONSchema defines the structure for responses in JSON.

type LLMClient ΒΆ

type LLMClient interface {
	CreateChatCompletion(ctx context.Context, req ChatCompletionRequest) (ChatCompletionResponse, error)
}

LLMClient defines the interface for interacting with LLM providers.

func NewDeepseekR1Client ΒΆ

func NewDeepseekR1Client(apiKey, baseURL string) LLMClient

NewDeepseekR1Client crea un nuevo cliente para DeepseekR1. Recibe la API key y el baseURL (por ejemplo, "https://models.inference.ai.azure.com/").

func NewOpenAIAzureClient ΒΆ

func NewOpenAIAzureClient(apiKey string) LLMClient

NewOpenAIAzureClient creates an LLMClient for Azure using Azure provider-specific settings. It configures the client with Azure-specific settings.

func NewOpenAIClient ΒΆ

func NewOpenAIClient(apiKey string) LLMClient

NewOpenAIClient creates a new LLMClient using the provided API key with the standard OpenAI endpoint.

type Memory ΒΆ

type Memory interface {
	// Add appends a message to the memory.
	Add(message Message)
	// Get returns all stored chat messages.
	Get() []Message
}

Memory defines the interface for managing a history of chat messages.

func NewMemory ΒΆ added in v0.3.0

func NewMemory(options ...MemoryOption) (Memory, error)

NewMemory creates a custom Memory implementation using functional options. Returns an error if required handlers are not provided.

Example:

memory, err := syndicate.NewMemory(
    syndicate.WithAddHandler(func(msg syndicate.Message) {
        // Your custom add logic here
    }),
    syndicate.WithGetHandler(func() []syndicate.Message {
        // Your custom get logic here
        return messages
    }),
)
if err != nil {
    log.Fatal(err)
}

func NewSimpleMemory ΒΆ

func NewSimpleMemory() Memory

NewSimpleMemory creates a basic in-memory storage for chat messages. This function cannot fail, so it doesn't return an error.

type MemoryConfig ΒΆ added in v0.3.0

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

MemoryConfig holds the configuration for creating custom memory implementations

type MemoryOption ΒΆ added in v0.3.0

type MemoryOption func(*MemoryConfig) error

MemoryOption defines a function that configures a Memory implementation

func WithAddHandler ΒΆ added in v0.3.0

func WithAddHandler(addFunc func(message Message)) MemoryOption

WithAddHandler sets the function to handle adding messages

func WithGetHandler ΒΆ added in v0.3.0

func WithGetHandler(getFunc func() []Message) MemoryOption

WithGetHandler sets the function to handle retrieving messages

type Message ΒΆ

type Message struct {
	Role       string     `json:"role"`
	Content    string     `json:"content"`
	Name       string     `json:"name,omitempty"`
	ToolCalls  []ToolCall `json:"tool_calls,omitempty"`
	ToolCallID string     `json:"tool_call_id,omitempty"`
	ImageURLs  []string   `json:"image_urls,omitempty"`
}

Message represents a chat message with standardized fields.

type OpenAIClient ΒΆ

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

OpenAIClient implements the LLMClient interface using the OpenAI SDK. It wraps the official OpenAI client and provides a consistent interface for making chat completion requests.

func (*OpenAIClient) CreateChatCompletion ΒΆ

func (o *OpenAIClient) CreateChatCompletion(ctx context.Context, req ChatCompletionRequest) (ChatCompletionResponse, error)

CreateChatCompletion sends a chat completion request to the OpenAI API using the provided request parameters. It converts internal messages and tool definitions to OpenAI formats, sends the request, and maps the response back into the SDK's unified structure.

type PipelineOption ΒΆ added in v0.3.0

type PipelineOption func(*pipelineRequest)

PipelineOption defines options for pipeline execution.

func WithPipelineImages ΒΆ added in v0.3.0

func WithPipelineImages(imageURLs ...string) PipelineOption

WithPipelineImages sets image URLs for pipeline execution (only for first agent).

func WithPipelineInput ΒΆ added in v0.3.0

func WithPipelineInput(input string) PipelineOption

WithPipelineInput sets the input for pipeline execution.

func WithPipelineUserName ΒΆ added in v0.3.0

func WithPipelineUserName(userName string) PipelineOption

WithPipelineUserName sets the user name for pipeline execution.

type PromptBuilder ΒΆ

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

PromptBuilder facilitates the construction of a prompt by organizing content into sections and subsections.

func NewPromptBuilder ΒΆ

func NewPromptBuilder() *PromptBuilder

NewPromptBuilder creates and initializes a new PromptBuilder instance.

func (*PromptBuilder) AddBlockquote ΒΆ added in v0.4.0

func (pb *PromptBuilder) AddBlockquote(sectionName, text string) *PromptBuilder

AddBlockquote adds a blockquote to the specified section.

func (*PromptBuilder) AddBoldText ΒΆ added in v0.4.0

func (pb *PromptBuilder) AddBoldText(sectionName, text string) *PromptBuilder

AddBoldText adds bold text to the specified section.

func (*PromptBuilder) AddBulletItem ΒΆ added in v0.4.0

func (pb *PromptBuilder) AddBulletItem(sectionName, item string) *PromptBuilder

AddBulletItem adds a bullet point item to the specified section or subsection.

func (*PromptBuilder) AddBulletItemF ΒΆ added in v0.4.0

func (pb *PromptBuilder) AddBulletItemF(sectionName string, value interface{}) *PromptBuilder

AddBulletItemF is a helper method that converts any value to its string representation and adds it as a bullet point item to the specified section.

func (*PromptBuilder) AddCodeBlock ΒΆ added in v0.4.0

func (pb *PromptBuilder) AddCodeBlock(sectionName, code, language string) *PromptBuilder

AddCodeBlock adds a code block with optional language specification to the specified section.

func (*PromptBuilder) AddCodeBlockF ΒΆ added in v0.4.0

func (pb *PromptBuilder) AddCodeBlockF(sectionName string, value interface{}, language string) *PromptBuilder

AddCodeBlockF is a helper method that converts any value to its string representation and adds it as a code block to the specified section.

func (*PromptBuilder) AddHeader ΒΆ added in v0.4.0

func (pb *PromptBuilder) AddHeader(sectionName, text string, level int) *PromptBuilder

AddHeader adds a header of specified level to the section.

func (*PromptBuilder) AddHorizontalRule ΒΆ added in v0.4.0

func (pb *PromptBuilder) AddHorizontalRule(sectionName string) *PromptBuilder

AddHorizontalRule adds a horizontal rule to the specified section.

func (*PromptBuilder) AddItalicText ΒΆ added in v0.4.0

func (pb *PromptBuilder) AddItalicText(sectionName, text string) *PromptBuilder

AddItalicText adds italic text to the specified section.

func (pb *PromptBuilder) AddLink(sectionName, text, url string) *PromptBuilder

AddLink adds a hyperlink to the specified section.

func (*PromptBuilder) AddListItem ΒΆ

func (pb *PromptBuilder) AddListItem(sectionName, item string) *PromptBuilder

AddListItem adds a numbered list item to the specified section or subsection. The item is trimmed for any unnecessary whitespace.

func (*PromptBuilder) AddListItemF ΒΆ

func (pb *PromptBuilder) AddListItemF(sectionName string, value interface{}) *PromptBuilder

AddListItemF is a helper method that converts any value to its string representation (using JSON marshaling if necessary) and adds it as a numbered list item to the specified section.

func (*PromptBuilder) AddSubSection ΒΆ

func (pb *PromptBuilder) AddSubSection(childName, parentName string) *PromptBuilder

AddSubSection creates a new subsection (child) under the specified parent section. If the parent section does not exist, it is created as a top-level section.

func (*PromptBuilder) AddTable ΒΆ added in v0.4.0

func (pb *PromptBuilder) AddTable(sectionName string, headers []string, rows [][]string) *PromptBuilder

AddTable adds a table with headers and rows to the specified section.

func (*PromptBuilder) AddText ΒΆ

func (pb *PromptBuilder) AddText(sectionName, text string) *PromptBuilder

AddText adds a line of text to the specified section or subsection. It trims any extra whitespace before appending.

func (*PromptBuilder) AddTextF ΒΆ

func (pb *PromptBuilder) AddTextF(sectionName string, value interface{}) *PromptBuilder

AddTextF is a helper method that converts any value to its string representation (using JSON marshaling if necessary) and adds it as a text line to the specified section.

func (*PromptBuilder) Build ΒΆ

func (pb *PromptBuilder) Build() string

Build generates the final prompt by concatenating all top-level sections and their nested subsections. It returns the fully formatted prompt as a single string.

func (*PromptBuilder) CreateSection ΒΆ

func (pb *PromptBuilder) CreateSection(name string) *PromptBuilder

CreateSection adds a new top-level section with the given name to the prompt. If a section with the same name already exists, it is not created again.

type ResponseFormat ΒΆ

type ResponseFormat struct {
	Type       string      `json:"type"`
	JSONSchema *JSONSchema `json:"json_schema,omitempty"`
}

ResponseFormat specifies how the LLM should format its response.

type Section ΒΆ

type Section struct {
	Name        string     // Name of the section.
	Lines       []string   // Lines of text contained in the section.
	SubSections []*Section // Nested subsections within this section.
	// contains filtered or unexported fields
}

Section represents a block of content that may include text lines and nested subsections. It is used by the PromptBuilder to structure and format the final prompt.

type Syndicate ΒΆ added in v0.2.0

type Syndicate interface {
	ExecuteAgent(ctx context.Context, agentName string, options ...ExecuteAgentOption) (string, error)
	ExecutePipeline(ctx context.Context, options ...PipelineOption) (string, error)
	FindAgent(name string) (Agent, bool)
	GetGlobalHistory() []Message
	GetAgentNames() []string
	GetPipeline() []string
}

Syndicate defines the interface for managing multiple agents and pipelines.

func NewSyndicate ΒΆ added in v0.2.0

func NewSyndicate(options ...SyndicateOption) (Syndicate, error)

NewSyndicate creates a new Syndicate with the provided options.

type SyndicateOption ΒΆ added in v0.3.0

type SyndicateOption func(*syndicate) error

SyndicateOption defines a function that configures a syndicate.

func WithAgent ΒΆ added in v0.3.0

func WithAgent(agent Agent) SyndicateOption

WithAgent registers an agent with the syndicate using the agent's name as the key.

func WithAgents ΒΆ added in v0.3.0

func WithAgents(agents ...Agent) SyndicateOption

WithAgents registers multiple agents with the syndicate.

func WithGlobalHistory ΒΆ added in v0.3.0

func WithGlobalHistory(history Memory) SyndicateOption

WithGlobalHistory sets a custom global conversation history for the syndicate.

func WithPipeline ΒΆ added in v0.3.0

func WithPipeline(pipeline ...string) SyndicateOption

WithPipeline defines the execution order (pipeline) of agents. For example: []string{"agent1", "agent2", "agent3"}.

type Tool ΒΆ

type Tool interface {
	GetDefinition() ToolDefinition
	Execute(args json.RawMessage) (interface{}, error)
}

Tool defines the interface for executable tools.

func NewTool ΒΆ added in v0.4.0

func NewTool(options ...ToolOption) (Tool, error)

NewTool creates a custom Tool implementation using functional options. Returns an error if required options are not provided.

Example:

tool, err := syndicate.NewTool(
	syndicate.WithToolName("ProcessOrder"),
	syndicate.WithToolDescription("Process customer orders"),
	syndicate.WithToolSchema(OrderSchema{}),
	syndicate.WithToolExecuteHandler(func(args json.RawMessage) (interface{}, error) {
		var order OrderSchema
		if err := json.Unmarshal(args, &order); err != nil {
			return nil, err
		}
		// Process the order...
		return "Order processed successfully", nil
	}),
)

type ToolCall ΒΆ

type ToolCall struct {
	ID   string          `json:"id"`
	Name string          `json:"name"`
	Args json.RawMessage `json:"args"`
}

ToolCall represents a tool invocation request.

type ToolConfig ΒΆ added in v0.4.0

type ToolConfig struct {
	Name        string
	Description string
	Schema      any
	ExecuteFunc func(args json.RawMessage) (interface{}, error)
}

ToolConfig holds the configuration for creating custom tool implementations

type ToolDefinition ΒΆ

type ToolDefinition struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Parameters  any    `json:"parameters"`
}

ToolDefinition describes a tool's capabilities.

type ToolOption ΒΆ added in v0.4.0

type ToolOption func(*ToolConfig) error

ToolOption defines a function that configures a Tool implementation

func WithToolDescription ΒΆ added in v0.4.0

func WithToolDescription(description string) ToolOption

WithToolDescription sets the description for the tool

func WithToolExecuteHandler ΒΆ added in v0.4.0

func WithToolExecuteHandler(executeFunc func(args json.RawMessage) (interface{}, error)) ToolOption

WithToolExecuteHandler sets the execute function for the tool

func WithToolName ΒΆ added in v0.4.0

func WithToolName(name string) ToolOption

WithToolName sets the name for the tool

func WithToolSchema ΒΆ added in v0.4.0

func WithToolSchema(schema any) ToolOption

WithToolSchema sets the schema for the tool

type Usage ΒΆ

type Usage struct {
	PromptTokens     int `json:"prompt_tokens"`
	CompletionTokens int `json:"completion_tokens"`
	TotalTokens      int `json:"total_tokens"`
}

Usage provides token usage statistics.

Directories ΒΆ

Path Synopsis
examples

Jump to

Keyboard shortcuts

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