gofabric

package module
v0.0.2 Latest Latest
Warning

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

Go to latest
Published: Jul 2, 2025 License: MIT Imports: 9 Imported by: 0

README

gofabric

gofabric is a Go client library for interacting with the Fabric API server. It provides a convenient way to manage contexts, patterns, and sessions, initiate chat sessions, and retrieve configuration and available models/strategies from the Fabric API.

Features

  • Client Initialization: Create a client with API key and custom HTTP client options.
  • Chat Functionality: Initiate chat sessions with streaming responses using Server-Sent Events (SSE).
  • Entity Management: Create, delete, retrieve, list, and rename contexts, patterns, and sessions.
  • Configuration Management: Get and update the Fabric API server configuration.
  • Model and Strategy Listing: Retrieve lists of available models and strategies.

Installation

To install gofabric, use go get:

go get github.com/sherif-fanous/gofabric

Usage

Basic Client Initialization
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/sherif-fanous/gofabric"
)

func main() {
    // Replace with your Fabric API server host
    host := "http://localhost:8000"
    // Replace with your API key if required by the server
    apiKey := "your-api-key"

    client := gofabric.NewClient(
        host,
        gofabric.WithAPIKey(apiKey),
    )

    // Example: Get server configuration
    config, err := client.GetConfig(context.Background())
    if err != nil {
        log.Fatalf("Failed to get config: %v", err)
    }
    fmt.Printf("Fabric API Config: %+v\n", config)
}
Chatting with the API
package main

import (
    "context"
    "fmt"
    "log"

    "github.com/sherif-fanous/gofabric"
)

func main() {
    host := "http://localhost:8000"
    apiKey := "your-api-key"

    client := gofabric.NewClient(
        host,
        gofabric.WithAPIKey(apiKey),
    )

    // Prepare chat request
    chatRequest := &gofabric.ChatRequest{
        Prompts: []gofabric.PromptRequest{
            {
                UserInput:   "Write a Golang function that calculates the factorial of a number.",
                Vendor:      "Gemini",
                Model:       "gemini-2.0-flash",
                ContextName: "",
                PatternName: "coding_master",
            },
        },
        Language:    "en",
        ChatOptions: gofabric.ChatOptions{},
    }

    // Start streaming chat
    responses, err := client.Chat(context.Background(), chatRequest)
    if err != nil {
        log.Fatalf("Error sending chat request: %v", err)
    }

    for response := range responses {
        switch response.Type {
        case "content":
            log.Printf("Content (%s): %s\n", response.Format, response.Content)
        case "error":
            log.Printf("Error: %s\n", response.Content)
        case "complete":
            log.Printf("Chat completed")
        }
    }
}
Managing Entities (Contexts, Patterns, Sessions)

The client provides methods for Context, Pattern, and Session management. Here's an example for Context:

package main

import (
    "context"
    "fmt"
    "log"
    "strings"

    "github.com/sherif-fanous/gofabric"
)

func main() {
    host := "http://localhost:8000"
    apiKey := "your-api-key"

    client := gofabric.NewClient(
        host,
        gofabric.WithAPIKey(apiKey),
    )

    ctx := context.Background()
    contextName := "context_example.md"

    // Check if the context exists
    if ok, err := client.ContextExists(ctx, contextName); err != nil {
        log.Fatalf("Error checking context existence: %v\n", err)
    } else if ok {
        log.Printf("Context '%s' already exists\n", contextName)
    } else {
        log.Printf("Context '%s' does not exist, proceeding to create it\n", contextName)
    }

    // Create a new context
    err := client.CreateContext(ctx, contextName, strings.NewReader("Context content"))
    if err != nil {
        log.Fatalf("Error creating context: %v\n", err)
    }
    log.Printf("Context '%s' created successfully\n", contextName)

    // Check again if the context exists
    if ok, err := client.ContextExists(ctx, contextName); err != nil {
        log.Printf("Error checking context existence: %v\n", err)

        return
    } else if ok {
        log.Printf("Context '%s' already exists\n", contextName)
    } else {
        log.Printf("Context '%s' does not exist, proceeding to create it\n", contextName)
    }

    // List all contexts
    contexts, err := client.ListContexts(ctx)
    if err != nil {
        log.Fatalf("Error listing contexts: %v\n", err)
    }
    log.Printf("Available contexts: %v\n", contexts)

    // Fetch the context metadata
    contextMetadata, err := client.GetContextMetadata(ctx, contextName)
    if err != nil {
        log.Fatalf("Error fetching context metadata: %v\n", err)
    }
    log.Printf("Fetched context: %+v\n", contextMetadata)

    // Rename the context
    if err := client.RenameContext(ctx, contextName, "renamed_"+contextName); err != nil {
        log.Fatalf("Error renaming context: %v\n", err)
    }
    log.Printf("Context '%s' renamed to 'renamed_%s'\n", contextName, contextName)

    // Delete the context
    if err := client.DeleteContext(ctx, "renamed_"+contextName); err != nil {
        log.Fatalf("Error deleting context: %v\n", err)
    }
    log.Printf("Context 'renamed_%s' deleted successfully\n", contextName)
}

Similar methods are available for Patterns and Sessions:

  • CreatePattern, DeletePattern, PatternExists, GetPatternMetadata, ListPatterns, RenamePattern
  • CreateSession, DeleteSession, SessionExists, GetSessionMetadata, ListSessions, RenameSession

For more detailed examples on how to use the API, refer to the examples/ directory.

Contributing

Contributions are welcome! Please feel free to submit issues or pull requests.

License

This project is licensed under the MIT License.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type AvailableModels

type AvailableModels struct {
	Models  []string            `json:"models"`  // Models is a list of model names.
	Vendors map[string][]string `json:"vendors"` // Vendors maps vendor names to their models.
}

AvailableModels contains a list of available model names and their vendors.

type ChatOptions

type ChatOptions struct {
	Model              string  `json:"model"`              // Model is the name of the model to use for the chat.
	Temperature        float64 `json:"temperature"`        // Temperature controls the randomness of the model's responses.
	TopP               float64 `json:"topP"`               // TopP is the nucleus sampling parameter for controlling diversity.
	PresencePenalty    float64 `json:"presencePenalty"`    // PresencePenalty discourages repetition of tokens already present in the conversation.
	FrequencyPenalty   float64 `json:"frequencyPenalty"`   // FrequencyPenalty discourages repetition of tokens based on their frequency in the conversation.
	Raw                bool    `json:"raw"`                // Raw indicates whether to return raw model output without processing.
	Seed               int     `json:"seed"`               // Seed is used for random number generation to ensure reproducibility.
	ModelContextLength int     `json:"modelContextLength"` // ModelContextLength is the maximum context length for the model.
}

type ChatRequest

type ChatRequest struct {
	Prompts     []PromptRequest `json:"prompts"`     // Prompts is a list of prompt requests to be processed.
	Language    string          `json:"language"`    // Language specifies the language for the chat.
	ChatOptions ChatOptions     `json:"chatOptions"` // ChatOptions contains various options for the chat session.
}

type Client

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

Client represents a client for the Fabric API server.

func NewClient

func NewClient(host string, opts ...Option) *Client

NewClient creates a new Client instance with the specified host and options. The Client will use the default HTTP client with a timeout of 60 seconds.

To set the API key, use the WithAPIKey option. To customize the HTTP client, use the WithHTTPClient option.

func (*Client) Chat

func (c *Client) Chat(ctx context.Context, chatRequest *ChatRequest) (<-chan StreamResponse, error)

Chat initiates a chat session with the specified chat request.

func (*Client) ContextExists

func (c *Client) ContextExists(ctx context.Context, name string) (bool, error)

ContextExists checks if a context exists.

func (*Client) CreateContext

func (c *Client) CreateContext(ctx context.Context, name string, body io.Reader) error

CreateContext creates a new context.

func (*Client) CreatePattern

func (c *Client) CreatePattern(ctx context.Context, name string, body io.Reader) error

CreatePattern creates a new pattern.

func (*Client) CreateSession

func (c *Client) CreateSession(ctx context.Context, name string, body io.Reader) error

CreateSession creates a new session.

func (*Client) DeleteContext

func (c *Client) DeleteContext(ctx context.Context, name string) error

DeleteContext deletes a context.

func (*Client) DeletePattern

func (c *Client) DeletePattern(ctx context.Context, name string) error

DeletePattern deletes a pattern.

func (*Client) DeleteSession

func (c *Client) DeleteSession(ctx context.Context, name string) error

DeleteSession deletes a session.

func (*Client) GetConfig

func (c *Client) GetConfig(ctx context.Context) (*Config, error)

GetConfig retrieves the configuration of fabric.

func (*Client) GetContextMetadata

func (c *Client) GetContextMetadata(ctx context.Context, name string) (*Context, error)

GetContextMetadata retrieves the metadata of a context.

func (*Client) GetPatternMetadata

func (c *Client) GetPatternMetadata(ctx context.Context, name string) (*Pattern, error)

GetPatternMetadata retrieves the metadata of a pattern.

func (*Client) GetSessionMetadata

func (c *Client) GetSessionMetadata(ctx context.Context, name string) (*Session, error)

GetSessionMetadata retrieves the metadata of a session.

func (*Client) ListContexts

func (c *Client) ListContexts(ctx context.Context) ([]string, error)

ListContexts retrieves the list of contexts.

func (*Client) ListModels

func (c *Client) ListModels(ctx context.Context) (*AvailableModels, error)

ListNames retrieves a list of models.

func (*Client) ListPatterns

func (c *Client) ListPatterns(ctx context.Context) ([]string, error)

ListPatterns retrieves the list of patterns.

func (*Client) ListSessions

func (c *Client) ListSessions(ctx context.Context) ([]string, error)

ListSessions retrieves the list of sessions.

func (*Client) ListStrategies

func (c *Client) ListStrategies(ctx context.Context) ([]Strategy, error)

ListStrategies retrieves a list of strategies.

func (*Client) PatternExists

func (c *Client) PatternExists(ctx context.Context, name string) (bool, error)

PatternExists checks if a pattern exists.

func (*Client) RenameContext

func (c *Client) RenameContext(ctx context.Context, oldName string, newName string) error

RenameContext renames a context.

func (*Client) RenamePattern

func (c *Client) RenamePattern(ctx context.Context, oldName string, newName string) error

RenamePattern renames a pattern.

func (*Client) RenameSession

func (c *Client) RenameSession(ctx context.Context, oldName string, newName string) error

RenameSession renames a session.

func (*Client) SessionExists

func (c *Client) SessionExists(ctx context.Context, name string) (bool, error)

SessionExists checks if a session exists.

func (*Client) UpdateConfig

func (c *Client) UpdateConfig(ctx context.Context, config *Config) error

UpdateConfig updates the configuration of fabric.

type Config

type Config struct {
	Anthropic  string `json:"anthropic"`  // Anthropic API key.
	DeepSeek   string `json:"deepseek"`   // DeepSeek API key.
	Gemini     string `json:"gemini"`     // Gemini API key.
	Grokai     string `json:"grokai"`     // Grokai API key.
	Groq       string `json:"groq"`       // Groq API key.
	LMStudio   string `json:"lmstudio"`   // LMStudio API key.
	Mistral    string `json:"mistral"`    // Mistral API key.
	Ollama     string `json:"ollama"`     // Ollama API key.
	OpenAI     string `json:"openai"`     // OpenAI API key.
	OpenRouter string `json:"openrouter"` // OpenRouter API key.
	Silicon    string `json:"silicon"`    // Silicon API key.
}

Config holds configuration values for various LLM providers.

type Context

type Context struct {
	Name    string `json:"name"`    // Name of the context.
	Content string `json:"content"` // Content is the text or data stored in the context.
}

Context represents a named context file with its content.

type Entity

type Entity interface {
	Pattern | Context | Session
}

Entity is a type constraint for generic functions that operate on Pattern, Context, or Session types.

type EntityType added in v0.0.2

type EntityType string
const (
	EntityTypeContext EntityType = "context"
	EntityTypePattern EntityType = "pattern"
	EntityTypeSession EntityType = "session"
)

type HTTPError

type HTTPError struct {
	URL        string
	StatusCode int
	Body       *string
}

HTTPError represents an error returned by the Fabric API

func (*HTTPError) Error

func (e *HTTPError) Error() string

Error implements the error interface

type Option

type Option func(*Client)

Option represents a function that configures the Client using the functional options pattern.

func WithAPIKey

func WithAPIKey(apiKey string) Option

WithAPIKey sets the API key for the client.

func WithHTTPClient

func WithHTTPClient(client *http.Client) Option

WithHTTPClient sets the HTTP client for the client.

type Pattern

type Pattern struct {
	Name        string `json:"name"`        // Name of the pattern.
	Description string `json:"description"` // Description provides details about the pattern's purpose.
	Pattern     string `json:"pattern"`     // Pattern is the actual prompt or template string.
}

Pattern represents a reusable prompt pattern with a name, description, and pattern string.

type PromptRequest

type PromptRequest struct {
	UserInput    string `json:"userInput"`    // UserInput is the input provided by the user for the prompt.
	Vendor       string `json:"vendor"`       // Vendor is the name of the LLM vendor (e.g., OpenAI, Anthropic).
	Model        string `json:"model"`        // Model is the name of the model to use for the prompt.
	ContextName  string `json:"contextName"`  // ContextName is the name of the context to use.
	PatternName  string `json:"patternName"`  // PatternName is the name of the pattern to use.
	StrategyName string `json:"strategyName"` // StrategyName is the name of the strategy to use.
}

type Session

type Session struct {
	Name     string `json:"name"` // Name of the session.
	Messages []struct {
		Role    string `json:"role"`    // Role is the sender's role (e.g., user, assistant).
		Content string `json:"content"` // Content is the message text.
	} `json:"messages"`
}

Session represents a chat session with a name and a list of messages.

type Strategy

type Strategy struct {
	Name        string `json:"name"`        // Name of the strategy.
	Description string `json:"description"` // Description provides details about the strategy's purpose.
	Pattern     string `json:"pattern"`     // Pattern is the pattern associated with the strategy.
}

Strategy represents a named strategy with a description and associated pattern.

type StreamResponse

type StreamResponse struct {
	Type    string `json:"type"`    // "content", "error", "complete"
	Format  string `json:"format"`  // "markdown", "mermaid", "plain"
	Content string `json:"content"` // The actual content
}

StreamResponse represents the chat's streaming response

type StreamResponseType added in v0.0.2

type StreamResponseType string
const (
	StreamResponseTypeComplete StreamResponseType = "complete"
	StreamResponseTypeContent  StreamResponseType = "content"
	StreamResponseTypeError    StreamResponseType = "error"
)

Directories

Path Synopsis
examples
chat command
config command
context command
model command
pattern command
session command
strategy command

Jump to

Keyboard shortcuts

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