syndicate

package module
v0.2.0 Latest Latest
Warning

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

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

README

Syndicate SDK Logo

Go Report Card GitHub Workflow Status codecov GoDoc Release

Syndicate SDK is a powerful, agile, and extensible toolkit for crafting intelligent conversational agents in Golang. Designed with both flexibility and simplicity in mind, it empowers developers to build AI-driven agents capable of sophisticated prompt engineering, seamless tool integration, dynamic memory management, and orchestrating complex workflows. Whether you're prototyping or building production-grade solutions, Syndicate SDK lets you unleash the full potential of conversational AI with a lightweight framework that’s both hacker-friendly and enterprise-ready. 🚀


For a quick and comprehensive overview of the SDK, check out the 👉Quick Guide👈 📚✨🔥🚀


Features

  • Agent Management 🤖: Easily build and configure agents with custom system prompts, tools, and memory.
  • Prompt Engineering 📝: Create structured prompts with nested sections for improved clarity.
  • Tool Schemas 🔧: Generate JSON schemas from Go structures to define tools and validate user inputs.
  • Memory Implementations 🧠: Use built-in SimpleMemory or implement your own memory storage that adheres to the Memory interface.
  • Syndicate 🦾: Manage multiple agents and execute them in a predefined sequence to achieve complex workflows.
  • Extendable 🔐: The SDK is designed to be unopinionated, allowing seamless integration into your projects.

Installation

To install Syndicate SDK, use Go modules:

go get github.com/Dieg0Code/syndicate-go

Ensure that you have Go installed and configured in your development environment.

Quick Start

Below is a simple example demonstrating how to create an agent, define a tool, and execute a pipeline using Syndicate SDK. The example simulates processing a customer order and providing a summary of the conversation.

package main

import (
	"context"
	"encoding/json"
	"fmt"
	"log"
	"sync"

	"gorm.io/driver/sqlite"
	"gorm.io/gorm"

	syndicate "github.com/Dieg0Code/syndicate-go"
	openai "github.com/sashabaranov/go-openai"
)

// --------------------------
// Order Tool Implementation
// --------------------------

// OrderItem defines a single item in a customer's order.
type OrderItem struct {
	ItemName string `json:"item_name" description:"Name of the menu item" required:"true"`
	Quantity int    `json:"quantity" description:"Number of items ordered" required:"true"`
	Price    int    `json:"price" description:"Price of the item in cents" required:"true"`
}

// OrderSchema defines the structure for a complete order.
type OrderSchema struct {
	Items           []OrderItem `json:"items" description:"List of ordered items" required:"true"`
	DeliveryAddress string      `json:"delivery_address" description:"Delivery address for the order" required:"true"`
	CustomerName    string      `json:"customer_name" description:"Name of the customer" required:"true"`
	PhoneNumber     string      `json:"phone_number" description:"Customer's phone number" required:"true"`
	PaymentMethod   string      `json:"payment_method" description:"Payment method (cash or transfer)" required:"true" enum:"cash,transfer"`
}

// OrderTool implements syndicate.Tool and simulates saving an order.
type OrderTool struct{}

// NewOrderTool returns a new instance of OrderTool.
func NewOrderTool() syndicate.Tool {
	return &OrderTool{}
}

// GetDefinition generates the tool definition using the OrderSchema.
func (ot *OrderTool) GetDefinition() syndicate.ToolDefinition {
	schema, err := syndicate.GenerateRawSchema(OrderSchema{})
	if err != nil {
		log.Fatal(err)
	}

	return syndicate.ToolDefinition{
		Name:        "OrderProcessor",
		Description: "Processes customer orders by saving order details (items, address, customer info, and payment method).",
		Parameters:  schema,
		Strict:      true,
	}
}

// Execute simulates processing the order by printing it and returning a success message.
func (ot *OrderTool) Execute(args json.RawMessage) (interface{}, error) {
	var order OrderSchema
	if err := json.Unmarshal(args, &order); err != nil {
		return nil, err
	}

	// Here you could insert the order into a database or call an external service.
	fmt.Printf("Processing Order: %+v\n", order)
	return "Order processed successfully", nil
}

// --------------------------
// Custom Memory Implementation
// --------------------------

// CustomMemory is an example of a custom memory implementation using SQLite.
type CustomMemory struct {
	db    *gorm.DB
	mutex sync.RWMutex
}

// NewCustomMemory initializes a new CustomMemory instance with the provided Gorm DB.
func NewCustomMemory(db *gorm.DB) syndicate.Memory {
	return &CustomMemory{
		db: db,
	}
}

// Add stores a new message into memory (database).
func (m *CustomMemory) Add(message syndicate.Message) {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	// Example: You could save the message to the database here.
	// m.db.Create(&message)
	fmt.Printf("Memory Add: %+v\n", message)
}

// Get retrieves stored messages from memory.
// For simplicity, this example returns nil (in a real implementation, fetch from the DB).
func (m *CustomMemory) Get() []syndicate.Message {
	m.mutex.RLock()
	defer m.mutex.RUnlock()
	// Example: Retrieve recent messages from the database.
	return nil
}

// Clear clears all stored messages.
func (m *CustomMemory) Clear() {
	m.mutex.Lock()
	defer m.mutex.Unlock()
	// Example: Delete messages from the database.
	// m.db.Where("1 = 1").Delete(&syndicate.Message{})
	fmt.Println("Memory cleared")
}

// --------------------------
// Main Function & Pipeline
// --------------------------

func main() {
	// Initialize the OpenAI client with your API key.
	client := syndicate.NewOpenAIClient("YOUR_OPENAI_API_KEY")

	// Initialize a Gorm DB connection to SQLite for our custom memory.
	db, err := gorm.Open(sqlite.Open("memory.db"), &gorm.Config{})
	if err != nil {
		log.Fatalf("Error opening database: %v", err)
	}
	customMemory := NewCustomMemory(db)

	// Create an instance of our OrderTool.
	orderTool := NewOrderTool()

	// Build the first agent: OrderAgent.
	// This agent processes customer orders and can call the OrderTool.
	orderAgent, err := syndicate.NewAgent().
		SetClient(client).
		SetName("OrderAgent").
		SetConfigPrompt("You are an agent that processes customer orders. If the input contains order details, call the OrderProcessor tool to process the order.").
		SetMemory(customMemory).
		SetModel(openai.GPT4).
		EquipTool(orderTool). // Equip the OrderTool.
		Build()
	if err != nil {
		log.Fatalf("Error building OrderAgent: %v", err)
	}

	// Build the second agent: SummaryAgent.
	// This agent provides a final summary of the conversation.
	summaryAgent, err := syndicate.NewAgent().
		SetClient(client).
		SetName("SummaryAgent").
		SetConfigPrompt("You are an agent that provides a final summary confirming that the order was processed and reiterating key details.").
		SetMemory(customMemory).
		SetModel(openai.GPT4).
		Build()
	if err != nil {
		log.Fatalf("Error building SummaryAgent: %v", err)
	}

	// Create a Syndicate system and define the processing pipeline.
	syndicateSystem := syndicate.NewSyndicate().
		RecruitAgent(orderAgent).
		RecruitAgent(summaryAgent).
		DefinePipeline([]string{"OrderAgent", "SummaryAgent"}).
		Build()

	// Simulate a user input written in natural language.
	userName := "Alice"
	input := `Hi, I'd like to place an order. I want two Margherita Pizzas and one Coke. Please deliver them to 123 Main Street in Springfield. My name is Alice, my phone number is 555-1234, and I'll pay with cash.`

	// Execute the pipeline.
	response, err := syndicateSystem.ExecutePipeline(context.Background(), userName, input)
	if err != nil {
		log.Fatalf("Error executing pipeline: %v", err)
	}

	fmt.Println("\nFinal Syndicate Response:")
	fmt.Println(response)
}

Config Prompt Builder

The Config Prompt Builder is a utility that simplifies the creation of agent configuration prompts. It allows you to define a structured prompt using a fluent API, making it easier to configure agents with specific instructions.

package main

import (
	"fmt"
	"time"

	syndicate "github.com/Dieg0Code/syndicate-go"
)

type MenuItem struct {
	Name        string
	Description string
	Pricing     int
}

// NewConfigPrompt generates the system prompt in XML format
func NewConfigPrompt(name string, additionalContext MenuItem) string {
	configPrompt := syndicate.NewPromptBuilder().
		// Introduction section
		CreateSection("Introduction").
		AddText("Introduction", "You are an agent who provides detailed information about the menu, dishes, and key restaurant data using a semantic search system to enrich responses with relevant context.").

		// Agent identity
		CreateSection("Identity").
		AddText("Identity", "This section defines your name and persona identity.").
		AddSubSection("Name", "Identity").
		AddTextF("Name", name).
		AddSubSection("Persona", "Identity").
		AddText("Persona", "You act as an AI assistant in the restaurant, interacting with customers in a friendly and helpful manner to improve their dining experience.").

		// Capabilities and behavior
		CreateSection("CapabilitiesAndBehavior").
		AddListItem("CapabilitiesAndBehavior", "Respond in a clear and friendly manner, tailoring your answer to the user's query.").
		AddListItem("CapabilitiesAndBehavior", "Provide details about dishes (ingredients, preparation, allergens) and suggest similar options if appropriate.").
		AddListItem("CapabilitiesAndBehavior", "Promote the restaurant positively, emphasizing the quality of dishes and the dining experience.").
		AddListItem("CapabilitiesAndBehavior", "Be cheerful, polite, and respectful at all times; use emojis if appropriate.").
		AddListItem("CapabilitiesAndBehavior", "Register or cancel orders but do not update them; inform the user accordingly.").
		AddListItem("CapabilitiesAndBehavior", "Remember only the last 5 interactions with the user.").

		// Additional context
		CreateSection("AdditionalContext").
		AddText("AdditionalContext", "This section contains additional information about the available dishes used to answer user queries based on semantic similarity.").
		AddSubSection("Menu", "AdditionalContext").
		AddTextF("Menu", additionalContext).
		AddSubSection("CurrentDate", "AdditionalContext").
		AddTextF("CurrentDate", time.Now().Format(time.RFC3339)).
		AddListItem("AdditionalContext", "Select dishes based on similarity without mentioning it explicitly.").
		AddListItem("AdditionalContext", "Use context to enrich responses, but do not reveal it.").
		AddListItem("AdditionalContext", "Offer only dishes available on the menu.").

		// Limitations and directives
		CreateSection("LimitationsAndDirectives").
		AddListItem("LimitationsAndDirectives", "Do not invent data or reveal confidential information.").
		AddListItem("LimitationsAndDirectives", "Redirect unrelated topics to relevant restaurant topics.").
		AddListItem("LimitationsAndDirectives", "Strictly provide information only about the restaurant and its menu.").
		AddListItem("LimitationsAndDirectives", "Offer only available menu items; do not invent dishes.").

		// Response examples
		CreateSection("ResponseExamples").
		AddListItem("ResponseExamples", "If asked about a dish, provide details only if it is on the menu.").
		AddListItem("ResponseExamples", "If asked for recommendations, suggest only from the available menu.").
		AddListItem("ResponseExamples", "If asked for the menu, list only available dishes.").

		// Final considerations
		CreateSection("FinalConsiderations").
		AddText("FinalConsiderations", "**You must follow these directives to ensure an optimal user experience, otherwise you will be dismissed.**").
		Build()

	return configPrompt
}

func main() {
	// Define the additional context for the agent.
	additionalContext := MenuItem{
		Name:        "Spaghetti Carbonara",
		Description: "A classic Italian pasta dish consisting of eggs, cheese, pancetta, and black pepper.",
		Pricing:     15,
	}

	// Generate the system prompt for the agent.
	configPrompt := NewConfigPrompt("Bob", additionalContext)
	fmt.Println(configPrompt)
}

Dependencies and Their Licenses

This project uses the following third-party libraries:

Please refer to their respective repositories for the full license texts.

Contributing

Contributions are welcome! Feel free to open issues or submit pull requests on GitHub.

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 {
	Process(ctx context.Context, userName string, input string, additionalMessages ...[]Message) (string, error)
	AddTool(tool Tool)
	SetConfigPrompt(prompt string)
	GetName() string
}

Agent defines the interface for processing inputs and managing tools. Implementations of Agent should support processing messages, adding tools, configuring prompts, and providing a name identifier.

type AgentBuilder

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

AgentBuilder provides a fluent, modular way to configure and construct an Agent.

func NewAgent added in v0.2.0

func NewAgent() *AgentBuilder

NewAgentBuilder initializes and returns a new instance of AgentBuilder.

func (*AgentBuilder) Build

func (b *AgentBuilder) Build() (*BaseAgent, error)

Build constructs and returns an Agent based on the current configuration. It returns an error if any issues occurred during the builder setup.

func (*AgentBuilder) EquipTool added in v0.2.0

func (b *AgentBuilder) EquipTool(tool Tool) *AgentBuilder

EquipTool adds a tool to the operative's configuration, making it available during processing.

func (*AgentBuilder) SetClient

func (b *AgentBuilder) SetClient(client LLMClient) *AgentBuilder

SetClient sets the LLMClient to be used by the agent.

func (*AgentBuilder) SetConfigPrompt

func (b *AgentBuilder) SetConfigPrompt(prompt string) *AgentBuilder

SetConfigPrompt sets the system prompt that configures the agent's behavior.

func (*AgentBuilder) SetJSONResponseFormat

func (b *AgentBuilder) SetJSONResponseFormat(schemaName string, structSchema any) *AgentBuilder

SetJSONResponseFormat configures the agent to use a JSON schema for response formatting, generating the schema from a provided sample type.

func (*AgentBuilder) SetMemory

func (b *AgentBuilder) SetMemory(memory Memory) *AgentBuilder

SetMemory sets the memory implementation for the agent.

func (*AgentBuilder) SetModel

func (b *AgentBuilder) SetModel(model string) *AgentBuilder

SetModel configures the model to be used by the agent.

func (*AgentBuilder) SetName

func (b *AgentBuilder) SetName(name string) *AgentBuilder

SetName sets the name identifier for the agent.

func (*AgentBuilder) SetTemperature

func (b *AgentBuilder) SetTemperature(temperature float32) *AgentBuilder

SetTemperature sets the temperature parameter for the agent's responses.

type BaseAgent

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

BaseAgent holds the common implementation of the Agent interface, including the OpenAI client, system prompt, tools, memory, model configuration, and concurrency control.

func (*BaseAgent) AddTool

func (b *BaseAgent) AddTool(tool Tool)

AddTool adds a tool to the agent. AddTool adds a tool to the agent.

func (*BaseAgent) GetName

func (b *BaseAgent) GetName() string

GetName returns the name identifier of the agent.

func (*BaseAgent) Process

func (b *BaseAgent) Process(ctx context.Context, userName, input string, additionalMessages ...[]Message) (string, error)

Process takes the user input along with optional additional messages, adds the initial user message to memory, and initiates processing with available tools.

func (*BaseAgent) SetConfigPrompt

func (b *BaseAgent) SetConfigPrompt(prompt string)

SetConfigPrompt sets the system prompt for the agent, which can be used to configure behavior.

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 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"`
	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 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, endpoint string) LLMClient

NewOpenAIAzureClient creates an LLMClient for Azure using the provided API key and endpoint. 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 complete ChatCompletionMessage to the memory.
	Add(message Message)
	// Get returns a copy of all stored chat messages.
	Get() []Message
	// Clear removes all stored chat messages from memory.
	Clear()
}

Memory defines the interface for managing a history of chat messages. It provides methods for adding messages, retrieving the complete history, and clearing the history.

func NewSimpleMemory

func NewSimpleMemory() Memory

NewSimpleMemory creates and returns a new instance of SimpleMemory. It initializes the internal message slice and ensures the memory is ready for use.

type Message

type Message struct {
	Role      string     `json:"role"`
	Content   string     `json:"content"`
	Name      string     `json:"name,omitempty"`
	ToolCalls []ToolCall `json:"tool_calls,omitempty"`
	ToolID    string     `json:"tool_id,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 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) 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) 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 SimpleMemory

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

SimpleMemory implements a basic in-memory storage for chat messages. It uses a slice to store messages and a RWMutex for safe concurrent access.

func (*SimpleMemory) Add

func (s *SimpleMemory) Add(message Message)

Add appends a complete chat message to the SimpleMemory.

func (*SimpleMemory) Clear

func (s *SimpleMemory) Clear()

Clear removes all stored messages from the memory.

func (*SimpleMemory) Get

func (s *SimpleMemory) Get() []Message

Get returns a copy of all stored chat messages to avoid data races. A copy of the messages slice is returned to ensure that external modifications do not affect the internal state.

type Syndicate added in v0.2.0

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

Syndicate manages multiple agents, maintains a global conversation history, and optionally defines an execution pipeline for agents.

func (*Syndicate) ExecuteAgent added in v0.2.0

func (s *Syndicate) ExecuteAgent(ctx context.Context, agentName, userName, input string) (string, error)

ExecuteAgent runs a specific agent by combining the global history with the agent's internal memory. It retrieves the target agent, merges global messages with the agent's own messages (if applicable), processes the input, and then updates the global history with both the user input and the agent's response.

func (*Syndicate) ExecutePipeline added in v0.2.0

func (s *Syndicate) ExecutePipeline(ctx context.Context, userName, input string) (string, error)

ExecutePipeline runs a sequence of agents as defined in the syndicate's pipeline. The output of each agent is used as the input for the next agent in the pipeline. It returns the final output from the last agent or an error if processing fails.

func (*Syndicate) FindAgent added in v0.2.0

func (s *Syndicate) FindAgent(name string) (Agent, bool)

FindAgent retrieves a registered agent by its name in a thread-safe manner.

type SyndicateBuilder added in v0.2.0

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

SyndicateBuilder provides a fluent interface for constructing a Syndicate. It allows developers to configure agents, set a custom global history, and define an execution pipeline.

func NewSyndicate added in v0.2.0

func NewSyndicate() *SyndicateBuilder

NewSyndicateBuilder initializes a new SyndicateBuilder with default values and a simple in-memory history. It creates an empty agents map, an empty pipeline, and a default global history.

func (*SyndicateBuilder) Build added in v0.2.0

func (b *SyndicateBuilder) Build() *Syndicate

Build constructs and returns a Syndicate instance based on the current configuration.

func (*SyndicateBuilder) DefinePipeline added in v0.2.0

func (b *SyndicateBuilder) DefinePipeline(pipeline []string) *SyndicateBuilder

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

func (*SyndicateBuilder) RecruitAgent added in v0.2.0

func (b *SyndicateBuilder) RecruitAgent(agent Agent) *SyndicateBuilder

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

func (*SyndicateBuilder) SetGlobalHistory added in v0.2.0

func (b *SyndicateBuilder) SetGlobalHistory(history Memory) *SyndicateBuilder

SetGlobalHistory sets a custom global conversation history for the syndicate.

type Tool

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

Tool defines the interface for executable tools.

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 ToolDefinition

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

ToolDefinition describes a tool's capabilities.

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