terraphim_types - Core Type Definitions
Overview
terraphim_types provides fundamental data structures used throughout the Terraphim ecosystem. This crate contains no business logic - it defines the domain models, types, and shared structures that other crates build upon.
Domain Model
Core Concepts
Role
Represents a user profile or persona with specific knowledge domains, search preferences, and configuration.
Key Responsibilities:
- Define user knowledge domains
- Configure search relevance functions
- Manage LLM integration settings
- Specify data sources (haystacks)
Document
The central unit of content in Terraphim. Documents come from various sources and are indexed for semantic search.
Key Responsibilities:
- Store content and metadata
- Track source and classification
- Maintain search rankings
- Link to knowledge graph concepts
Thesaurus
Mapping from normalised terms to concepts, supporting synonyms and URLs.
Key Responsibilities:
- Normalise terminology
- Store concept mappings
- Provide synonym support
- Link concepts to external resources
Node
Concept entity in the knowledge graph.
Key Responsibilities:
- Represent abstract concepts
- Store metadata and descriptions
- Link to external resources
Edge
Relationship between two nodes in the knowledge graph.
Key Responsibilities:
- Define concept relationships
- Enable graph traversal
- Support relationship types
Data Models
Normalised Types
NormalisedTermValue
A string that has been normalised to lowercase and trimmed.
;
Use Cases:
- Case-insensitive term matching
- Consistent key generation
- Normalised storage
NormalisedTerm
Higher-level term with unique identifier and display values.
Use Cases:
- Unique concept identification
- Preserving original case for display
- Linking concepts to URLs
RoleName
Role name with case-insensitive lookup support.
Use Cases:
- User profile identification
- Case-insensitive comparisons
- Preserving display names
Search Types
SearchQuery
Structure for search requests with terms and operators.
Use Cases:
- Single-term search
- Multi-term boolean search
- Role-scoped queries
- Pagination and layering
LogicalOperator
Boolean operators for combining search terms.
Use Cases:
- Combining search criteria
- Excluding terms
- Complex query building
RelevanceFunction
Algorithm for ranking search results.
Use Cases:
- Title matching (
TitleScorer) - Statistical ranking (
BM25,BM25F,BM25Plus) - Knowledge graph-based ranking (
TerraphimGraph)
Document Types
DocumentType
Classification of document types.
Use Cases:
- Knowledge graph entries
- Regular documents
- Configuration documents
IndexedDocument
Document with search indexes and concept links.
Use Cases:
- Search-ready documents
- Knowledge graph integration
- Optimised retrieval
LLM Types
Conversation
Chat context with messages and metadata.
Use Cases:
- Managing chat history
- Context window management
- Role-specific conversations
ChatMessage
Individual message in a conversation.
Use Cases:
- Storing user/assistant messages
- Timestamp tracking
- Conversation flow
ContextItem
Fragment of context for LLM requests.
Use Cases:
- Building LLM context
- Ranking context fragments
- Source attribution
Routing Types
RoutingRule
Rule-based LLM provider selection.
Use Cases:
- Capability-based routing
- Provider selection
- Model specification
RoutingDecision
Result of routing logic.
Use Cases:
- Routing execution results
- Audit trail
- Debug information
Priority
Priority levels for routing decisions.
Use Cases:
- Rule ordering
- Fallback prioritisation
- Resource allocation
Multi-Agent Types
MultiAgentContext
Shared context for coordinated agents.
Use Cases:
- Agent coordination
- State sharing
- Task distribution
AgentInfo
Information about an agent.
Use Cases:
- Agent discovery
- Capability matching
- Status tracking
Dynamic Ontology Types
SchemaSignal
Signal indicating schema structure.
Use Cases:
- Schema discovery
- Ontology learning
- Structure detection
ExtractedEntity
Entity extracted from content.
Use Cases:
- Entity recognition
- Confidence scoring
- Type classification
CoverageSignal
Signal indicating coverage level.
Use Cases:
- Coverage measurement
- Quality assessment
- Progress tracking
GroundingMetadata
Metadata for grounding operations.
Use Cases:
- Source attribution
- Confidence tracking
- Temporal grounding
Specialised Modules
Medical Types (feature: "medical")
HgncGene
HGNC gene normalisation data.
Use Cases:
- Gene normalisation
- Symbol lookup
- Alias expansion
HgncNormalizer
Normaliser for HGNC genes.
Use Cases:
- Consistent gene naming
- Symbol resolution
- Alias matching
Persona Types
PersonaDefinition
Agent persona with characteristics and skills.
Use Cases:
- Agent behaviour definition
- Skill specification
- Personality modelling
CharacteristicDef
Behavioural characteristic.
Use Cases:
- Behaviour shaping
- Weighted characteristics
- Personality traits
SfiaSkillDef
SFIA skill definition.
Use Cases:
- Skill specification
- Proficiency tracking
- Category organisation
Implementation Patterns
Type Safety
- Use
Option<T>for optional fields - Use
Result<T, E>for fallible operations - Use
Arc<T>for shared immutable data - Use
AHashMap<K, V>for high-performance maps
Serialisation
- Implement
SerializeandDeserialize - Use
serdewith sensible defaults - Support JSON interchange
- Optional TypeScript generation (
tsifyfeature)
Validation
- Builder patterns for complex construction
- Constructor methods with validation
new()andwith_*()pattern- Sensible defaults for all fields
Relationships
Core Relationships
Role 1..* Haystack
Role 1..1 KnowledgeGraph
Document 1..* Tag
Node 1..* Edge
Document 1..* IndexedDocument
Thesaurus 1..* NormalisedTermSearch Relationships
SearchQuery 1..1 NormalisedTermValue
SearchQuery 0..1 LogicalOperator
SearchQuery 0..1 Role
IndexedDocument 1..1 Document
IndexedDocument 0..* NodeLLM Relationships
Conversation 1..* ChatMessage
Conversation 1..1 Role
Conversation 1..* ContextItem
RoutingRule 0..* RoutingDecision
RoutingRule 1..1 PriorityFuture Extensions
Planned Additions
- Additional document types
- Enhanced relevance functions
- Richer agent information
- More sophisticated routing rules
- Extended ontology types
Compatibility
- Maintain backward compatibility
- Versioned schema evolution
- Migration utilities
- Deprecation warnings
Best Practices
Type Usage
- Prefer explicit types over dynamic values
- Use
Option<T>for nullable fields - Document invariants in comments
- Provide builder methods for complex types
Serialisation
- Use sensible serde defaults
- Handle missing fields gracefully
- Provide human-readable JSON
- Support feature-gated optional fields
Error Handling
- Use
thiserrorfor error types - Provide context in error messages
- Categorise errors for handling
- Support conversion between error types
Testing
Test Coverage
- Unit tests for all types
- Serialisation/deserialisation tests
- Edge case handling
- Integration with dependent crates
Test Patterns