Documentation
¶
Overview ¶
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT
* ChatCLI - Command Line Interface for LLM interaction * Copyright (c) 2024 Edilson Freitas * License: MIT
Index ¶
- Constants
- type AttachOptions
- type AttachedContext
- type ChunkStrategy
- type Chunker
- type ContextFilter
- type ContextMetrics
- type FileChunk
- type FileContext
- type FormatOptions
- type Manager
- func (m *Manager) AttachContext(sessionID, contextID string, priority int) error
- func (m *Manager) AttachContextWithOptions(sessionID, contextID string, opts AttachOptions) error
- func (m *Manager) BuildPromptMessages(sessionID string, opts FormatOptions) ([]models.Message, error)
- func (m *Manager) CreateContext(name, description string, paths []string, mode ProcessingMode, tags []string, ...) (*FileContext, error)
- func (m *Manager) DeleteContext(contextID string) error
- func (m *Manager) DetachContext(sessionID, contextID string) error
- func (m *Manager) GetAttachedContexts(sessionID string) ([]*FileContext, error)
- func (m *Manager) GetContext(contextID string) (*FileContext, error)
- func (m *Manager) GetContextByName(name string) (*FileContext, error)
- func (m *Manager) GetMetrics() *ContextMetrics
- func (m *Manager) ListContexts(filter *ContextFilter) ([]*FileContext, error)
- func (m *Manager) MergeContexts(name, description string, contextIDs []string, opts MergeOptions) (*FileContext, error)
- func (m *Manager) UpdateContext(name string, newPaths []string, newMode ProcessingMode, newTags []string, ...) (*FileContext, error)
- type MergeOptions
- type ProcessingMode
- type Processor
- type ScanOptionsMetadata
- type Storage
- func (s *Storage) DeleteContext(contextID string) error
- func (s *Storage) ExportContext(ctx *FileContext, targetPath string) error
- func (s *Storage) GetStoragePath() string
- func (s *Storage) ImportContext(sourcePath string) (*FileContext, error)
- func (s *Storage) LoadAllContexts() ([]*FileContext, error)
- func (s *Storage) LoadContext(contextID string) (*FileContext, error)
- func (s *Storage) SaveContext(ctx *FileContext) error
- type ValidationResult
- type Validator
- func (v *Validator) ValidateContext(ctx *FileContext) *ValidationResult
- func (v *Validator) ValidateDescription(description string) error
- func (v *Validator) ValidateMode(mode ProcessingMode) error
- func (v *Validator) ValidateName(name string) error
- func (v *Validator) ValidatePriority(priority int) error
- func (v *Validator) ValidateTags(tags []string) error
- func (v *Validator) ValidateTotalSize(size int64) error
Constants ¶
const ( // Tamanho alvo por chunk (em tokens estimados) DefaultChunkTargetTokens = 30000 // ~120KB de texto // Tamanho máximo por chunk MaxChunkTokens = 50000 // ~200KB de texto // Tamanho mínimo para considerar dividir MinFilesForChunking = 10 )
const ( MaxContextNameLength = 64 MaxTotalSizeBytes = 200 * 1024 * 1024 // 200MB MinNameLength = 3 MaxDescriptionLength = 500 )
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type AttachOptions ¶
AttachOptions define opções para anexar contextos
type AttachedContext ¶
type AttachedContext struct {
ContextID string `json:"context_id"` // ID do contexto
AttachedAt time.Time `json:"attached_at"` // Quando foi anexado
Priority int `json:"priority"` // Prioridade na ordem de mensagens (menor = primeiro)
SelectedChunks []int `json:"selected_chunks,omitempty"` // CORREÇÃO: Adicionado campo para chunks selecionados
}
AttachedContext representa um contexto anexado a uma sessão
type ChunkStrategy ¶
type ChunkStrategy string
ChunkStrategy define a estratégia de divisão
const ( ChunkByDirectory ChunkStrategy = "directory" // Agrupar por diretório ChunkByFileType ChunkStrategy = "filetype" // Agrupar por tipo de arquivo ChunkBySize ChunkStrategy = "size" // Dividir por tamanho ChunkSmart ChunkStrategy = "smart" // Estratégia inteligente híbrida )
type Chunker ¶
type Chunker struct {
// contains filtered or unexported fields
}
Chunker divide arquivos em chunks inteligentes
func NewChunker ¶
NewChunker cria uma nova instância de Chunker
func (*Chunker) DivideIntoChunks ¶
func (c *Chunker) DivideIntoChunks(files []utils.FileInfo, strategy ChunkStrategy) ([]FileChunk, error)
DivideIntoChunks divide arquivos em chunks usando estratégia inteligente
type ContextFilter ¶
type ContextFilter struct {
Tags []string `json:"tags"` // Filtrar por tags
Mode ProcessingMode `json:"mode"` // Filtrar por modo
MinSize int64 `json:"min_size"` // Tamanho mínimo
MaxSize int64 `json:"max_size"` // Tamanho máximo
CreatedAfter *time.Time `json:"created_after"` // Criado após
CreatedBefore *time.Time `json:"created_before"` // Criado antes
NamePattern string `json:"name_pattern"` // Padrão regex para nome
}
ContextFilter filtra contextos ao listar
type ContextMetrics ¶
type ContextMetrics struct {
TotalContexts int `json:"total_contexts"`
AttachedContexts int `json:"attached_contexts"`
TotalFiles int `json:"total_files"`
TotalSizeBytes int64 `json:"total_size_bytes"`
ContextsByMode map[string]int `json:"contexts_by_mode"`
LastUpdated time.Time `json:"last_updated"`
StoragePath string `json:"storage_path"`
}
ContextMetrics contém métricas sobre o uso de contextos
type FileChunk ¶
type FileChunk struct {
Index int `json:"index"` // Índice do chunk (1-based)
TotalChunks int `json:"total_chunks"` // Total de chunks
Files []utils.FileInfo `json:"files"` // Arquivos neste chunk
Description string `json:"description"` // Descrição do chunk
TotalSize int64 `json:"total_size"` // Tamanho total
EstTokens int `json:"est_tokens"` // Tokens estimados
}
FileChunk representa um chunk de arquivos
type FileContext ¶
type FileContext struct {
ID string `json:"id"`
Name string `json:"name"`
Description string `json:"description"`
Files []utils.FileInfo `json:"files"`
Mode ProcessingMode `json:"mode"`
TotalSize int64 `json:"total_size"`
FileCount int `json:"file_count"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
Tags []string `json:"tags"`
Metadata map[string]string `json:"metadata"`
ScanOptions utils.DirectoryScanOptions `json:"-"`
ScanOptionsMetadata ScanOptionsMetadata `json:"scan_options_metadata"`
Chunks []FileChunk `json:"chunks,omitempty"` // Chunks divididos (se modo chunked)
IsChunked bool `json:"is_chunked"` // Se foi dividido em chunks
ChunkStrategy string `json:"chunk_strategy,omitempty"` // Estratégia usada
}
FileContext representa um contexto gerenciado contendo arquivos e metadados
type FormatOptions ¶
type FormatOptions struct {
IncludeMetadata bool `json:"include_metadata"` // Incluir metadados no prompt
IncludeTimestamp bool `json:"include_timestamp"` // Incluir timestamp
Compact bool `json:"compact"` // Formato compacto (sem índice)
}
FormatOptions opções para formatar contexto como prompt
type Manager ¶
type Manager struct {
Storage *Storage
// contains filtered or unexported fields
}
Manager gerencia contextos de forma thread-safe
func NewManager ¶
NewManager cria uma nova instância do gerenciador de contextos
func (*Manager) AttachContext ¶
AttachContext anexa um contexto a uma sessão (não envia à LLM ainda)
func (*Manager) AttachContextWithOptions ¶
func (m *Manager) AttachContextWithOptions(sessionID, contextID string, opts AttachOptions) error
CORREÇÃO 1: Função refatorada para usar a estrutura de dados correta do Manager. AttachContextWithOptions anexa contexto com opções avançadas
func (*Manager) BuildPromptMessages ¶
func (m *Manager) BuildPromptMessages(sessionID string, opts FormatOptions) ([]models.Message, error)
CORREÇÃO 2: Refatorada para usar a estrutura de dados correta e lidar com chunks selecionados. BuildPromptMessages agora considera chunks selecionados
func (*Manager) CreateContext ¶
func (m *Manager) CreateContext(name, description string, paths []string, mode ProcessingMode, tags []string, force bool) (*FileContext, error)
CreateContext cria um novo contexto a partir de caminhos de arquivos/diretórios
func (*Manager) DeleteContext ¶
DeleteContext remove um contexto permanentemente
func (*Manager) DetachContext ¶
DetachContext remove um contexto anexado de uma sessão
func (*Manager) GetAttachedContexts ¶
func (m *Manager) GetAttachedContexts(sessionID string) ([]*FileContext, error)
GetAttachedContexts retorna os contextos anexados a uma sessão
func (*Manager) GetContext ¶
func (m *Manager) GetContext(contextID string) (*FileContext, error)
GetContext retorna um contexto pelo ID
func (*Manager) GetContextByName ¶
func (m *Manager) GetContextByName(name string) (*FileContext, error)
GetContextByName retorna um contexto pelo nome
func (*Manager) GetMetrics ¶
func (m *Manager) GetMetrics() *ContextMetrics
GetMetrics retorna métricas sobre os contextos
func (*Manager) ListContexts ¶
func (m *Manager) ListContexts(filter *ContextFilter) ([]*FileContext, error)
ListContexts lista todos os contextos com filtro opcional
func (*Manager) MergeContexts ¶
func (m *Manager) MergeContexts(name, description string, contextIDs []string, opts MergeOptions) (*FileContext, error)
MergeContexts mescla múltiplos contextos em um novo
func (*Manager) UpdateContext ¶ added in v1.35.0
func (m *Manager) UpdateContext(name string, newPaths []string, newMode ProcessingMode, newTags []string, newDescription string) (*FileContext, error)
UpdateContext atualiza um contexto existente
type MergeOptions ¶
type MergeOptions struct {
RemoveDuplicates bool `json:"remove_duplicates"` // Remove arquivos duplicados
SortByPath bool `json:"sort_by_path"` // Ordena por caminho
PreferNewer bool `json:"prefer_newer"` // Prefere versões mais recentes em duplicatas
Tags []string `json:"tags"` // Tags para o contexto mesclado
}
MergeOptions configura como contextos devem ser mesclados
type ProcessingMode ¶
type ProcessingMode string
ProcessingMode define o modo de processamento de arquivos no contexto
const ( ModeFull ProcessingMode = "full" // Conteúdo completo ModeSummary ProcessingMode = "summary" // Apenas estrutura ModeChunked ProcessingMode = "chunked" // Dividido em chunks ModeSmart ProcessingMode = "smart" // Seleção inteligente )
type Processor ¶
type Processor struct {
// contains filtered or unexported fields
}
Processor processa arquivos e diretórios para contextos
func NewProcessor ¶
NewProcessor cria uma nova instância de Processor
func (*Processor) EstimateTokenCount ¶
EstimateTokenCount estima o número de tokens em um conjunto de arquivos
func (*Processor) ProcessPaths ¶
func (p *Processor) ProcessPaths(paths []string, mode ProcessingMode) ([]utils.FileInfo, utils.DirectoryScanOptions, error)
ProcessPaths processa múltiplos caminhos baseado no modo
type ScanOptionsMetadata ¶
type ScanOptionsMetadata struct {
MaxTotalSize int64 `json:"max_total_size"`
MaxFilesToProcess int `json:"max_files_to_process"`
Extensions []string `json:"extensions"`
ExcludeDirs []string `json:"exclude_dirs"`
ExcludePatterns []string `json:"exclude_patterns"`
IncludeHidden bool `json:"include_hidden"`
}
ScanOptionsMetadata contém versão serializável das opções de scan
type Storage ¶
type Storage struct {
// contains filtered or unexported fields
}
Storage gerencia a persistência de contextos em disco
func NewStorage ¶
NewStorage cria uma nova instância de Storage
func (*Storage) DeleteContext ¶
DeleteContext deleta um contexto do disco
func (*Storage) ExportContext ¶
func (s *Storage) ExportContext(ctx *FileContext, targetPath string) error
ExportContext exporta um contexto para um arquivo específico
func (*Storage) GetStoragePath ¶
GetStoragePath retorna o caminho base de armazenamento
func (*Storage) ImportContext ¶
func (s *Storage) ImportContext(sourcePath string) (*FileContext, error)
ImportContext importa um contexto de um arquivo
func (*Storage) LoadAllContexts ¶
func (s *Storage) LoadAllContexts() ([]*FileContext, error)
LoadAllContexts carrega todos os contextos do disco
func (*Storage) LoadContext ¶
func (s *Storage) LoadContext(contextID string) (*FileContext, error)
LoadContext carrega um contexto do disco
func (*Storage) SaveContext ¶
func (s *Storage) SaveContext(ctx *FileContext) error
SaveContext salva um contexto em disco
type ValidationResult ¶
type ValidationResult struct {
Valid bool `json:"valid"`
Errors []string `json:"errors"`
Warnings []string `json:"warnings"`
}
ValidationResult resultado da validação de um contexto
type Validator ¶
type Validator struct {
// contains filtered or unexported fields
}
Validator valida contextos e suas operações
func NewValidator ¶
NewValidator cria uma nova instância de Validator
func (*Validator) ValidateContext ¶
func (v *Validator) ValidateContext(ctx *FileContext) *ValidationResult
ValidateContext valida um contexto completo
func (*Validator) ValidateDescription ¶
ValidateDescription valida a descrição de um contexto
func (*Validator) ValidateMode ¶
func (v *Validator) ValidateMode(mode ProcessingMode) error
ValidateMode valida o modo de processamento
func (*Validator) ValidateName ¶
ValidateName valida o nome de um contexto
func (*Validator) ValidatePriority ¶
ValidatePriority valida a prioridade de anexação
func (*Validator) ValidateTags ¶
ValidateTags valida as tags de um contexto
func (*Validator) ValidateTotalSize ¶
ValidateTotalSize valida o tamanho total de arquivos