util

package
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Jun 15, 2025 License: MIT Imports: 20 Imported by: 0

Documentation

Index

Constants

View Source
const (
	DefaultTerminalWidth  = 120
	DefaultTerminalHeight = 80

	DefaultElementsPadding = 2
)

Defaults

View Source
const (
	PromptPaneHeight      = 5
	PromptPanePadding     = 2
	PromptPaneMarginTop   = 0
	StatusBarPaneHeight   = 5
	EditModeUiElementsSum = 4

	ChatPaneMarginRight = 1
	SidePaneLeftPadding = 5

	// A 'counterweight' is a sum of other elements' margins and paggings
	// The counterweight needs to be subtracted when calculating pane sizes
	// in order to properly align elements
	SettingsPaneHeightCounterweight = 3
	SessionsPaneHeightCounterweight = 4 // TODO: info pane hight
	ChatPaneVisualModeCounterweight = 1
)

Panes

View Source
const (
	ListRightShiftedItemPadding    = -2
	TextSelectorMaxWidthCorrection = 6
	InputContainerDelta            = 5

	ListItemMarginLeft  = 2
	ListItemPaddingLeft = 2

	WidthMinScalingLimit  = 120
	HeightMinScalingLimit = 46

	ListItemTrimThreshold  = 10
	ListItemTrimCharAmount = 14
)

UI elements

View Source
const (
	OpenAiProviderType = "openai"
	GeminiProviderType = "gemini"
)
View Source
const ActiveDot = "■"
View Source
const ChunkIndexStart = 1
View Source
const DefaultRequestTimeOutSec = 5
View Source
const DefaultSettingsId = 0
View Source
const ErrorHelp = "" /* 131-byte string literal not displayed */
View Source
const FrequencyRange = "[-2.0, 2.0)"
View Source
const InactiveDot = "•"
View Source
const ListHeadingDot = "■"
View Source
const QuickChatWarning = "" /* 135-byte string literal not displayed */
View Source
const TemperatureRange = "[0.0, 2.0]"
View Source
const TipsSeparator = " • "
View Source
const TopPRange = "[0.0, 1.0]"
View Source
const WordWrapDelta = 5

Variables

View Source
var (
	NormalFocusPanes = []Pane{SettingsPane, SessionsPane, PromptPane, ChatPane}
	ZenFocusPanes    = []Pane{PromptPane, ChatPane}
)
View Source
var DeleteSessionValidator = func(input string) error {
	allowed := []string{"y", "n"}
	if len(input) > 1 || !slices.Contains(allowed, input) {
		return errors.New("Invalid input")
	}
	return nil
}
View Source
var EmptyValidator = func(input string) error {
	return nil
}
View Source
var FrequencyValidator = func(input string) error {
	return validateRangedFloat(input, -2.0, 2.0, false, true)
}
View Source
var HelpStyle = lipgloss.NewStyle().Padding(0, 0, 0, 2).Foreground(subduedColor)
View Source
var ManualContent string
View Source
var MaxTokensValidator = func(input string) error {
	if input == "" {
		return nil
	}

	min := 0
	max := 1_000_000
	val, err := strconv.Atoi(input)
	if err != nil {
		return err
	}

	if val <= min || val > max {
		log.Printf("value %d out of range (%d, %d)", val, min, max)
		return fmt.Errorf("value %d out of range (%d, %d)", val, min, max)
	}

	return nil
}
View Source
var TemperatureValidator = func(input string) error {
	return validateRangedFloat(input, 0.0, 2.0, false, false)
}
View Source
var TopPValidator = func(input string) error {
	return validateRangedFloat(input, 0.0, 1.0, false, false)
}

Functions

func AddNewSession

func AddNewSession(isTemporary bool) tea.Cmd

func CalcChatPaneSize

func CalcChatPaneSize(tw, th int, mode ViewMode) (w, h int)

func CalcMaxSettingItemWidth

func CalcMaxSettingItemWidth(containerWidth int) int

func CalcModelsListSize

func CalcModelsListSize(tw, th int) (w, h int)

func CalcPromptPaneSize

func CalcPromptPaneSize(tw, th int, isTextEditMode bool) (w, h int)

func CalcSessionsListSize

func CalcSessionsListSize(tw, th, tipsOffset int) (w, h int)

func CalcSessionsPaneSize

func CalcSessionsPaneSize(tw, th int) (w, h int)

func CalcSettingsPaneSize

func CalcSettingsPaneSize(tw, th int) (w, h int)

func CalcVisualModeViewSize

func CalcVisualModeViewSize(tw, th int) (w, h int)

func DeleteFilesIfDevMode

func DeleteFilesIfDevMode()

func GetAppDataPath

func GetAppDataPath() (string, error)

func GetAppDirName

func GetAppDirName() string

func GetFilteredModelList

func GetFilteredModelList(providerType string, apiUrl string, models []string) []string

func GetManual

func GetManual(w int, colors SchemeColors) string

func GetMessagesAsPrettyString

func GetMessagesAsPrettyString(msgsToRender []MessageToSend, w int, colors SchemeColors, isQuickChat bool) string

func GetQuickChatDisclaimer

func GetQuickChatDisclaimer(w int, colors SchemeColors) string

func GetVisualModeView

func GetVisualModeView(msgsToRender []MessageToSend, w int, colors SchemeColors) string

func InitDb

func InitDb() *sql.DB

func IsFocusAllowed

func IsFocusAllowed(mode ViewMode, pane Pane, tw int) bool

func IsSystemMessageSupported

func IsSystemMessageSupported(provider ApiProvider, model string) bool

func Log

func Log(msgs ...any)

func MakeErrorMsg

func MakeErrorMsg(v string) tea.Cmd

func MakeFocusMsg

func MakeFocusMsg(v bool) tea.Msg

func MigrateFS

func MigrateFS(db *sql.DB, migrationsFS fs.FS, dir string) error

func PurgeModelsCache

func PurgeModelsCache(db *sql.DB) error

func RemoveDuplicates

func RemoveDuplicates[T comparable](slice []T) []T

func RenderBotMessage

func RenderBotMessage(msg string, width int, colors SchemeColors, isVisualMode bool) string

func RenderErrorMessage

func RenderErrorMessage(msg string, width int, colors SchemeColors) string

func RenderUserMessage

func RenderUserMessage(msg string, width int, colors SchemeColors, isVisualMode bool) string

func SendAsyncDependencyReadyMsg

func SendAsyncDependencyReadyMsg(dependency AsyncDependency) tea.Cmd

func SendCopyAllMsgs

func SendCopyAllMsgs() tea.Msg

func SendCopyLastMsg

func SendCopyLastMsg() tea.Msg

func SendNotificationMsg

func SendNotificationMsg(notification Notification) tea.Cmd

func SendProcessingStateChangedMsg

func SendProcessingStateChangedMsg(isProcessing bool) tea.Cmd

func SendPromptReadyMsg

func SendPromptReadyMsg(prompt string) tea.Cmd

func SendViewModeChangedMsg

func SendViewModeChangedMsg(mode ViewMode) tea.Cmd

func StripAnsiCodes

func StripAnsiCodes(str string) string

func SwitchToEditor

func SwitchToEditor(content string, op Operation, isFocused bool) tea.Cmd

func TransformRequestHeaders

func TransformRequestHeaders(provider ApiProvider, params map[string]any) map[string]any

func TrimListItem

func TrimListItem(value string, listWidth int) string

func UpdateSystemPrompt

func UpdateSystemPrompt(prompt string) tea.Cmd

Types

type AddNewSessionMsg

type AddNewSessionMsg struct {
	IsTemporary bool
}

type ApiProvider

type ApiProvider int
const (
	OpenAi ApiProvider = iota
	Local
	Mistral
	Gemini
)

func GetOpenAiInferenceProvider

func GetOpenAiInferenceProvider(providerType string, apiUrl string) ApiProvider

type AsyncDependency

type AsyncDependency int
const (
	SettingsPaneModule AsyncDependency = iota
	Orchestrator
)

type AsyncDependencyReady

type AsyncDependencyReady struct {
	Dependency AsyncDependency
}

type Choice

type Choice struct {
	Index        int                    `json:"index"`
	Delta        map[string]interface{} `json:"delta"`
	FinishReason string                 `json:"finish_reason"`
}

type ColorScheme

type ColorScheme string
const (
	OriginalPink ColorScheme = "pink"
	SmoothBlue   ColorScheme = "blue"
	Groovebox    ColorScheme = "groove"
)

func (ColorScheme) GetColors

func (s ColorScheme) GetColors() SchemeColors

type CompletionChunk

type CompletionChunk struct {
	ID               string      `json:"id"`
	Object           string      `json:"object"`
	Created          int         `json:"created"`
	Model            string      `json:"model"`
	SystemFingerpint string      `json:"system_fingerprint"`
	Choices          []Choice    `json:"choices"`
	Usage            *TokenUsage `json:"usage"`
}

type CompletionResponse

type CompletionResponse struct {
	Data CompletionChunk `json:"data"`
}

type CopyAllMsgs

type CopyAllMsgs struct{}

type CopyLastMsg

type CopyLastMsg struct{}

type ErrorEvent

type ErrorEvent struct {
	Message string
}

type FocusEvent

type FocusEvent struct {
	IsFocused bool
}

type LlmClient

type LlmClient interface {
	RequestCompletion(
		ctx context.Context,
		chatMsgs []MessageToSend,
		modelSettings Settings,
		resultChan chan ProcessApiCompletionResponse,
	) tea.Cmd
	RequestModelsList(ctx context.Context) ProcessModelsResponse
}

type MessageToSend

type MessageToSend struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type ModelDescription

type ModelDescription struct {
	Id      string `json:"id"`
	Object  string `json:"object"`
	Created int64  `json:"created"`
	OwnedBy string `json:"owned_by"`
}

type ModelsListResponse

type ModelsListResponse struct {
	Object string             `json:"object"`
	Data   []ModelDescription `json:"data"`
}

func (ModelsListResponse) GetModelNamesFromResponse

func (m ModelsListResponse) GetModelNamesFromResponse() []string

type ModelsLoaded

type ModelsLoaded struct {
	Models []string
}

type Notification

type Notification int
const (
	CopiedNotification Notification = iota
	CancelledNotification
	SysPromptChangedNotification
	PresetSavedNotification
)

type NotificationMsg

type NotificationMsg struct {
	Notification Notification
}

type OpenTextEditorMsg

type OpenTextEditorMsg struct {
	Content   string
	Operation Operation
	IsFocused bool
}

type Operation

type Operation int
const (
	NoOperaton Operation = iota
	SystemMessageEditing
)

type Pane

type Pane int
const (
	SettingsPane Pane = iota
	SessionsPane
	PromptPane
	ChatPane
)

fake enum to keep tab of the currently focused pane

func GetNewFocusMode

func GetNewFocusMode(mode ViewMode, currentFocus Pane, tw int) Pane

type ProcessApiCompletionResponse

type ProcessApiCompletionResponse struct {
	ID     int
	Result CompletionChunk // or whatever type you need
	Err    error
	Final  bool
}

Define a type for the data you want to return, if needed

type ProcessModelsResponse

type ProcessModelsResponse struct {
	Result ModelsListResponse
	Err    error
	Final  bool
}

type ProcessingStateChanged

type ProcessingStateChanged struct {
	IsProcessing bool
}

type PrompInputMode

type PrompInputMode int
const (
	PromptInsertMode PrompInputMode = iota
	PromptNormalMode
)

type PromptReady

type PromptReady struct {
	Prompt string
}

type SchemeColors

type SchemeColors struct {
	MainColor            lipgloss.Color
	AccentColor          lipgloss.Color
	HighlightColor       lipgloss.Color
	DefaultTextColor     lipgloss.Color
	ErrorColor           lipgloss.Color
	NormalTabBorderColor lipgloss.Color
	ActiveTabBorderColor lipgloss.Color
	RendererThemeOption  glamour.TermRendererOption
}

type Settings

type Settings struct {
	ID           int
	Model        string
	MaxTokens    int
	Frequency    *float32
	SystemPrompt *string
	TopP         *float32
	Temperature  *float32
	PresetName   string
}

type SwitchToPaneMsg

type SwitchToPaneMsg struct {
	Target Pane
}

type SystemPromptUpdatedMsg

type SystemPromptUpdatedMsg struct {
	SystemPrompt string
}

type TokenUsage

type TokenUsage struct {
	Prompt     int `json:"prompt_tokens"`
	Completion int `json:"completion_tokens"`
	Total      int `json:"total_tokens"`
}

type ViewMode

type ViewMode int
const (
	ZenMode ViewMode = iota
	TextEditMode
	NormalMode
)

type ViewModeChanged

type ViewModeChanged struct {
	Mode ViewMode
}

Jump to

Keyboard shortcuts

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