# Example Projects
Explore sample projects built with Mira Flows
Discover practical implementations of Mira Flows through our curated collection of example projects. Each example includes complete source code and demonstrates different aspects of the platform.
Complete implementation showing how to integrate and use pre-built flows from the Mira Flows marketplace.
Step-by-step example of creating and deploying custom flows using the Mira Flows SDK.
Example project demonstrating dataset creation, management, and RAG integration with flows.
# Video Tutorials
Learn Mira Flows through step-by-step video guides
Get started with Mira Flows through our comprehensive video tutorials. Each tutorial provides a detailed walkthrough of key platform features and implementation steps.
Learn how to discover, integrate, and use pre-built flows from the Mira Flows marketplace in your applications.
Follow along to create your first custom flow using the Mira Flows SDK and deploy it to the marketplace.
Step-by-step guide to creating and configuring datasets for enhanced RAG capabilities.
# Compound Flows
Step-by-step guide to installing and setting up Mira Flows SDK for your project
A Compound Flow is an advanced flow type designed for complex, multi-stage processing pipelines. Unlike Elemental Flows which perform single, focused tasks, Compound Flows can create sophisticated decision trees, implement custom processing logic, and orchestrate multiple processing stages. 🎯
## Compound Flow Attributes
### Version ⚡
| Component | Description | Required | Example |
| --------- | ---------------------------------------------------- | -------- | --------- |
| version | Flow specification version using semantic versioning | Yes | `"0.1.0"` |
### Metadata
| Component | Description | Required | Example |
| ----------- | --------------------------------- | -------- | ------------------------------------ |
| flow\_type | Type of flow (must be "compound") | Yes | `"compound"` |
| name | Unique identifier for the flow | Yes | `"your-flow-name"` |
| description | Explanation of flow's purpose | Yes | `"A brief description of your flow"` |
| author | Creator's username | Yes | `"your-username"` |
| tags | Keywords for categorization | No | `[tag1, tag2, tag3]` |
| private | Access control setting | Yes | `false` |
### Input Configuration
| Component | Description | Required | Example |
| ----------- | ------------------------------------------ | -------- | ------------------------------- |
| inputs | Map of input parameters | Yes | Collection of input definitions |
| type | Data type of input (currently only string) | Yes | `"string"` |
| description | Purpose of the input | Yes | `"Description of input1"` |
| required | Whether input is mandatory | Yes | `true` or `false` |
| example | Sample input value | No | `"Example value for input1"` |
### Workflow Configuration
Each Compound Flow must define a workflow consisting of multiple processing stages. There are two types of workflow stages:
#### Elemental Stage Configuration
| Component | Description | Required | Example |
| ----------- | ------------------------------------ | -------- | ---------------------- |
| type | Must be "elemental" | Yes | `"elemental"` |
| flow\_name | Reference to existing Elemental Flow | Yes | `"author/flow-name"` |
| inputs | Mapping to flow inputs | Yes | Input mapping object |
| depends\_on | List of dependent stages | No | `["stage1", "stage2"]` |
#### Custom Stage Configuration
| Component | Description | Required | Example |
| ----------- | ------------------------- | -------- | ---------------------------------- |
| type | Must be "custom" | Yes | `"custom"` |
| model | LLM configuration | Yes | Model settings object |
| prompt | Processing instructions | Yes | Template with {input} placeholders |
| inputs | Stage input parameters | Yes | Input mapping object |
| dataset | RAG dataset configuration | No | `"author_name/dataset_name"` |
| depends\_on | List of dependent stages | No | `["stage1", "stage2"]` |
### Dependency Configuration
| Component | Description | Required | Example |
| ----------- | -------------------------------------------------- | -------- | ---------------------- |
| depends\_on | List of stages that must complete before execution | No | `["stage1", "stage2"]` |
#### Execution Behavior
* Stages without depends\_on can execute in parallel
* Stages with depends\_on will wait for specified stages to complete
* Multiple stages can depend on the same previous stage
### Output Configuration
| Component | Description | Required | Example |
| ------------ | -------------------------------- | -------- | ---------------------------------------- |
| output.value | List of stage outputs to combine | Yes | `[${stage1.outputs}, ${stage2.outputs}]` |
## Basic Flow Structure
```yaml .yaml
# Flow specification version
version: "0.1.0"
# Flow metadata and configuration
metadata:
flow_type: "compound"
name: "your-flow-name"
description: "Describe what this compound flow accomplishes"
author: "your-username"
tags: [tag1, tag2, tag3]
private: true
# Primary input definitions
inputs:
prime_input_1:
type: string
description: "What this input is used for"
required: true
example: "Example value"
prime_input_2:
type: string
description: "Description of this input"
required: false
example: "Example"
# Workflow definition
workflow:
# Elemental Flow stage - starts immediately
first_flow:
type: "elemental"
flow_name: "john_doe/first_elemental_flow"
inputs:
abc: ${inputs.prime_input_1}
xyz: ${inputs.prime_input_2}
# Custom processing stage - starts immediately (parallel to first_flow)
second_flow:
type: "custom"
inputs:
input1: ${inputs.input_name}
model:
provider: "provider-name"
name: "model-name"
prompt: |
Your flow's primary instruction or role...
You can use {input1} placeholders to reference inputs.
# Waits for both first_flow and second_flow to complete
third_flow:
type: "custom"
depends_on: [first_flow, second_flow]
inputs:
input1: ${first_flow.output}
input2: ${second_flow.output}
model:
provider: "provider-name"
name: "model-name"
dataset:
source: "author_name/dataset_name"
prompt: |
Your flow's primary instruction or role...
You can use {input1} and {input2} placeholders to reference inputs.
# Output configuration
output:
value:
- ${first_flow.output}
- ${second_flow.output}
- ${third_flow.output}
# Flow documentation
readme: |
This is a detailed explanation of what your flow does.
### Workflow Overview:
1. **First Flow**: Executes `john_doe/first_elemental_flow` with the provided inputs.
2. **Second Flow**: Runs in parallel with first flow
3. **Third Flow**: Depends on both previous flows, executes after they complete
### Outputs:
- Combined outputs from all flows are returned in order.
```
## Implementation Structure 🛠️
Compound Flows can either define custom processing logic within their workflow or integrate existing Elemental Flows, providing maximum flexibility for solving complex challenges. The workflow allows for:
1. Advanced Decision Making with conditional processing paths 🧠
2. Custom Processing stages with direct model and prompt configurations ⚙️
3. Integration of existing Elemental Flows for reusability 🔄
4. Parallel execution of independent stages ⚡
5. Sequential execution through depends\_on configurations 🔗
6. Flexible input/output mapping between stages 🔀
# Datasets and RAG
Step-by-step guide to installing and setting up Mira Flows SDK for your project
Datasets in **Mira Flows** support **Retrieval-Augmented Generation (RAG)** to enhance flows with specific knowledge. This capability allows flows to leverage custom knowledge bases for improved accuracy and contextual awareness in their responses. 🤖📈
***
## Dataset Attributes
| **Component** | **Description** | **Required** | **Example** |
| --------------- | ----------------------------- | ------------ | ----------------------------------- |
| **Name** | Unique identifier for dataset | Yes | `"author/dataset_name"` |
| **Description** | Purpose and content overview | Yes | `"Optional description"` |
| **Source Type** | Type of data being added | Yes | `"url"` or `"file_path"` |
| **Source Path** | Location of source data | Yes | `"example.com"` or `"path/to/file"` |
| **Author** | Creator's username | Yes | `"your-username"` |
***
## Supported File Formats
| **Format** | **Description** | **Processing Method** |
| ------------------ | --------------- | ----------------------------------- |
| **PDF (.pdf)** | Document files | Text extraction from document |
| **Markdown (.md)** | Formatted text | Text extraction from document |
| **URL** | Web content | Web content scraping |
| **CSV (.csv)** | URL listings | URL extraction and content scraping |
| **Text (.txt)** | Plain text | Direct text extraction |
***
## Creating and Configuring Datasets
### Creating a Dataset
```python Python
from mira_sdk import MiraClient
client = MiraClient(config={"API_KEY": "YOUR_API_KEY"})
# Create dataset
client.dataset.create("author/dataset_name", "Optional description")
```
### Adding Data Sources
```python Python
# Add URL to your dataset
client.dataset.add_source("author/dataset_name", url="example.com")
# Add file to your dataset
client.dataset.add_source("author/dataset_name", file_path="path/to/my/file.csv")
```
### Linking Dataset with Flow
Add the following configuration to your `flow.yaml` file:
```yaml .yaml
dataset:
source: "author/dataset_name"
```
***
# Elemental Flows
Understanding the fundamental building blocks of Mira Flows
An Elemental Flow is a self-contained, autonomous unit designed to perform specific, unique actions. These flows serve as the foundational building blocks within the Mira Flows ecosystem, enabling precise and reliable AI-powered operations.
## Elemental Flow Attributes
### Version
| Component | Description | Required | Example |
| --------- | ---------------------------------------------------- | -------- | --------- |
| version | Flow specification version using semantic versioning | Yes | `"0.0.1"` |
### Metadata
| Component | Description | Required | Example |
| ----------- | ------------------------------ | -------- | ------------------------------------ |
| name | Unique identifier for the flow | Yes | `"your-flow-name"` |
| description | Explanation of flow's purpose | Yes | `"A brief description of your flow"` |
| author | Creator's username | Yes | `"your-username"` |
| tags | Keywords for categorization | No | `[tag1, tag2, tag3]` |
| private | Access control setting | Yes | `false` |
### Input Configuration
Supported Input Types:
| Type | Description |
| ------ | ----------------------- |
| string | Text-based input values |
Input Structure:
| Component | Description | Required | Example |
| ----------- | ------------------------------------------ | -------- | ------------------------------- |
| inputs | Map of input parameters | Yes | Collection of input definitions |
| type | Data type of input (currently only string) | Yes | `"string"` |
| description | Purpose of the input | Yes | `"Description of input1"` |
| required | Whether input is mandatory | Yes | `true` or `false` |
| example | Sample input value | No | `"Example value for input1"` |
### Model Configuration
| Component | Description | Required | Example |
| --------- | ------------------------- | -------- | ----------------- |
| provider | AI service provider | Yes | `"provider-name"` |
| name | Specific model identifier | Yes | `"model-name"` |
### Dataset Configuration (Optional)
| Component | Description | Required | Example |
| --------- | -------------------- | -------- | ---------------------------- |
| source | Reference to dataset | No | `"author_name/dataset_name"` |
### Prompt and Readme Configuration
| Component | Description | Required | Example |
| --------- | ------------------------------- | -------- | ---------------------------------------------- |
| prompt | Instructions for model behavior | Yes | "Generate a tweet on the given topic: {topic}" |
| readme | Usage documentation | Yes | Markdown-formatted guide |
## Basic Flow Structure
The official YAML structure for a basic Mira Flow:
```yaml .yaml
version: "your.version.here"
metadata:
name: "your-flow-name"
description: "A brief description of your flow"
author: "your-username"
tags: [tag1, tag2, tag3]
private: false
inputs:
input1:
type: string
description: "Description of input1"
required: true
example: "Example value for input1"
input2:
type: string
description: "Description of input2"
required: true
example: "Example value for input2"
model:
provider: "provider-name"
name: "model-name"
prompt: |
Your flow's primary instruction or role...
You can use {input1} and {input2} placeholders to reference inputs.
readme: |
Your flow's readme...
You can use raw text or markdown here.
```
## RAG Integration 🔍
To integrate RAG capabilities, you'll need to:
1. Create a dataset
2. Add data sources to your dataset
3. Link the dataset to your flow
The following file formats are supported for datasets:
| File Type | Processing Method |
| -------------- | --------------------------------------- |
| PDF (.pdf) | Text extraction from document |
| Markdown (.md) | Text extraction from document |
| URL | Web content scraping |
| CSV (.csv) | URL extraction and content scraping |
| Text (.txt) | Direct text extraction |
| Zip (.zip) | Processing of contained supported files |
### Creating a Dataset 🗃️
```python
from mira_sdk import MiraClient
client = MiraClient(config={"API_KEY": "YOUR_API_KEY"})
# Create dataset
client.dataset.create("author/dataset_name", "Optional description")
```
### Adding Data Sources
```python
# Add URL to your dataset
client.dataset.add_source("author/dataset_name", url="example.com")
# Add file to your dataset
client.dataset.add_source("author/dataset_name", file_path="path/to/my/file.csv")
```
### Linking Dataset with Flow
Add the following configuration to your flow\.yaml file:
```yaml
dataset:
source: "author/dataset_name"
```
### Flow Structure with RAG
The official YAML structure for a flow with RAG capabilities:
```yaml
version: "your.version.here"
metadata:
name: "your-flow-name"
description: "A brief description of your flow"
author: "your-username"
tags: [tag1, tag2, tag3]
private: false
inputs:
input1:
type: string
description: "Description of input1"
required: true
example: "Example value for input1"
model:
provider: "provider-name"
name: "model-name"
dataset:
source: "author_name/dataset_name"
prompt: |
Your flow's primary instruction or role...
You can use {input1} placeholders to reference inputs.
readme: |
Your flow's readme...
You can use raw text or markdown here.
```
# Installation
Step-by-step guide to installing and setting up Mira Flows SDK for your project
## Account Setup
Sign up for your free Mira Flows account and begin your AI development journey.
Generate your API key from the API section - you'll need this to access Mira Flows features.
## Prerequisites
Mira flows requires **`Python >=3.9, <=3.13`**
```bash
# Check your Python version
python3 --version
```
Need to update? Visit [python.org/downloads](https://python.org/downloads)
## Installation Steps
1. Install the SDK using pip:
```bash
pip install mira-sdk
```
1. Initialize the client:
```python
from mira_sdk import MiraClient
client = MiraClient(config={"API_KEY": "YOUR_API_KEY"})
```
### Using Environment Variables (Recommended)
Install python-dotenv
```bash
pip install python-dotenv
```
Create a `.env` file in your project root and add:
```plaintext
MIRA_API_KEY=your_api_key_here
```
Then initialize the client using the environment variable:
```python
from dotenv import load_dotenv
from mira_sdk import MiraClient
import os
load_dotenv()
client = MiraClient(config={"API_KEY": os.getenv("MIRA_API_KEY")})
```
## Next Steps
Browse available flows to understand the platform's capabilities and start using pre-built solutions.
Follow our guide to build your own custom flow and unlock the full potential of Mira Flows.
# Introduction
Introduction to Mira Flows SDK
## What is Mira Flows SDK?
Mira Flows SDK is a powerful Python toolkit that enables developers to programmatically create, manage, and deploy AI-powered flows. From simple chat interfaces to complex multi-stage AI pipelines, the SDK provides a seamless interface to build sophisticated AI applications by combining Large Language Models (LLMs) with custom knowledge bases and configurable workflows.
## Key Features
Create, test, and deploy AI flows with minimal setup using straightforward YAML configurations - from basic chatbots to complex multi-stage pipelines
Enhance your flows with custom knowledge through easy integration of PDFs, markdown files, URLs, and more for context-aware AI solutions
Discover, use, and customize pre-built flows from our growing marketplace of AI solutions to accelerate development
## SDK Capabilities
* **Simple to Complex**: Build everything from basic Q\&A flows to sophisticated multi-stage processing pipelines
* **Actionable Flows**: Transform your flows into autonomous agents that can interact with external tools and APIs
* **Custom Knowledge Integration**: Enhance flows with domain-specific knowledge through RAG capabilities
* **Flow Composition**: Combine multiple flows to create complex AI workflows and processing chains
* **Extensible Design**: Add custom tools and integrations to expand your flows' capabilities
* **Scalable Architecture**: Handle increasing workloads with built-in scaling capabilities
## Getting Started
Sign up for a Mira Flows account to begin your AI development journey.
Set up the Mira Flows SDK in your development environment.
Discover available flows and explore the possibilities in our marketplace of AI solutions.
Connect with developers, and stay updated through our vibrant Discord community.
Start building powerful AI applications with Mira Flows SDK today! Follow our [installation guide](./installation.md) to begin your journey.
# Models
Step-by-step guide to installing and setting up Mira Flows SDK for your project
**Mira Flows** provides access to a selection of **Large Language Models (LLMs)** that serve as the computational engine for flows. Each model offers specific capabilities and performance characteristics suitable for different use cases. 🚀✨
***
## Model Attributes
| **Component** | **Description** | **Required** | **Example** |
| -------------- | ------------------------- | ------------ | -------------------------- |
| **Provider** | AI service provider | Yes | `"meta"` |
| **Model Name** | Specific model identifier | Yes | `"llama-3.3-70b-instruct"` |
***
## Available Models
| **Provider** | **Model Name** |
| ------------- | ------------------------ |
| **openai** | `gpt-4o` |
| **anthropic** | `claude-3.5-sonnet` |
| **meta** | `llama-3.3-70b-instruct` |
# Build Compound Flows
Learn how to build your own compound flow using Mira Flows SDK
This guide explains how to **create, test, and deploy compound flows** that implement complex, multi-stage processing pipelines. **Compound flows** provide sophisticated capabilities for implementing business logic, custom processing stages, and integration with existing **elemental flows**. 🔄💡
## Development Lifecycle
Creating a **compound flow** follows a systematic process:
Let's explore each step in detail.
***
Use **OpenAI (gpt-4o)** or **Anthropic (claude-3.5-sonnet)** models when building complex workflows to ensure optimal performance. Checkout [Available Models](documentation/get-started/models)
## Step 1: YAML Configuration
```yaml .yaml
# Flow specification version
version: "0.1.0" # Flow specification version
metadata:
flow_type: "compound" # Specifies this as a compound flow
name: "your-flow-name" # Unique identifier
description: "Describe what this compound flow accomplishes"
author: "your-username" # Your Mira Flows username
tags: [tag1, tag2, tag3] # Discovery keywords
private: true # Access control setting
inputs:
prime_input_1: # Primary input parameter
type: string
description: "What is this input used for"
required: true
example: "Example value"
prime_input_2: # Secondary input parameter
type: string
description: "Description of this input"
required: false
example: "Example"
workflow:
# Elemental Flow stage - starts immediately
first_flow: # First processing stage
type: "elemental"
flow_name: "john_doe/first_elemental_flow"
inputs:
abc: ${inputs.prime_input_1}
xyz: ${inputs.prime_input_2}
# Custom processing stage - starts immediately (parallel to first_flow)
second_flow: # Parallel processing stage
type: "custom"
inputs:
input1: ${inputs.prime_input_1}
model:
provider: "provider-name" # e.g., anthropic, openai, meta, etc.
name: "model-name" # Specific model identifier
prompt: |
Your flow's primary instruction or role...
You can use {input1} placeholders to reference inputs.
# Waits for both first_flow and second_flow to complete
third_flow:
type: "custom"
depends_on: [first_flow, second_flow] # Dependent on fist_flow and second_flow
inputs:
input1: ${first_flow.output} # uses output of first_flow as input
input2: ${second_flow.output} # uses output of second_flow as input
model:
provider: "provider-name"
name: "model-name"
dataset:
source: "author_name/dataset_name"
prompt: |
Your flow's primary instruction or role...
You can use {input1} and {input2} placeholders to reference inputs.
output:
value: # Combine & customise outputs in order
- ${first_flow.output}
- ${second_flow.output}
- ${third_flow.output}
readme: |
This is a detailed explanation of what your flow does.
### Workflow Overview:
1. **First Flow**: Executes `john_doe/first_elemental_flow` with the provided inputs
2. **Second Flow**: Runs in parallel with first flow
3. **Third Flow**: Depends on both previous flows, executes after they complete
### Outputs:
- Combined outputs from all flows are returned in order
```
***
## Step 2: Testing
**Test your compound flow** to ensure all stages work correctly:
```python Python
from mira_sdk import MiraClient, CompoundFlow
from mira_sdk.exceptions import FlowError
client = MiraClient(config={"API_KEY": "YOUR_API_KEY"}) # Initialize Mira Client
flow = CompoundFlow(source="/path/to/compound_flow.yaml") # Load flow configuration
test_input = { # Prepare test inputs
"prime_input_1": "test data",
"prime_input_2": "test parameters"
}
try:
response = client.flow.test(flow, test_input) # Test entire pipeline
print("Test response:", response)
except FlowError as e:
print("Test failed:", str(e)) # Handle test failure
```
***
## Step 3: Deployment
**Deploy your compound flow** to make it available:
```python Python
from mira_sdk import MiraClient, CompoundFlow
from mira_sdk.exceptions import FlowError
flow = CompoundFlow(source="/path/to/compound_flow.yaml") # Load flow configuration
try:
client.flow.deploy(flow) # Deploy to platform
print("Compound flow deployed successfully!") # Success message
except FlowError as e:
print(f"Deployment error: {str(e)}") # Handle deployment error
```
***
## Step 4: Execution
After deployment, **execute your compound flow**:
```python Python
from mira_sdk import MiraClient
from mira_sdk.exceptions import FlowError
flow_name = "your-username/your-flow-name" # Flow identifier
input_data = { # Execution inputs
"prime_input_1": "production data",
"prime_input_2": "production parameters"
}
try:
result = client.flow.execute(flow_name, input_data) # Execute workflow
print("Execution result:", result) # Display result
except FlowError as e:
print("Execution error:", str(e)) # Handle execution error
```
***
## Step 5: Updates
When you need to **modify your compound flow**:
```python Python
from mira_sdk import MiraClient
from mira_sdk.exceptions import FlowError
flow = client.flow.get("your-username/your-flow-name") # Retrieve existing flow
flow.save("/path/to/compound_flow.yaml") # Save for editing
try:
client.flow.deploy(flow) # Deploy updated version
print("Updated flow deployed successfully!") # Success message
except FlowError as e:
print(f"Update error: {str(e)}") # Handle update error
# In case you forget to bump the flow version, it will get bumped by default every time you deploy the same flow.
```
By following these steps, you can **create, test, deploy, and manage** your own **custom compound flows** on the **Mira Flows** platform. 🌟🔧
# Build Elemental Flows
Learn how to build your own elemental flow using Mira Flows SDK
## Video Tutorial
Check out this Github Repository for a quick overview on how to build an Elemental Flow.
This guide explains how to **create, test, and deploy elemental flows** that implement focused, single-task processing. **Elemental flows** provide core functionality that can be used independently or as building blocks within compound flows. 🔄💡
## Development Lifecycle
Creating an **elemental flow** follows a systematic process:
Let's explore each step in detail.
***
## Step 1: YAML Configuration
```yaml .yaml
# Version format ex. "0.0.1"
version: "your.version.here" # Flow specification version
# Basic metadata for the agent
metadata:
name: "your-flow-name" # Unique identifier
description: "A brief description of your flow" # Flow purpose
author: "your-username" # Must match your account username
tags: [tag1, tag2, tag3, ...] # Keywords for categorization
private: false # Access control setting
# Define the input variables required
inputs:
input1: # First input parameter
type: string # Currently only String format
description: "Description of input1"
required: true
example: "Example value for input1"
input2: # Second input parameter
type: string
description: "Description of input2"
required: true
example: "Example value for input2"
# LLM configuration
model:
provider: "provider-name" # e.g., anthropic, openai, meta, etc.
name: "model-name" # Specific model identifier
# Dataset configuration (Optional)
dataset:
source: "author_name/dataset_name" # Make sure this dataset exists
# Prompt template configuration
prompt: |
Your flow's primary instruction or role...
You can use {input1} and {input2} placeholders to reference inputs.
# ReadME configuration
readme: |
Your flow's readme...
You can use raw text or markdown here.
```
***
## Step 2: Testing
**Test your elemental flow** before deployment:
```python Python
from mira_sdk import MiraClient, Flow
client = MiraClient(config={"API_KEY": "YOUR_API_KEY"}) # Initialize Mira Client
# Basic test
flow = Flow(source="/path/to/your.yaml") # Load flow configuration
input_dict = {"key": "value"} # Prepare test input
response = client.flow.test(flow, input_dict) # Test flow
```
***
## Step 3: Deployment
**Deploy your elemental flow** to make it available:
```python Python
from mira_sdk import MiraClient, Flow
from mira_sdk.exceptions import FlowError
client = MiraClient(config={"API_KEY": "YOUR_API_KEY"}) # Initialize client
flow = Flow(source="/path/to/your.yaml") # Load flow
try:
client.flow.deploy(flow) # Deploy to platform
except FlowError as e:
print(f"Error occurred: {str(e)}") # Handle deployment error
```
***
## Step 4: Execution
After deployment, **execute your elemental flow**:
```python Python
from mira_sdk import MiraClient, Flow
client = MiraClient(config={"API_KEY": "YOUR_API_KEY"}) # Initialize client
version = "1.0.0" # Optional specific version
input_data = {"key": "value"} # Execution input
# If no version is provided, it'll use the latest version by default
if version:
flow_name = f"author/your-flow-name/{version}"
else:
flow_name = "author/your-flow-name"
result = client.flow.execute(flow_name, input_data) # Execute flow
print(result)
```
***
## Step 5: Updates
When you need to **modify your elemental flow**:
```python Python
from mira_sdk import Flow, MiraClient
from mira_sdk.exceptions import FlowError
client = MiraClient(config={"API_KEY": "YOUR_API_KEY"}) # Initialize client
# Load existing flow
flow = client.flow.get("author/flow_name") # Get current version
flow.save("/path/to/flow.yaml") # Save for editing
# Deploy updated flow
try:
client.flow.deploy(flow) # Deploy new version
except FlowError as e:
print(f"Error occurred: {str(e)}") # Handle update error
# In case you forget to bump the flow version, it will get bumped by default every time you deploy the same flow.
```
By following these steps, you can **create, test, deploy, and manage** your own **custom elemental flows** on the **Mira Flows** platform. This process allows you to **contribute to the Marketplace** and **continuously improve** your flows over time. 🌟🔧
### Example
Complete example showcasing how to build and customize your own
elemental flows from scratch.
# Turn flows into Actionable Agents
Use the Composio tool integration to turn flows into Actionalble Agents
Composio allows you to connect your Mira Flows with various external services and platforms, enabling automated actions based on your flow outputs. This integration bridges the gap between AI-powered flows and real-world actions.
Composio tool requires Anthropic Claude-3.5-sonnet to function. Check out [Models](/documentation/get-started/models) for more information.
## Step-by-Step Integration Guide
### 1. Set Up Platform Integration
First, let's set up your desired platform integration in Composio:
1. Visit [Composio](https://composio.dev/)
2. Sign in to your account & Navigate to "All Tools"
3. Search for your desired integration (e.g., Twitter, Discord, Telegram)
4. Complete the integration process and authorise your account
### 2. Obtain Integration Details
After setting up the integration, you'll need 3 key pieces of information:
1. **API Key**:
* Go to your Composio dashboard
* Look for the API key section at top and copy your API key.
* You can use the default API key or create a new one
2. **Enum**:
* Go to the actions of the app you want to integrate with
* Copy the "Enum" of the action you wish to perform
3. **Entity ID**:
* This is generated after you complete the platform integration
* Find it in your "connected accounts" section under tools
### 3. Step by Step Demo
Here's an interactive demo showing the process:
## Code Implementation
### ComposioConfig Attributes
| Attribute | Description | Required |
| ------------------ | ----------------------------------------------------------------- | -------- |
| COMPOSIO\_API\_KEY | Your Composio authentication key | Yes |
| ACTION | Platform-specific action (e.g., "TWITTER\_POST", "DISCORD\_SEND") | Yes |
| TASK | Natural language description including `{content}` placeholder | Yes |
| ENTITY\_ID | Platform-specific entity identifier | Yes |
### Code Example
```python
from mira_sdk import MiraClient, Flow, ComposioConfig
# Initialize Mira client with your API key
client = MiraClient(config={"API_KEY": "YOUR_MIRA_API_KEY"})
# Get your exisitng flow
version = "1.0.0"
input_data = {"key": "value"}
# If no version is provided, latest version is used by default
if version:
flow = f"author/your-flow-name/{version}"
else:
flow = "author/your-flow-name"
# Set up your flow's input parameters
input_dict = {
"input": "value"
}
# Execute flow with Composio integration
# The flow's output will automatically replace {content} in the TASK
response = client.flow.execute(
flow,
input_dict,
ComposioConfig(
COMPOSIO_API_KEY="YOUR_COMPOSIO_API_KEY",
ACTION="ENUM", # This is the Enum e.g., "TWITTER_POST", "DISCORD_SEND"
TASK="Describe your task in natural language - {content}", # {content} is required and gets replaced with flow output
ENTITY_ID="YOUR_ENTITY_ID" # Platform-specific identifier
)
)
```
### What Not to Do
1. Don't forget `{content}` in TASK:
```python
# ❌ Incorrect - missing {content}
TASK="Post this message"
# ✅ Correct
TASK="Post this message: {content}"
```
1. Don't modify the `{content}` placeholder:
```python
# ❌ Incorrect
TASK="Send {message}"
TASK="Post {text}"
# ✅ Correct
TASK="Send {content}"
```
1. Don't use multiple `{content}` placeholders:
```python
# ❌ Incorrect
TASK="Post {content} and then {content}"
# ✅ Correct
TASK="Post {content}"
```
# Implement RAG Capabilities
Learn how to enhance your flows with Retrieval-Augmented Generation (RAG) using Mira Flows SDK
## Video Tutorial
Check out this Github Repository for a quick overview on how to Implement RAG Capabilities.
### Understanding RAG Implementation
**Retrieval-Augmented Generation (RAG)** enhances your flows with specific domain knowledge. The implementation process involves three main stages:
1. 🗂️ **Create a Dataset**: Establish a knowledge base that contains specialized information your flow will reference during execution.
2. ➕ **Add Data Sources**: Populate your dataset with relevant information from various supported sources.
3. 🔗 **Link Dataset to Flow**: Connect the dataset to your flow, enabling it to leverage this information during processing.
### Creating Your Dataset
Begin by establishing your knowledge base:
```python Python
from mira_sdk import MiraClient
client = MiraClient(config={"API_KEY": "YOUR_API_KEY"}) # Initialize client
# Create a new dataset
client.dataset.create(
"author/dataset_name", # Unique identifier
"Description of your knowledge base" # Dataset purpose
)
```
### Adding Data Sources
Populate your dataset with information from various supported formats:
```python Python
# Add a PDF document as data source
client.dataset.add_source("author/dataset_name", file_path="document.pdf")
# Add and URL as data source
client.dataset.add_source("author/dataset_name", url="https://example.com/data")
# Add multiple URL sources via a CSV file
client.dataset.add_source("author/dataset_name", file_path="sources.csv")
```
### Linking Dataset to Flow
Connect your dataset to an existing flow by modifying its configuration:
```yaml .yaml
# Additional flow configuration with RAG
dataset:
source: "author/dataset_name" # Link to your dataset
# Rest of your flow configuration remains unchanged
```
### Example
Complete example showcasing how to set up and configure datasets for
Retrieval Augmented Generation (RAG) capabilities.
# Save and Customize Marketplace Flows
Learn how to save flows from the marketplace and customize them according to your specific requirements
This guide explains how to **save flows from the marketplace** and **customize them** according to your specific requirements. 🛠️✨
***
## Saving a Flow
When you find a useful flow in the **Marketplace**, you can **save it locally** for customization:
```python Python
from mira_sdk import MiraClient
# Initialize client
client = MiraClient(config={"API_KEY": "YOUR_API_KEY"})
# Get the flow you want to customize
flow = client.flow.get("author/flow_name")
# Save to local YAML file
flow.save("/path/to/flow.yaml")
```
***
## Customizing Your Flow
After saving the flow locally, you can **modify the YAML file** according to your needs. Here are the **key areas** you can customize:
### Modifying Metadata
Update the flow's basic information to reflect your ownership and purpose:
```yaml .yaml
metadata:
name: "your-customized-flow-name" # Rename flow
description: "Your modified description" # Flow description
author: "your-username" # Your Mira Flows username
tags: [your, custom, tags] # Discovery keywords
private: true # Access control setting (true/false)
```
### Adjusting Inputs
Modify input parameters to match your requirements:
```yaml .yaml
inputs:
custom_input:
type: string # Input type
description: "Your custom input description" # Input description
required: true # Required field
example: "Your example value" # Example value
```
### Updating the Prompt
Customize the prompt to achieve your desired output:
```yaml .yaml
prompt: |
Your customized instructions...
You can use {custom_input} as a placeholder
```
### Modifying Model Settings
Change the model configuration if needed:
```yaml .yaml
model:
provider: "provider-name" # AI service provider
name: "your-preferred-model" # Specific model identifier
```
***
## Testing Your Customized Flow
Before deployment, **test your modifications** to ensure everything works correctly:
```python Python
from mira_sdk import Flow
# Load your modified flow
modified_flow = Flow(source="/path/to/flow.yaml")
# Test with sample inputs
test_input = {"custom_input": "test value"}
response = client.flow.test(modified_flow, test_input)
```
***
## Deploying Your Custom Flow
Once you're satisfied with the modifications:
```python Python
# Deploy as your own flow
client.flow.deploy(modified_flow)
```
For more detailed information about **customization options** and **best practices**, please refer to our complete **documentation** 📖🔗.
# Use Marketplace Flows
Learn how to discover, integrate, and customize pre-built flows from the Mira Flows Marketplace
## Video Tutorial
Check out this Github Repository for a quick overview on how to use Marketplace Flows.
**Mira Flows** offers a **Marketplace** where you can explore and use a variety of pre-built flows. There are two primary ways to utilize these flows:
1. 🛠️ **Using the Mira Flows SDK**
2. 🌐 **Direct API calls (without the SDK)**
***
## Exploring the Marketplace
To discover available flows:
1. 🚀 **Navigate to the** [**Marketplace**](https://console.mira.network/)
2. 🔎 **Browse or search for flows that fit your needs**
***
## Using Flows via the SDK
```python Python
from mira_sdk import MiraClient, Flow
# Initialize the client
client = MiraClient(config={"API_KEY": "YOUR_API_KEY"})
version = "1.0.0"
input_data = {"key": "value"}
# If no version is provided, latest version is used by default
if version:
flow_name = f"author/your-flow-name/{version}"
else:
flow_name = "author/your-flow-name"
result = client.flow.execute(flow_name, input_data)
print(result)
```
***
## Flow Management via SDK
```python Python
from mira_sdk import MiraClient, Flow
# Get a flow
flow = client.flow.get("author/flow_name")
# Get flows by author
flows = client.flow.get_by_author("author")
# Get flows by tag
flows = client.flow.get_by_tag("tag")
# Search for flow
flows = client.flow.search("abcd")
```
***
## Direct API Calls (Without SDK)
For those who prefer not to use the SDK or are working in other programming languages, you can interact with flows directly via API calls:
1. 🔍 **Find the flow you want to use in the marketplace and view its API documentation.**
2. 📡 **Use the flow's API endpoint in your HTTP requests**
```terminal Terminal
curl --request POST \
--url https://console-bff.stg.arohalabs.dev/v1/flows/flows/{author}/{flow_name} \
--header 'MiraAuthorization: YOUR_API_KEY' \
--data '{
"input_param": "value"
}'
```
Replace `YOUR_API_KEY`, `author`, and `flow_name` with your actual API key, author name, and flow name, and adjust the endpoint and payload structure according to the specific flow's requirements.
**Response**:
```json .json
{
"result": "LLM output"
}
```
### Example
Complete example showcasing how to integrate and use Marketplace flows
in your applications.
# null
***
title: "Checking Credits"
description: "Monitor your credit balance and usage"
icon: "wallet"
iconType: "light"
-----------------
## Credit Information
Monitor your current credit balance and usage using the `get_user_credits()` method.
### Example
```python
from mira_network import MiraClient
async def check_credits():
async with MiraClient(api_key="your-api-key") as client:
credits = await client.get_user_credits()
print("Credits:", credits)
```
### Response Structure
```python
{
"amount": 150.75 # Current balance in USD
}
```
### Usage Notes
* Monitor credits regularly to ensure uninterrupted service
* View detailed credit analytics in [Mira Console Credit History](https://console.mira.network/credit-history)
* Credits are consumed based on model usage and request volume
# Credit History
Track your credit usage over time
## Credit History
Track your credit usage and transactions over time using the `get_credits_history()` method.
### Example
```python
from mira_network import MiraClient
async def view_credit_history():
async with MiraClient(api_key="your-api-key") as client:
history = await client.get_credits_history()
for transaction in history:
print(f"Transaction: {transaction}")
```
### Response Structure
```python
[
{
"amount": 10.50, # Amount in USD
"description": "Used 1000 tokens with gpt-4o model"
},
{
"amount": 50.00, # Amount in USD
"description": "Credit recharge"
}
// ... more transactions
]
```
### Visual Analytics
For detailed credit usage analytics and visualizations:
1. Visit [Mira Console Credit History](https://console.mira.network/credit-history)
2. View usage patterns, trends, and detailed breakdowns
# Installation
Install and configure Mira Network SDK for your project
## Prerequisites
Before installing the SDK, ensure you have:
* Python 3.8 or higher installed
* pip package manager
* A Mira Network API key (get one at [console.mira.network](https://console.mira.network))
## Installation Steps
### Step 1: Install via pip
Install the SDK using pip:
```bash
pip install mira-network
```
### Step 2: Verify Installation
Verify the installation:
```bash
pip show mira-network
```
### Step 3: Environment Configuration
Configure your environment:
```python
import os
from mira_network import MiraClient
client = MiraClient(
api_key=os.getenv("MIRA_API_KEY"),
base_url=os.getenv("MIRA_API_URL", "https://apis.mira.network")
)
```
### Step 4: Test Your Setup
Create a simple test script:
```python
from mira_network import MiraClient
async def test_setup():
async with MiraClient(api_key="your-api-key") as client:
models = await client.list_models()
print("Available models:", models)
if __name__ == "__main__":
import asyncio
asyncio.run(test_setup())
```
## Next Steps
Once installed, proceed to the [Quickstart](/documentation/get-started/quickstart) guide to make your first API call.
# Introduction
Introduction to Mira Network SDK
## What is Mira Network SDK?
Mira Network SDK is your unified interface to the world of AI language models, providing a seamless way to integrate multiple language models while offering advanced routing, load balancing, and flow management capabilities.
The SDK offers several key capabilities:
* 🔄 **Smart Model Routing**: Route requests across different models
* ⚖️ **Load Balancing**: Distribute workload across nodes
* 🌊 **Flow Management**: Handle request patterns efficiently
* 🔌 **Universal Integration**: Single API for multiple models
* 📊 **Usage Tracking**: Monitor your model usage
## Why Choose Mira Network SDK?
| Feature | Mira SDK | Traditional Approach |
| ---------------------- | -------------------------- | ----------------------- |
| 🔄 Multi-model Support | Single unified API | Separate APIs per model |
| ⚖️ Load Balancing | Built-in | Custom implementation |
| 🌊 Flow Control | Automatic handling | Manual implementation |
| 📊 Usage Tracking | Integrated | Custom tracking needed |
| 🛡️ Error Handling | Standardized across models | Model-specific handling |
## Key Features
* 🔌 Simple, intuitive API
* 🔄 Async-first design
* 🌊 Streaming support
* 🔐 Error handling
* 🛠️ Customizable nodes
* 📊 Usage tracking
## Perfect For
* 🤖 AI Applications
* 📝 Text Generation
* 🔍 Search Enhancement
* 🎮 Interactive Systems
## Getting Started
To begin using the Mira Network SDK, you'll need:
1. **Python Environment**: Python 3.8 or higher
2. **Mira API Key**: Sign up at [Mira Console](https://console.mira.network) to obtain your API key
3. **Installation**: Install via pip (see next section)
Ready to start? Head to the [Installation](/documentation/get-started/installation) guide.
# Quickstart
Get started with Mira Network SDK
## Quick Start Guide
Let's walk through basic usage patterns of the Mira Network SDK.
### Basic Chat Completion
Here's a simple example to get started:
```python
from mira_network import MiraClient
async def main():
async with MiraClient(api_key="your-api-key") as client:
response = await client.chat_completions_create(
model="gpt-4o", # You can choose any available model of your choice
messages=[
{"role": "user", "content": "What is the capital of France?"}
]
)
print(response["choices"][0]["message"]["content"])
if __name__ == "__main__":
import asyncio
asyncio.run(main())
```
### Streaming Responses
For real-time responses:
```python
async def stream_response():
async with MiraClient(api_key="your-api-key") as client:
stream = await client.chat_completions_create(
model="your-chosen-model",
messages=[{"role": "user", "content": "Write a story"}],
stream=True
)
async for chunk in stream:
print(chunk["choices"][0]["delta"]["content"], end="")
```
### Managing Conversations
Handle multi-turn conversations:
```python
messages = [
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "Hi! Can you help me?"},
]
async with MiraClient(api_key="your-api-key") as client:
response = await client.chat_completions_create(
model="your-chosen-model",
messages=messages
)
```
### Error Handling
Implement robust error handling:
```python
try:
response = await client.chat_completions_create(
model="your-chosen-model",
messages=[{"role": "user", "content": "Hello"}]
)
except ValueError as e:
print(f"Validation error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
```
## Next Steps
* Explore [Advanced Features](/documentation/advanced-features)
* Check out [API Reference](/documentation/api-reference)
* Learn about [Best Practices](/documentation/best-practices)
# Generate Text
Generate text using AI models via chat completions
## Text Generation
Use `chat_completions_create()` to generate text responses from AI models.
### Basic Usage
```python
from mira_network import MiraClient
async def generate_text():
async with MiraClient(api_key="your-api-key") as client:
response = await client.chat_completions_create(
model="your-chosen-model",
messages=[
{"role": "user", "content": "What is the capital of France?"}
]
)
print(response["choices"][0]["message"]["content"])
```
### Streaming Responses
For real-time text generation:
```python
async def stream_response():
async with MiraClient(api_key="your-api-key") as client:
stream = await client.chat_completions_create(
model="your-chosen-model",
messages=[{"role": "user", "content": "Write a story"}],
stream=True
)
async for chunk in stream:
print(chunk["choices"][0]["delta"]["content"], end="")
```
### Multi-turn Conversations
Handle complex dialogues:
```python
messages = [
{"role": "system", "content": "You are a helpful assistant"},
{"role": "user", "content": "Hi! Can you help me?"},
{"role": "assistant", "content": "Of course! What can I help you with?"},
{"role": "user", "content": "Tell me about Paris"}
]
async with MiraClient(api_key="your-api-key") as client:
response = await client.chat_completions_create(
model="your-chosen-model",
messages=messages
)
```
### Error Handling
Implement robust error handling:
```python
try:
response = await client.chat_completions_create(
model="your-chosen-model",
messages=[{"role": "user", "content": "Hello"}]
)
except ValueError as e:
print(f"Validation error: {e}")
except Exception as e:
print(f"An error occurred: {e}")
```
### Custom Node Configuration
For specialized deployments:
```python
response = await client.chat_completions_create(
model="your-model",
messages=[{"role": "user", "content": "Hello"}],
mira_node={
"base_url": "https://custom-node.com",
"api_key": "node-api-key"
}
)
```
## Message Structure
Core components of a message:
```python
Message:
role: str # "system", "user", or "assistant"
content: str # The message content
```
# List Models
Explore available AI models on Mira Network
## List Available Models
The `list_models()` method allows you to explore the diverse range of AI models available on Mira Network.
### Example
```python
from mira_network import MiraClient
async def explore_models():
async with MiraClient(api_key="your-api-key") as client:
# Get list of available models
models = await client.list_models()
print("Available models:", models)
# Get detailed information about models
for model in models:
print(f"\nModel: {model}")
# You can use this model ID in chat_completions_create()
```
### Response Structure
```python
[
"gpt-4o",
"deepseek-r1",
"claude-3.5-sonnet",
"llama-3.3-70b-instruct",
// ... other available models
]
```
### Usage Notes
* Check available models before making completion requests
* Different models may have different capabilities and pricing
* Model availability may vary based on your subscription tier
# Creating an API Token
Create new API tokens for authentication
## Create API Token
Generate new API tokens for authentication using the `create_api_token()` method.
### Example
```python
from mira_network import MiraClient
async def create_token():
async with MiraClient(api_key="your-api-key") as client:
# Create new API token
new_token = await client.create_api_token({
"description": "Production API Key"
})
print(f"New token created: {new_token}")
```
### Response Structure
```python
{
"token": "sk-mira-xxxx...", # API keys start with sk-mira-
"description": "Production API Key",
"created_at": "2024-01-01T00:00:00Z"
}
```
### Usage Notes
* Store tokens securely
* Use descriptive names for easy identification
* Keep track of token creation dates
* Monitor usage metrics in [Mira Console](https://console.mira.network/api-keys) with detailed analytics
* API keys always start with `sk-mira-`
```
```
# Delete API Token
Revoke and delete API tokens
## Delete API Token
Revoke access by deleting API tokens using the `delete_api_token()` method.
### Example
```python
from mira_network import MiraClient
async def delete_token():
async with MiraClient(api_key="your-api-key") as client:
# Delete specific token
await client.delete_api_token("token-id")
print("Token successfully deleted")
```
### Error Handling
```python
try:
await client.delete_api_token("token-id")
except Exception as e:
print(f"Error deleting token: {e}")
```
### Usage Notes
* Deletion is permanent and cannot be undone
* Verify token ID before deletion
* Plan for service disruption if deleting active tokens
```
```
# List API Tokens
Retrieve all active API tokens
## List API Tokens
View all active API tokens using the `list_api_tokens()` method.
### Example
```python
from mira_network import MiraClient
async def list_tokens():
async with MiraClient(api_key="your-api-key") as client:
# List all tokens
tokens = await client.list_api_tokens()
# Display token information
for token in tokens:
print(f"Token: {token['description']}")
```
### Response Structure
```python
[
{
"token": "mira_tk_xxxx...",
"description": "Production API Key",
"created_at": "2024-01-01T00:00:00Z"
},
// ... other tokens
]
```
### Usage Notes
* Regular audit of active tokens recommended
* Check creation dates for token rotation
* Review token descriptions for accuracy
* Monitor token usage metrics in [Mira Console](https://console.mira.network/api-keys)
* API keys follow the format `sk-mira-****`
### Usage Metrics
View detailed usage metrics for each token in the Mira Console:
* Request volume over time
* Model usage distribution
* Cost analysis charts
* Usage patterns visualization
Access these metrics by visiting the [API Keys Dashboard](https://console.mira.network/api-keys) in your Mira Console.