This commit is contained in:
Cyber MacGeddon 2025-07-03 10:39:23 +01:00
parent 1e5352e8b7
commit 483d3f0da7
8 changed files with 1893 additions and 0 deletions

View file

@ -0,0 +1,285 @@
# tg-add-library-document
Adds documents to the TrustGraph library with comprehensive metadata support.
## Synopsis
```bash
tg-add-library-document [options] file1 [file2 ...]
```
## Description
The `tg-add-library-document` command adds documents to the TrustGraph library system, which provides persistent document storage with rich metadata management. Unlike direct document loading, the library approach offers better document lifecycle management, metadata preservation, and processing control.
Documents added to the library can later be processed using `tg-start-library-processing` for controlled batch processing operations.
## Options
### Connection & User
- `-u, --url URL`: TrustGraph API URL (default: `$TRUSTGRAPH_URL` or `http://localhost:8088/`)
- `-U, --user USER`: User identifier (default: `trustgraph`)
### Document Information
- `--name NAME`: Document name/title
- `--description DESCRIPTION`: Document description
- `--id ID`: Custom document identifier (if not specified, uses content hash)
- `--kind MIMETYPE`: Document MIME type (auto-detected if not specified)
- `--tags TAGS`: Comma-separated list of tags
### Copyright Information
- `--copyright-notice NOTICE`: Copyright notice text
- `--copyright-holder HOLDER`: Copyright holder name
- `--copyright-year YEAR`: Copyright year
- `--license LICENSE`: Copyright license
### Publication Information
- `--publication-organization ORG`: Publishing organization name
- `--publication-description DESC`: Publication description
- `--publication-date DATE`: Publication date
- `--publication-url URL`: Publication URL
### Document Source
- `--document-url URL`: Original document source URL
- `--keyword KEYWORDS`: Document keywords (space-separated)
## Arguments
- `file1 [file2 ...]`: One or more files to add to the library
## Examples
### Basic Document Addition
```bash
tg-add-library-document report.pdf
```
### With Complete Metadata
```bash
tg-add-library-document \
--name "Annual Research Report 2024" \
--description "Comprehensive analysis of research outcomes" \
--copyright-holder "Research Institute" \
--copyright-year "2024" \
--license "CC BY 4.0" \
--tags "research,annual,analysis" \
--keyword "research" "analysis" "2024" \
annual-report.pdf
```
### Academic Paper
```bash
tg-add-library-document \
--name "Machine Learning in Healthcare" \
--description "Study on ML applications in medical diagnosis" \
--publication-organization "University Medical School" \
--publication-date "2024-03-15" \
--copyright-holder "Dr. Jane Smith" \
--tags "machine-learning,healthcare,medical" \
--keyword "ML" "healthcare" "diagnosis" \
ml-healthcare-paper.pdf
```
### Multiple Documents with Shared Metadata
```bash
tg-add-library-document \
--publication-organization "Tech Company" \
--copyright-holder "Tech Company Inc." \
--copyright-year "2024" \
--license "Proprietary" \
--tags "documentation,technical" \
manual-v1.pdf manual-v2.pdf manual-v3.pdf
```
### Custom Document ID
```bash
tg-add-library-document \
--id "PROJ-2024-001" \
--name "Project Specification" \
--description "Technical requirements document" \
project-spec.docx
```
## Document Processing
1. **File Reading**: Reads document content as binary data
2. **ID Generation**: Creates SHA256 hash-based ID (unless custom ID provided)
3. **Metadata Assembly**: Combines all metadata into structured format
4. **Library Storage**: Stores document and metadata in library system
5. **URI Creation**: Generates TrustGraph document URI
## Document ID Generation
- **Automatic**: SHA256 hash of file content converted to TrustGraph URI
- **Custom**: Use `--id` parameter for specific identifiers
- **Format**: `http://trustgraph.ai/d/[hash-or-custom-id]`
## MIME Type Detection
The system automatically detects document types:
- **PDF**: `application/pdf`
- **Word**: `application/vnd.openxmlformats-officedocument.wordprocessingml.document`
- **Text**: `text/plain`
- **HTML**: `text/html`
Override with `--kind` parameter if needed.
## Metadata Format
Metadata is stored as RDF triples including:
### Dublin Core Properties
- `dc:title`: Document name
- `dc:description`: Document description
- `dc:creator`: Copyright holder
- `dc:date`: Publication date
- `dc:rights`: Copyright notice
- `dc:license`: License information
- `dc:subject`: Keywords and tags
### Organization Information
- `foaf:Organization`: Publisher details
- `foaf:name`: Organization name
- `vcard:hasURL`: Organization website
### Document Properties
- `bibo:doi`: DOI if applicable
- `bibo:url`: Document source URL
## Output
For each successfully added document:
```bash
report.pdf: Loaded successfully.
```
For failures:
```bash
invalid.pdf: Failed: File not found
```
## Error Handling
### File Errors
```bash
document.pdf: Failed: No such file or directory
```
**Solution**: Verify file path exists and is readable.
### Permission Errors
```bash
document.pdf: Failed: Permission denied
```
**Solution**: Check file permissions and user access rights.
### Connection Errors
```bash
document.pdf: Failed: Connection refused
```
**Solution**: Verify API URL and ensure TrustGraph is running.
### Library Errors
```bash
document.pdf: Failed: Document already exists
```
**Solution**: Use different ID or update existing document.
## Library Management Workflow
### 1. Add Documents
```bash
tg-add-library-document research-paper.pdf
```
### 2. Verify Addition
```bash
tg-show-library-documents
```
### 3. Start Processing
```bash
tg-start-library-processing --flow-id research-flow
```
### 4. Monitor Processing
```bash
tg-show-library-processing
```
## Environment Variables
- `TRUSTGRAPH_URL`: Default API URL
## Related Commands
- [`tg-show-library-documents`](tg-show-library-documents.md) - List library documents
- [`tg-remove-library-document`](tg-remove-library-document.md) - Remove documents from library
- [`tg-start-library-processing`](tg-start-library-processing.md) - Process library documents
- [`tg-stop-library-processing`](tg-stop-library-processing.md) - Stop library processing
- [`tg-show-library-processing`](tg-show-library-processing.md) - Show processing status
## API Integration
This command uses the [Librarian API](../apis/api-librarian.md) with the `add-document` operation to store documents with metadata.
## Use Cases
### Research Document Management
```bash
tg-add-library-document \
--name "Climate Change Analysis" \
--publication-organization "Climate Research Institute" \
--tags "climate,research,environment" \
climate-study.pdf
```
### Corporate Documentation
```bash
tg-add-library-document \
--name "Product Manual v2.1" \
--copyright-holder "Acme Corporation" \
--license "Proprietary" \
--tags "manual,product,v2.1" \
product-manual.pdf
```
### Legal Document Archive
```bash
tg-add-library-document \
--name "Contract Template" \
--description "Standard service agreement template" \
--copyright-holder "Legal Department" \
--tags "legal,contract,template" \
contract-template.docx
```
### Academic Paper Collection
```bash
tg-add-library-document \
--publication-organization "IEEE" \
--copyright-year "2024" \
--tags "academic,ieee,conference" \
paper1.pdf paper2.pdf paper3.pdf
```
## Best Practices
1. **Consistent Metadata**: Use standardized metadata fields for better organization
2. **Meaningful Tags**: Add relevant tags for document discovery
3. **Copyright Information**: Include complete copyright details for legal compliance
4. **Batch Operations**: Process related documents together with shared metadata
5. **Version Control**: Use clear naming and tagging for document versions
6. **Library Organization**: Use collections and user assignments for multi-tenant systems
## Advantages over Direct Loading
### Library Benefits
- **Persistent Storage**: Documents preserved in library system
- **Metadata Management**: Rich metadata storage and querying
- **Processing Control**: Controlled batch processing with start/stop
- **Document Lifecycle**: Full document management capabilities
- **Search and Discovery**: Better document organization and retrieval
### When to Use Library vs Direct Loading
- **Use Library**: For document management, metadata preservation, controlled processing
- **Use Direct Loading**: For immediate processing, simple workflows, temporary documents

View file

@ -0,0 +1,221 @@
# tg-invoke-graph-rag
Uses the Graph RAG service to answer questions using knowledge graph data.
## Synopsis
```bash
tg-invoke-graph-rag -q "question" [options]
```
## Description
The `tg-invoke-graph-rag` command performs graph-based Retrieval Augmented Generation (RAG) to answer questions using structured knowledge from the knowledge graph. It retrieves relevant entities and relationships from the graph and uses them to provide contextually accurate answers.
Graph RAG is particularly effective for questions that require understanding relationships between entities, reasoning over structured knowledge, and providing answers based on factual connections in the data.
## Options
### Required Arguments
- `-q, --question QUESTION`: The question to answer using graph knowledge
### Optional Arguments
- `-u, --url URL`: TrustGraph API URL (default: `$TRUSTGRAPH_URL` or `http://localhost:8088/`)
- `-f, --flow-id FLOW`: Flow ID to use (default: `default`)
- `-U, --user USER`: User identifier (default: `trustgraph`)
- `-C, --collection COLLECTION`: Collection identifier (default: `default`)
### Graph Search Parameters
- `-e, --entity-limit LIMIT`: Maximum entities to retrieve (default: `50`)
- `-t, --triple-limit LIMIT`: Maximum triples to retrieve (default: `30`)
- `-s, --max-subgraph-size SIZE`: Maximum subgraph size (default: `150`)
- `-p, --max-path-length LENGTH`: Maximum path length for graph traversal (default: `2`)
## Examples
### Basic Graph RAG Query
```bash
tg-invoke-graph-rag -q "What is the relationship between AI and machine learning?"
```
### With Custom Parameters
```bash
tg-invoke-graph-rag \
-q "How are neural networks connected to deep learning?" \
-e 100 \
-t 50 \
-s 200
```
### Using Specific Flow and Collection
```bash
tg-invoke-graph-rag \
-q "What research papers discuss climate change?" \
-f research-flow \
-C scientific-papers \
-U researcher
```
### Large Graph Exploration
```bash
tg-invoke-graph-rag \
-q "Explain the connections between quantum computing and cryptography" \
-e 150 \
-t 100 \
-s 300 \
-p 3
```
## Graph Search Parameters Explained
### Entity Limit (`-e, --entity-limit`)
Controls how many entities are retrieved from the knowledge graph that are relevant to the question. Higher values provide more context but may include less relevant information.
### Triple Limit (`-t, --triple-limit`)
Limits the number of relationship triples (subject-predicate-object) retrieved. These triples define the relationships between entities.
### Max Subgraph Size (`-s, --max-subgraph-size`)
Sets the maximum size of the knowledge subgraph used for answering. Larger subgraphs provide more complete context but require more processing.
### Max Path Length (`-p, --max-path-length`)
Determines how many "hops" through the graph are considered when finding relationships. Higher values can discover more distant but potentially relevant connections.
## Output Format
The command returns a natural language answer based on the retrieved graph knowledge:
```
Neural networks are a fundamental component of deep learning architectures.
The knowledge graph shows that deep learning is a subset of machine learning
that specifically utilizes multi-layered neural networks. These networks consist
of interconnected nodes (neurons) organized in layers, where each layer processes
and transforms the input data. The relationship between neural networks and deep
learning is that neural networks provide the computational structure, while deep
learning represents the training methodologies and architectures that use these
networks to learn complex patterns from data.
```
## How Graph RAG Works
1. **Query Analysis**: Analyzes the question to identify key entities and concepts
2. **Entity Retrieval**: Finds relevant entities in the knowledge graph
3. **Subgraph Extraction**: Retrieves connected entities and relationships
4. **Context Assembly**: Combines retrieved knowledge into coherent context
5. **Answer Generation**: Uses LLM with graph context to generate accurate answers
## Comparison with Document RAG
### Graph RAG Advantages
- **Structured Knowledge**: Leverages explicit relationships between concepts
- **Reasoning Capability**: Can infer answers from connected facts
- **Consistency**: Provides factually consistent answers based on structured data
- **Relationship Discovery**: Excellent for questions about connections and relationships
### When to Use Graph RAG
- Questions about relationships between entities
- Queries requiring logical reasoning over facts
- When you need to understand connections in complex domains
- For factual questions with precise answers
## Error Handling
### Flow Not Available
```bash
Exception: Invalid flow
```
**Solution**: Verify the flow exists and is running with `tg-show-flows`.
### No Graph Data
```bash
Exception: No relevant knowledge found
```
**Solution**: Ensure knowledge has been loaded into the graph using `tg-load-kg-core` or document processing.
### Connection Errors
```bash
Exception: Connection refused
```
**Solution**: Check the API URL and ensure TrustGraph is running.
### Parameter Errors
```bash
Exception: Invalid parameter value
```
**Solution**: Verify that numeric parameters are within valid ranges.
## Environment Variables
- `TRUSTGRAPH_URL`: Default API URL
## Related Commands
- [`tg-invoke-document-rag`](tg-invoke-document-rag.md) - Document-based RAG queries
- [`tg-invoke-agent`](tg-invoke-agent.md) - Interactive agent with multiple tools
- [`tg-load-kg-core`](tg-load-kg-core.md) - Load knowledge into graph
- [`tg-show-graph`](tg-show-graph.md) - Explore graph contents
- [`tg-show-flows`](tg-show-flows.md) - List available flows
## API Integration
This command uses the [Graph RAG API](../apis/api-graph-rag.md) to perform retrieval augmented generation using knowledge graph data.
## Use Cases
### Research and Academia
```bash
tg-invoke-graph-rag \
-q "What are the key researchers working on quantum machine learning?" \
-C academic-papers
```
### Business Intelligence
```bash
tg-invoke-graph-rag \
-q "How do our products relate to market trends?" \
-C business-data
```
### Technical Documentation
```bash
tg-invoke-graph-rag \
-q "What are the dependencies between these software components?" \
-C technical-docs
```
### Medical Knowledge
```bash
tg-invoke-graph-rag \
-q "What are the known interactions between these medications?" \
-C medical-knowledge
```
## Performance Tuning
### For Broad Questions
Increase limits to get comprehensive answers:
```bash
-e 100 -t 80 -s 250 -p 3
```
### For Specific Questions
Use lower limits for faster, focused responses:
```bash
-e 30 -t 20 -s 100 -p 2
```
### For Deep Analysis
Allow longer paths and larger subgraphs:
```bash
-e 150 -t 100 -s 400 -p 4
```
## Best Practices
1. **Parameter Tuning**: Start with defaults and adjust based on question complexity
2. **Question Clarity**: Ask specific questions for better graph retrieval
3. **Knowledge Quality**: Ensure high-quality knowledge is loaded in the graph
4. **Flow Selection**: Use flows with appropriate knowledge domains
5. **Collection Targeting**: Specify relevant collections for focused results

267
docs/cli/tg-invoke-llm.md Normal file
View file

@ -0,0 +1,267 @@
# tg-invoke-llm
Invokes the text completion service with custom system and user prompts.
## Synopsis
```bash
tg-invoke-llm "system prompt" "user prompt" [options]
```
## Description
The `tg-invoke-llm` command provides direct access to the Large Language Model (LLM) text completion service. It allows you to specify both a system prompt (which sets the AI's behavior and context) and a user prompt (the actual query or task), giving you complete control over the LLM interaction.
This is useful for custom AI tasks, experimentation with prompts, and direct LLM integration without the overhead of retrieval augmented generation or agent frameworks.
## Options
### Required Arguments
- `system`: System prompt that defines the AI's role and behavior
- `prompt`: User prompt containing the actual query or task
### Optional Arguments
- `-u, --url URL`: TrustGraph API URL (default: `$TRUSTGRAPH_URL` or `http://localhost:8088/`)
- `-f, --flow-id FLOW`: Flow ID to use (default: `default`)
## Arguments
The command requires exactly two positional arguments:
1. **System Prompt**: Sets the AI's context, role, and behavior
2. **User Prompt**: The specific question, task, or content to process
## Examples
### Basic Question Answering
```bash
tg-invoke-llm "You are a helpful assistant." "What is the capital of France?"
```
### Code Generation
```bash
tg-invoke-llm \
"You are an expert Python programmer." \
"Write a function to calculate the Fibonacci sequence."
```
### Creative Writing
```bash
tg-invoke-llm \
"You are a creative writer specializing in science fiction." \
"Write a short story about time travel in 200 words."
```
### Technical Documentation
```bash
tg-invoke-llm \
"You are a technical writer who creates clear, concise documentation." \
"Explain how REST APIs work in simple terms."
```
### Data Analysis
```bash
tg-invoke-llm \
"You are a data analyst expert at interpreting statistics." \
"Explain what a p-value means and when it's significant."
```
### Using Specific Flow
```bash
tg-invoke-llm \
"You are a medical expert." \
"Explain the difference between Type 1 and Type 2 diabetes." \
-f medical-flow
```
## System Prompt Design
The system prompt is crucial for getting good results:
### Role Definition
```bash
"You are a [role] with expertise in [domain]."
```
### Behavior Instructions
```bash
"You are helpful, accurate, and concise. Always provide examples."
```
### Output Format
```bash
"You are a technical writer. Always structure your responses with clear headings and bullet points."
```
### Constraints
```bash
"You are a helpful assistant. Keep responses under 100 words and always cite sources when possible."
```
## Output Format
The command returns the LLM's response directly:
```
The capital of France is Paris. Paris has been the capital city of France since the late 10th century and is located in the north-central part of the country along the Seine River. It is the most populous city in France with over 2 million inhabitants in the city proper and over 12 million in the metropolitan area.
```
## Prompt Engineering Tips
### Effective System Prompts
- **Be Specific**: Clearly define the AI's role and expertise
- **Set Tone**: Specify the desired communication style
- **Include Constraints**: Set limits on response length or format
- **Provide Context**: Give relevant background information
### Effective User Prompts
- **Be Clear**: State exactly what you want
- **Provide Examples**: Show the desired output format
- **Add Context**: Include relevant background information
- **Specify Format**: Request specific output structure
## Error Handling
### Flow Not Available
```bash
Exception: Invalid flow
```
**Solution**: Verify the flow exists and is running with `tg-show-flows`.
### Connection Errors
```bash
Exception: Connection refused
```
**Solution**: Check the API URL and ensure TrustGraph is running.
### Prompt Errors
```bash
Exception: Invalid prompt format
```
**Solution**: Ensure both system and user prompts are provided as separate arguments.
## Environment Variables
- `TRUSTGRAPH_URL`: Default API URL
## Related Commands
- [`tg-invoke-agent`](tg-invoke-agent.md) - Interactive agent with tools and reasoning
- [`tg-invoke-graph-rag`](tg-invoke-graph-rag.md) - Graph-based retrieval augmented generation
- [`tg-invoke-document-rag`](tg-invoke-document-rag.md) - Document-based retrieval augmented generation
- [`tg-invoke-prompt`](tg-invoke-prompt.md) - Use predefined prompt templates
## API Integration
This command uses the [Text Completion API](../apis/api-text-completion.md) to perform direct LLM inference with custom prompts.
## Use Cases
### Development and Testing
```bash
# Test prompt variations
tg-invoke-llm "You are a code reviewer." "Review this Python function: def add(a, b): return a + b"
# Experiment with different system prompts
tg-invoke-llm "You are a harsh critic." "What do you think of Python?"
tg-invoke-llm "You are an enthusiastic supporter." "What do you think of Python?"
```
### Content Generation
```bash
# Blog post writing
tg-invoke-llm \
"You are a technical blogger who writes engaging, informative content." \
"Write an introduction to machine learning for beginners."
# Marketing copy
tg-invoke-llm \
"You are a marketing copywriter focused on clear, compelling messaging." \
"Write a product description for a cloud storage service."
```
### Educational Applications
```bash
# Concept explanation
tg-invoke-llm \
"You are a teacher who explains complex topics in simple terms." \
"Explain quantum computing to a high school student."
# Study guides
tg-invoke-llm \
"You are an educational content creator specializing in study materials." \
"Create a study guide for photosynthesis."
```
### Business Applications
```bash
# Report summarization
tg-invoke-llm \
"You are a business analyst who creates executive summaries." \
"Summarize the key points from this quarterly report: [report text]"
# Email drafting
tg-invoke-llm \
"You are a professional communication expert." \
"Draft a polite follow-up email for a job interview."
```
### Research and Analysis
```bash
# Literature review
tg-invoke-llm \
"You are a research academic who analyzes scientific literature." \
"What are the current trends in renewable energy research?"
# Competitive analysis
tg-invoke-llm \
"You are a market research analyst." \
"Compare the features of different cloud computing platforms."
```
## Advanced Techniques
### Multi-step Reasoning
```bash
# Chain of thought prompting
tg-invoke-llm \
"You are a logical reasoner. Work through problems step by step." \
"If a train travels 60 mph for 2 hours, then 80 mph for 1 hour, what's the average speed?"
```
### Format Control
```bash
# JSON output
tg-invoke-llm \
"You are a data processor. Always respond with valid JSON." \
"Convert this to JSON: Name: John, Age: 30, City: New York"
# Structured responses
tg-invoke-llm \
"You are a technical writer. Use markdown formatting with headers and lists." \
"Explain the software development lifecycle."
```
### Domain Expertise
```bash
# Legal analysis
tg-invoke-llm \
"You are a legal expert specializing in contract law." \
"What are the key elements of a valid contract?"
# Medical information
tg-invoke-llm \
"You are a medical professional. Provide accurate, evidence-based information." \
"What are the symptoms of Type 2 diabetes?"
```
## Best Practices
1. **Clear System Prompts**: Define the AI's role and behavior explicitly
2. **Specific User Prompts**: Be precise about what you want
3. **Iterative Refinement**: Experiment with different prompt variations
4. **Output Validation**: Verify the quality and accuracy of responses
5. **Appropriate Flows**: Use flows configured for your specific domain
6. **Length Considerations**: Balance detail with conciseness in prompts

241
docs/cli/tg-put-kg-core.md Normal file
View file

@ -0,0 +1,241 @@
# tg-put-kg-core
Stores a knowledge core in the TrustGraph system from MessagePack format.
## Synopsis
```bash
tg-put-kg-core --id CORE_ID -i INPUT_FILE [options]
```
## Description
The `tg-put-kg-core` command loads a knowledge core from a MessagePack-formatted file and stores it in the TrustGraph knowledge system. Knowledge cores contain RDF triples and graph embeddings that represent structured knowledge and can be loaded into flows for processing.
This command processes MessagePack files containing both triples (RDF knowledge) and graph embeddings (vector representations) and stores them via WebSocket connection to the Knowledge API.
## Options
### Required Arguments
- `--id, --identifier CORE_ID`: Unique identifier for the knowledge core
- `-i, --input INPUT_FILE`: Path to MessagePack input file
### Optional Arguments
- `-u, --url URL`: TrustGraph API URL (default: `$TRUSTGRAPH_URL` or `ws://localhost:8088/`)
- `-U, --user USER`: User identifier (default: `trustgraph`)
## Examples
### Store Knowledge Core
```bash
tg-put-kg-core --id "research-core-v1" -i knowledge.msgpack
```
### With Custom User
```bash
tg-put-kg-core \
--id "medical-knowledge" \
-i medical-data.msgpack \
-U researcher
```
### Using Custom API URL
```bash
tg-put-kg-core \
--id "production-core" \
-i prod-knowledge.msgpack \
-u ws://production:8088/
```
## Input File Format
The input file must be in MessagePack format containing structured knowledge data:
### MessagePack Structure
The file contains tuples with type indicators:
#### Triple Data (`"t"`)
```python
("t", {
"m": { # metadata
"i": "core-id",
"m": [], # metadata triples
"u": "user",
"c": "collection"
},
"t": [ # triples array
{
"s": {"value": "subject", "is_uri": true},
"p": {"value": "predicate", "is_uri": true},
"o": {"value": "object", "is_uri": false}
}
]
})
```
#### Graph Embeddings Data (`"ge"`)
```python
("ge", {
"m": { # metadata
"i": "core-id",
"m": [], # metadata triples
"u": "user",
"c": "collection"
},
"e": [ # entities array
{
"e": {"value": "entity", "is_uri": true},
"v": [[0.1, 0.2, 0.3]] # vectors
}
]
})
```
## Processing Flow
1. **File Reading**: Opens MessagePack file for binary reading
2. **Message Unpacking**: Unpacks MessagePack tuples sequentially
3. **Type Processing**: Handles both triples (`"t"`) and graph embeddings (`"ge"`)
4. **WebSocket Transmission**: Sends each message via WebSocket to Knowledge API
5. **Response Handling**: Waits for confirmation of each message
6. **Progress Reporting**: Shows count of processed messages
## Output
The command reports the number of messages processed:
```bash
Put: 150 triple, 75 GE messages.
```
Where:
- **triple**: Number of triple data messages processed
- **GE**: Number of graph embedding messages processed
## Error Handling
### File Not Found
```bash
Exception: No such file or directory: 'missing.msgpack'
```
**Solution**: Verify the input file path exists and is readable.
### Invalid MessagePack Format
```bash
Exception: Unpacked unexpected message type 'x'
```
**Solution**: Ensure the input file is properly formatted MessagePack with correct type indicators.
### Connection Errors
```bash
Exception: Connection refused
```
**Solution**: Verify the API URL and ensure TrustGraph is running.
### Knowledge API Errors
```bash
Exception: Knowledge core operation failed
```
**Solution**: Check that the Knowledge API is available and the core ID is valid.
## File Creation
MessagePack files can be created using:
### Python Example
```python
import msgpack
# Create triples data
triples_msg = ("t", {
"m": {"i": "core-id", "m": [], "u": "user", "c": "default"},
"t": [
{
"s": {"value": "Person1", "is_uri": True},
"p": {"value": "hasName", "is_uri": True},
"o": {"value": "John Doe", "is_uri": False}
}
]
})
# Create embeddings data
embeddings_msg = ("ge", {
"m": {"i": "core-id", "m": [], "u": "user", "c": "default"},
"e": [
{
"e": {"value": "Person1", "is_uri": True},
"v": [[0.1, 0.2, 0.3, 0.4]]
}
]
})
# Write to file
with open("knowledge.msgpack", "wb") as f:
msgpack.pack(triples_msg, f)
msgpack.pack(embeddings_msg, f)
```
### Export from Existing Core
```bash
# Export existing core to MessagePack
tg-get-kg-core --id "existing-core" -o exported.msgpack
# Import to new core
tg-put-kg-core --id "new-core" -i exported.msgpack
```
## Environment Variables
- `TRUSTGRAPH_URL`: Default API URL (automatically converted to WebSocket format)
## Related Commands
- [`tg-get-kg-core`](tg-get-kg-core.md) - Retrieve knowledge core
- [`tg-load-kg-core`](tg-load-kg-core.md) - Load knowledge core into flow
- [`tg-show-kg-cores`](tg-show-kg-cores.md) - List available knowledge cores
- [`tg-delete-kg-core`](tg-delete-kg-core.md) - Remove knowledge core
- [`tg-dump-msgpack`](tg-dump-msgpack.md) - Debug MessagePack files
## API Integration
This command uses the [Knowledge API](../apis/api-knowledge.md) via WebSocket connection with `put-kg-core` operations to store knowledge data.
## Use Cases
### Knowledge Import
```bash
# Import knowledge from external systems
tg-put-kg-core --id "external-kb" -i imported-knowledge.msgpack
```
### Data Migration
```bash
# Migrate knowledge between environments
tg-get-kg-core --id "prod-core" -o backup.msgpack
tg-put-kg-core --id "dev-core" -i backup.msgpack
```
### Knowledge Versioning
```bash
# Store versioned knowledge cores
tg-put-kg-core --id "research-v2.0" -i research-updated.msgpack
```
### Batch Knowledge Loading
```bash
# Load multiple knowledge domains
tg-put-kg-core --id "medical-core" -i medical.msgpack
tg-put-kg-core --id "legal-core" -i legal.msgpack
tg-put-kg-core --id "technical-core" -i technical.msgpack
```
## Best Practices
1. **Unique IDs**: Use descriptive, unique identifiers for knowledge cores
2. **Versioning**: Include version information in core IDs
3. **Validation**: Verify MessagePack files before importing
4. **Backup**: Keep backup copies of important knowledge cores
5. **Documentation**: Document knowledge core contents and sources
6. **Testing**: Test imports with small datasets first

207
docs/cli/tg-show-flows.md Normal file
View file

@ -0,0 +1,207 @@
# tg-show-flows
Shows configured flows with their interfaces and queue information.
## Synopsis
```bash
tg-show-flows [options]
```
## Description
The `tg-show-flows` command displays all currently configured flow instances, including their identifiers, class names, descriptions, and available service interfaces with corresponding Pulsar queue names.
This command is essential for understanding what flows are available, discovering service endpoints, and finding Pulsar queue names for direct API integration.
## Options
- `-u, --api-url URL`: TrustGraph API URL (default: `$TRUSTGRAPH_URL` or `http://localhost:8088/`)
## Examples
### Show All Flows
```bash
tg-show-flows
```
### Using Custom API URL
```bash
tg-show-flows -u http://production:8088/
```
## Output Format
The command displays each flow in a formatted table with the following information:
```
+-------+---------------------------+
| id | research-flow |
| class | document-rag+graph-rag |
| desc | Research document pipeline |
| queue | agent request: non-persistent://tg/request/agent:default |
| | agent response: non-persistent://tg/request/agent:default |
| | graph-rag request: non-persistent://tg/request/graph-rag:document-rag+graph-rag |
| | graph-rag response: non-persistent://tg/request/graph-rag:document-rag+graph-rag |
| | text-load: persistent://tg/flow/text-document-load:default |
+-------+---------------------------+
+-------+---------------------------+
| id | medical-analysis |
| class | medical-nlp |
| desc | Medical document analysis |
| queue | embeddings request: non-persistent://tg/request/embeddings:medical-nlp |
| | embeddings response: non-persistent://tg/request/embeddings:medical-nlp |
| | document-load: persistent://tg/flow/document-load:medical-analysis |
+-------+---------------------------+
```
### No Flows Available
```bash
No flows.
```
## Interface Types
The queue information shows two types of service interfaces:
### Request/Response Services
Services that accept requests and return responses:
```
agent request: non-persistent://tg/request/agent:default
agent response: non-persistent://tg/response/agent:default
```
### Fire-and-Forget Services
Services that accept data without returning responses:
```
text-load: persistent://tg/flow/text-document-load:default
```
## Service Interface Discovery
Use this command to discover available services and their queue names:
### Common Request/Response Services
- **agent**: Interactive Q&A service
- **graph-rag**: Graph-based retrieval augmented generation
- **document-rag**: Document-based retrieval augmented generation
- **text-completion**: LLM text completion service
- **prompt**: Prompt-based text generation
- **embeddings**: Text embedding generation
- **graph-embeddings**: Graph entity embeddings
- **triples**: Knowledge graph triple queries
### Common Fire-and-Forget Services
- **text-load**: Text document loading
- **document-load**: Document file loading
- **triples-store**: Knowledge graph storage
- **graph-embeddings-store**: Graph embedding storage
- **document-embeddings-store**: Document embedding storage
- **entity-contexts-load**: Entity context loading
## Queue Name Patterns
### Flow-Hosted Request/Response
```
non-persistent://tg/request/{service}:{flow-class}
non-persistent://tg/response/{service}:{flow-class}
```
### Flow-Hosted Fire-and-Forget
```
persistent://tg/flow/{service}:{flow-id}
```
## Error Handling
### Connection Errors
```bash
Exception: Connection refused
```
**Solution**: Verify the API URL and ensure TrustGraph is running.
### Authentication Errors
```bash
Exception: Unauthorized
```
**Solution**: Check authentication credentials and permissions.
## Environment Variables
- `TRUSTGRAPH_URL`: Default API URL
## Related Commands
- [`tg-start-flow`](tg-start-flow.md) - Start a new flow instance
- [`tg-stop-flow`](tg-stop-flow.md) - Stop a running flow
- [`tg-show-flow-classes`](tg-show-flow-classes.md) - List available flow classes
- [`tg-show-flow-state`](tg-show-flow-state.md) - Show detailed flow status
- [`tg-show-config`](tg-show-config.md) - Show complete system configuration
## API Integration
This command uses the [Flow API](../apis/api-flow.md) to list flows and the [Config API](../apis/api-config.md) to retrieve interface descriptions.
## Use Cases
### Service Discovery
Find available services and their endpoints:
```bash
# List all flows and their services
tg-show-flows
# Use discovered queue names for direct Pulsar integration
```
### System Monitoring
Monitor active flows and their configurations:
```bash
# Check what flows are running
tg-show-flows
# Verify flow services are properly configured
```
### Development and Debugging
Understand flow configurations during development:
```bash
# Check if flow started correctly
tg-start-flow -n "my-class" -i "test-flow" -d "Test"
tg-show-flows
# Verify service interfaces are available
```
### Integration Planning
Plan API integrations by understanding available services:
```bash
# Discover queue names for Pulsar clients
tg-show-flows | grep "graph-rag request"
# Find WebSocket endpoints for real-time services
```
## Output Interpretation
### Flow Information
- **id**: Unique flow instance identifier
- **class**: Flow class name used to create the instance
- **desc**: Human-readable flow description
- **queue**: Service interfaces and their Pulsar queue names
### Queue Names
Queue names indicate:
- **Persistence**: `persistent://` vs `non-persistent://`
- **Tenant**: Usually `tg`
- **Namespace**: `request`, `response`, or `flow`
- **Service**: The specific service name
- **Flow Identifier**: Either flow class or flow ID
## Best Practices
1. **Regular Monitoring**: Check flows regularly to ensure they're running correctly
2. **Queue Documentation**: Save queue names for API integration documentation
3. **Flow Lifecycle**: Use in conjunction with flow start/stop commands
4. **Capacity Planning**: Monitor number of active flows for resource planning
5. **Service Discovery**: Use output to understand available capabilities

View file

@ -0,0 +1,227 @@
# tg-show-kg-cores
Shows available knowledge cores in the TrustGraph system.
## Synopsis
```bash
tg-show-kg-cores [options]
```
## Description
The `tg-show-kg-cores` command lists all knowledge cores available in the TrustGraph system for a specific user. Knowledge cores contain structured knowledge (RDF triples and graph embeddings) that can be loaded into flows for processing and querying.
This command is useful for discovering what knowledge resources are available, managing knowledge core inventories, and preparing for knowledge loading operations.
## Options
- `-u, --api-url URL`: TrustGraph API URL (default: `$TRUSTGRAPH_URL` or `http://localhost:8088/`)
- `-U, --user USER`: User identifier (default: `trustgraph`)
## Examples
### List All Knowledge Cores
```bash
tg-show-kg-cores
```
### List Cores for Specific User
```bash
tg-show-kg-cores -U researcher
```
### Using Custom API URL
```bash
tg-show-kg-cores -u http://production:8088/
```
## Output Format
The command lists knowledge core identifiers, one per line:
```
medical-knowledge-v1
research-papers-2024
legal-documents-core
technical-specifications
climate-data-march
```
### No Knowledge Cores
```bash
No knowledge cores.
```
## Knowledge Core Naming
Knowledge cores typically follow naming conventions that include:
- **Domain**: `medical-`, `legal-`, `technical-`
- **Content Type**: `papers-`, `documents-`, `data-`
- **Version/Date**: `v1`, `2024`, `march`
Example patterns:
- `medical-knowledge-v2.1`
- `research-papers-2024-q1`
- `legal-documents-updated`
- `technical-specs-current`
## Related Operations
After discovering knowledge cores, you can:
### Load into Flow
```bash
# Load core into active flow
tg-load-kg-core --kg-core-id "medical-knowledge-v1" --flow-id "medical-flow"
```
### Examine Contents
```bash
# Export core for examination
tg-get-kg-core --id "research-papers-2024" -o examination.msgpack
```
### Remove Unused Cores
```bash
# Delete obsolete cores
tg-delete-kg-core --id "old-knowledge-v1" -U researcher
```
## Error Handling
### Connection Errors
```bash
Exception: Connection refused
```
**Solution**: Verify the API URL and ensure TrustGraph is running.
### Authentication Errors
```bash
Exception: Unauthorized
```
**Solution**: Check authentication credentials and user permissions.
### User Not Found
```bash
Exception: User not found
```
**Solution**: Verify the user identifier exists in the system.
## Environment Variables
- `TRUSTGRAPH_URL`: Default API URL
## Related Commands
- [`tg-put-kg-core`](tg-put-kg-core.md) - Store knowledge core from file
- [`tg-get-kg-core`](tg-get-kg-core.md) - Retrieve knowledge core to file
- [`tg-load-kg-core`](tg-load-kg-core.md) - Load knowledge core into flow
- [`tg-delete-kg-core`](tg-delete-kg-core.md) - Remove knowledge core
- [`tg-unload-kg-core`](tg-unload-kg-core.md) - Unload knowledge core from flow
## API Integration
This command uses the [Knowledge API](../apis/api-knowledge.md) with the `list-kg-cores` operation to retrieve available knowledge cores.
## Use Cases
### Knowledge Inventory
```bash
# Check what knowledge is available
tg-show-kg-cores
# Document available knowledge resources
tg-show-kg-cores > knowledge-inventory.txt
```
### Pre-Processing Verification
```bash
# Verify knowledge cores exist before loading
tg-show-kg-cores | grep "medical"
tg-load-kg-core --kg-core-id "medical-knowledge-v1" --flow-id "medical-flow"
```
### Multi-User Management
```bash
# Check knowledge for different users
tg-show-kg-cores -U researcher
tg-show-kg-cores -U analyst
tg-show-kg-cores -U admin
```
### Knowledge Discovery
```bash
# Find knowledge cores by pattern
tg-show-kg-cores | grep "2024"
tg-show-kg-cores | grep "medical"
tg-show-kg-cores | grep "v[0-9]"
```
### System Administration
```bash
# Audit knowledge core usage
for user in $(cat users.txt); do
echo "User: $user"
tg-show-kg-cores -U $user
echo
done
```
### Development Workflow
```bash
# Check development knowledge cores
tg-show-kg-cores -U developer | grep "test"
# Load test knowledge for development
tg-load-kg-core --kg-core-id "test-knowledge" --flow-id "dev-flow"
```
## Knowledge Core Lifecycle
1. **Creation**: Knowledge cores created via `tg-put-kg-core` or document processing
2. **Discovery**: Use `tg-show-kg-cores` to find available cores
3. **Loading**: Load cores into flows with `tg-load-kg-core`
4. **Usage**: Query loaded knowledge via RAG or agent services
5. **Management**: Update, backup, or remove cores as needed
## Best Practices
1. **Regular Inventory**: Check available knowledge cores regularly
2. **Naming Conventions**: Use consistent naming for easier discovery
3. **User Organization**: Organize knowledge cores by user and purpose
4. **Version Management**: Track knowledge core versions and updates
5. **Cleanup**: Remove obsolete knowledge cores to save storage
6. **Documentation**: Document knowledge core contents and purposes
## Integration with Other Commands
### Knowledge Loading Workflow
```bash
# 1. Discover available knowledge
tg-show-kg-cores
# 2. Start appropriate flow
tg-start-flow -n "research-class" -i "research-flow" -d "Research analysis"
# 3. Load relevant knowledge
tg-load-kg-core --kg-core-id "research-papers-2024" --flow-id "research-flow"
# 4. Query the knowledge
tg-invoke-graph-rag -q "What are the latest research trends?" -f "research-flow"
```
### Knowledge Management Workflow
```bash
# 1. Audit current knowledge
tg-show-kg-cores > current-cores.txt
# 2. Import new knowledge
tg-put-kg-core --id "new-research-2024" -i new-research.msgpack
# 3. Verify import
tg-show-kg-cores | grep "new-research-2024"
# 4. Remove old versions
tg-delete-kg-core --id "old-research-2023"
```

189
docs/cli/tg-start-flow.md Normal file
View file

@ -0,0 +1,189 @@
# tg-start-flow
Starts a processing flow using a defined flow class.
## Synopsis
```bash
tg-start-flow -n CLASS_NAME -i FLOW_ID -d DESCRIPTION [options]
```
## Description
The `tg-start-flow` command creates and starts a new processing flow instance based on a predefined flow class. Flow classes define the processing pipeline configuration, while flow instances are running implementations of those classes with specific identifiers.
Once started, a flow provides endpoints for document processing, knowledge queries, and other TrustGraph services through its configured interfaces.
## Options
### Required Arguments
- `-n, --class-name CLASS_NAME`: Name of the flow class to instantiate
- `-i, --flow-id FLOW_ID`: Unique identifier for the new flow instance
- `-d, --description DESCRIPTION`: Human-readable description of the flow
### Optional Arguments
- `-u, --api-url URL`: TrustGraph API URL (default: `$TRUSTGRAPH_URL` or `http://localhost:8088/`)
## Examples
### Start Basic Document Processing Flow
```bash
tg-start-flow \
-n "document-rag+graph-rag" \
-i "research-flow" \
-d "Research document processing pipeline"
```
### Start Custom Flow Class
```bash
tg-start-flow \
-n "medical-analysis" \
-i "medical-research-2024" \
-d "Medical research analysis for 2024 studies"
```
### Using Custom API URL
```bash
tg-start-flow \
-n "document-processing" \
-i "production-flow" \
-d "Production document processing" \
-u http://production:8088/
```
## Prerequisites
### Flow Class Must Exist
Before starting a flow, the flow class must be available in the system:
```bash
# Check available flow classes
tg-show-flow-classes
# Upload a flow class if needed
tg-put-flow-class -n "my-class" -f flow-definition.json
```
### System Requirements
- TrustGraph API gateway must be running
- Required processing components must be available
- Sufficient system resources for the flow's processing needs
## Flow Lifecycle
1. **Flow Class Definition**: Flow classes define processing pipelines
2. **Flow Instance Creation**: `tg-start-flow` creates a running instance
3. **Service Availability**: Flow provides configured service endpoints
4. **Processing**: Documents and queries can be processed through the flow
5. **Flow Termination**: Use `tg-stop-flow` to stop the instance
## Error Handling
### Flow Class Not Found
```bash
Exception: Flow class 'invalid-class' not found
```
**Solution**: Check available flow classes with `tg-show-flow-classes` and ensure the class name is correct.
### Flow ID Already Exists
```bash
Exception: Flow ID 'my-flow' already exists
```
**Solution**: Choose a different flow ID or stop the existing flow with `tg-stop-flow`.
### Connection Errors
```bash
Exception: Connection refused
```
**Solution**: Verify the API URL and ensure TrustGraph is running.
### Resource Errors
```bash
Exception: Insufficient resources to start flow
```
**Solution**: Check system resources and ensure required processing components are available.
## Output
On successful flow creation:
```bash
Flow 'research-flow' started successfully using class 'document-rag+graph-rag'
```
## Flow Configuration
Once started, flows provide service interfaces based on their class definition. Common interfaces include:
### Request/Response Services
- **agent**: Interactive Q&A service
- **graph-rag**: Graph-based retrieval augmented generation
- **document-rag**: Document-based retrieval augmented generation
- **text-completion**: LLM text completion
- **embeddings**: Text embedding generation
- **triples**: Knowledge graph queries
### Fire-and-Forget Services
- **text-load**: Text document loading
- **document-load**: Document file loading
- **triples-store**: Knowledge graph storage
## Environment Variables
- `TRUSTGRAPH_URL`: Default API URL
## Related Commands
- [`tg-stop-flow`](tg-stop-flow.md) - Stop a running flow
- [`tg-show-flows`](tg-show-flows.md) - List active flows and their interfaces
- [`tg-show-flow-classes`](tg-show-flow-classes.md) - List available flow classes
- [`tg-put-flow-class`](tg-put-flow-class.md) - Upload/update flow class definitions
- [`tg-show-flow-state`](tg-show-flow-state.md) - Check flow status
## API Integration
This command uses the [Flow API](../apis/api-flow.md) with the `start-flow` operation to create and start flow instances.
## Use Cases
### Development Environment
```bash
tg-start-flow \
-n "dev-pipeline" \
-i "dev-$(date +%Y%m%d)" \
-d "Development testing flow for $(date)"
```
### Research Projects
```bash
tg-start-flow \
-n "research-analysis" \
-i "climate-study" \
-d "Climate change research document analysis"
```
### Production Processing
```bash
tg-start-flow \
-n "production-pipeline" \
-i "prod-primary" \
-d "Primary production document processing pipeline"
```
### Specialized Processing
```bash
tg-start-flow \
-n "medical-nlp" \
-i "medical-trials" \
-d "Medical trial document analysis and extraction"
```
## Best Practices
1. **Descriptive IDs**: Use meaningful flow IDs that indicate purpose and scope
2. **Clear Descriptions**: Provide detailed descriptions for flow tracking
3. **Resource Planning**: Ensure adequate resources before starting flows
4. **Monitoring**: Use `tg-show-flows` to monitor active flows
5. **Cleanup**: Stop unused flows to free up resources
6. **Documentation**: Document flow purposes and configurations for team use

256
docs/cli/tg-stop-flow.md Normal file
View file

@ -0,0 +1,256 @@
# tg-stop-flow
Stops a running processing flow.
## Synopsis
```bash
tg-stop-flow -i FLOW_ID [options]
```
## Description
The `tg-stop-flow` command terminates a running flow instance and releases its associated resources. When a flow is stopped, it becomes unavailable for processing requests, and all its service endpoints are shut down.
This command is essential for flow lifecycle management, resource cleanup, and system maintenance operations.
## Options
### Required Arguments
- `-i, --flow-id FLOW_ID`: Identifier of the flow to stop
### Optional Arguments
- `-u, --api-url URL`: TrustGraph API URL (default: `$TRUSTGRAPH_URL` or `http://localhost:8088/`)
## Examples
### Stop Specific Flow
```bash
tg-stop-flow -i research-flow
```
### Using Custom API URL
```bash
tg-stop-flow -i production-flow -u http://production:8088/
```
### Stop Multiple Flows
```bash
# Stop multiple flows in sequence
tg-stop-flow -i dev-flow-1
tg-stop-flow -i dev-flow-2
tg-stop-flow -i test-flow
```
## Prerequisites
### Flow Must Exist and Be Running
Before stopping a flow, verify it exists:
```bash
# Check running flows
tg-show-flows
# Stop the desired flow
tg-stop-flow -i my-flow
```
## Flow Termination Process
1. **Request Validation**: Verifies flow exists and is running
2. **Service Shutdown**: Stops all flow service endpoints
3. **Resource Cleanup**: Releases allocated system resources
4. **Queue Cleanup**: Cleans up associated Pulsar queues
5. **State Update**: Updates flow status to stopped
## Impact of Stopping Flows
### Service Unavailability
Once stopped, the flow's services become unavailable:
- REST API endpoints return errors
- WebSocket connections are terminated
- Pulsar queues are cleaned up
### In-Progress Operations
- **Completed**: Already finished operations remain completed
- **Active**: In-progress operations may be interrupted
- **Queued**: Pending operations are lost
### Resource Recovery
- **Memory**: Memory allocated to flow components is freed
- **CPU**: Processing resources are returned to system pool
- **Storage**: Temporary storage is cleaned up
## Error Handling
### Flow Not Found
```bash
Exception: Flow 'invalid-flow' not found
```
**Solution**: Check available flows with `tg-show-flows` and verify the flow ID.
### Flow Already Stopped
```bash
Exception: Flow 'my-flow' is not running
```
**Solution**: The flow is already stopped. Use `tg-show-flows` to check current status.
### Connection Errors
```bash
Exception: Connection refused
```
**Solution**: Verify the API URL and ensure TrustGraph is running.
### Permission Errors
```bash
Exception: Insufficient permissions to stop flow
```
**Solution**: Check user permissions and authentication credentials.
## Output
On successful flow termination:
```bash
Flow 'research-flow' stopped successfully.
```
No output typically indicates successful operation.
## Flow Management Workflow
### Development Cycle
```bash
# 1. Start flow for development
tg-start-flow -n "dev-class" -i "dev-flow" -d "Development testing"
# 2. Use flow for testing
tg-invoke-graph-rag -q "test query" -f dev-flow
# 3. Stop flow when done
tg-stop-flow -i dev-flow
```
### Resource Management
```bash
# Check active flows
tg-show-flows
# Stop unused flows to free resources
tg-stop-flow -i old-research-flow
tg-stop-flow -i temporary-test-flow
```
### System Maintenance
```bash
# Stop all flows before maintenance
for flow in $(tg-show-flows | grep "id" | awk '{print $2}'); do
tg-stop-flow -i "$flow"
done
```
## Safety Considerations
### Data Preservation
- **Knowledge Cores**: Loaded knowledge cores are preserved
- **Library Documents**: Library documents remain intact
- **Configuration**: System configuration is unaffected
### Service Dependencies
- **Dependent Services**: Ensure no critical services depend on the flow
- **Active Users**: Notify users before stopping production flows
- **Scheduled Operations**: Check for scheduled operations using the flow
## Environment Variables
- `TRUSTGRAPH_URL`: Default API URL
## Related Commands
- [`tg-start-flow`](tg-start-flow.md) - Start a new flow instance
- [`tg-show-flows`](tg-show-flows.md) - List active flows
- [`tg-show-flow-state`](tg-show-flow-state.md) - Check detailed flow status
- [`tg-show-flow-classes`](tg-show-flow-classes.md) - List available flow classes
## API Integration
This command uses the [Flow API](../apis/api-flow.md) with the `stop-flow` operation to terminate flow instances.
## Use Cases
### Development Environment Cleanup
```bash
# Clean up development flows at end of day
tg-stop-flow -i dev-$(whoami)
tg-stop-flow -i test-experimental
```
### Resource Optimization
```bash
# Stop idle flows to free resources
tg-show-flows | grep "idle" | while read flow; do
tg-stop-flow -i "$flow"
done
```
### Environment Switching
```bash
# Switch from development to production configuration
tg-stop-flow -i dev-flow
tg-start-flow -n "production-class" -i "prod-flow" -d "Production processing"
```
### Maintenance Operations
```bash
# Prepare for system maintenance
echo "Stopping all flows for maintenance..."
tg-show-flows | grep -E "^[a-z-]+" | while read flow_id; do
echo "Stopping $flow_id"
tg-stop-flow -i "$flow_id"
done
```
### Flow Recycling
```bash
# Restart flow with fresh configuration
tg-stop-flow -i my-flow
tg-start-flow -n "updated-class" -i "my-flow" -d "Updated configuration"
```
## Best Practices
1. **Graceful Shutdown**: Allow in-progress operations to complete when possible
2. **User Notification**: Inform users before stopping production flows
3. **Resource Monitoring**: Check system resources after stopping flows
4. **Documentation**: Record why flows were stopped for audit purposes
5. **Verification**: Confirm flow stopped successfully with `tg-show-flows`
6. **Cleanup Planning**: Plan flow stops during low-usage periods
## Troubleshooting
### Flow Won't Stop
```bash
# Check flow status
tg-show-flow-state -i problematic-flow
# Force stop if necessary (implementation dependent)
# Contact system administrator if flow remains stuck
```
### Resource Not Released
```bash
# Check system resources after stopping
ps aux | grep trustgraph
netstat -an | grep 8088
# Restart TrustGraph if resources not properly released
```
### Service Still Responding
```bash
# Verify flow services are actually stopped
tg-invoke-graph-rag -q "test" -f stopped-flow
# Should return flow not found error
```