# Connect Your Apps URL: /finops/connect-your-apps Point client applications at the FinOps AI Gateway using a virtual key. *** title: "Connect Your Apps" description: "Point client applications at the FinOps AI Gateway using a virtual key." -------------------------------------------------------------------------------------- Applications connect to the FinOps AI Gateway the same way they would connect to OpenAI — by changing the **base URL** and using a **virtual key** issued in Monetize360. ## Prerequisites 1. A [virtual key](/finops/user-keys) created and active in Finops Config 2. Your tenant's **gateway URL** (provided by your Monetize360 administrator) 3. Models and providers configured and allowed for the key's organization ## Authentication Send the virtual key JWT in the `Authorization` header: ``` Authorization: Bearer ``` Monetize360 generates and rotates these tokens when you create virtual keys. Applications should obtain the token from your secure configuration store — not hard-code provider API keys. Alternative headers supported by the gateway: | Header | Format | | ---------------- | ----------------------------------- | | `Authorization` | `Bearer ` (OpenAI style) | | `x-bf-vk` | Virtual key token | | `x-api-key` | Virtual key token (Anthropic style) | | `x-goog-api-key` | Virtual key token (Google style) | ## OpenAI-compatible example Replace `YOUR_GATEWAY_URL` and `YOUR_VIRTUAL_KEY_JWT` with values from your administrator: ```bash curl -X POST "https://YOUR_GATEWAY_URL/v1/chat/completions" \ -H "Content-Type: application/json" \ -H "Authorization: Bearer YOUR_VIRTUAL_KEY_JWT" \ -d '{ "model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Hello"}] }' ``` ## SDK configuration For OpenAI, Anthropic, or other SDKs, set: | Setting | Value | | ------------ | ----------------------------------------------------------------------- | | **Base URL** | Your tenant gateway URL (e.g. `https://gateway.your-tenant.example/v1`) | | **API Key** | Virtual key JWT | No SDK-specific FinOps package is required — the gateway speaks standard provider APIs. ## Framework-specific guides | Integration | Guide | | ------------------- | ------------------------------------------------------------ | | LangChain | [LangChain SDK](/finops/integrations/langchain-sdk) | | OpenAI SDK | [OpenAI SDK](/finops/integrations/openai-sdk/overview) | | Anthropic SDK | [Anthropic SDK](/finops/integrations/anthropic-sdk/overview) | | Google GenAI | [GenAI SDK](/finops/integrations/genai-sdk/overview) | | LiteLLM | [LiteLLM SDK](/finops/integrations/litellm-sdk) | | Cursor & other IDEs | [CLI & IDE Agents](/finops/cli-agents/overview) | See [What is an integration?](/finops/integrations/what-is-an-integration) for the full list of protocol adapters and endpoint paths. ## Test before production Use the [Simulator](/finops/simulator) to verify budgets, routing, and model allowlists with the same virtual key before pointing production traffic at the gateway. ## API reference For full endpoint documentation, open the **API** tab in the navigation bar. --- # Dashboard URL: /finops/dashboard Monitor AI spend, value delivery, routing savings, and token consumption from the FinOps dashboard. *** title: "Dashboard" description: "Monitor AI spend, value delivery, routing savings, and token consumption from the FinOps dashboard." ------------------------------------------------------------------------------------------------------------------ The **Dashboard** under Finops Config gives executives and FinOps admins a single view of AI economics across your organization.
FinOps dashboard with KPI cards and trend charts
## KPI cards | Metric | Description | | --------------------- | --------------------------------------------------------------------------------- | | **AI Spend** | Total cost of AI inference across all providers and models in the selected period | | **Value Delivered** | Business value attributed to AI usage (from value-driver metrics) | | **Saved via Routing** | Cost avoided by routing requests to cheaper or preferred models | | **Tokens Consumed** | Aggregate input and output tokens processed through the gateway | Each card includes a sparkline for quick trend context. ## Charts ### Budget Utilization Trend Tracks **Total Budget**, **Utilized Budget**, and **Allocated Budget** over time. Use this to spot departments or entities approaching their caps before hard blocks occur. ### Expense and Saving Trend Compares **Cost** against **Total Savings** from intelligent routing and model selection. ### Spend by Model Bar chart of spend broken down by model. Identify which models drive the majority of cost. ### Value Delivery Trend Line chart of value delivered over time. Use the department tabs — **Overall**, Engineering, Finance, Sales, Marketing, Legal, Support — to drill into team-level contribution. ## Filters Use the **Period** filter at the top of the page, then click **Apply Filters** to refresh all widgets for the selected date range. ## Related pages * [Telemetry Data](/finops/telemetry) — row-level token consumption * [Value Driver Metrics](/finops/value-driver-metrics) — configure how value is measured * [Organization → Budget](/finops/organization/budget) — set the budget limits reflected in utilization charts --- # Getting Started URL: /finops/getting-started Access FinOps Config in Monetize360 and configure your AI gateway in the recommended order. *** title: "Getting Started" description: "Access FinOps Config in Monetize360 and configure your AI gateway in the recommended order." ---------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' FinOps AI Gateway is managed entirely through **Monetize360**. Sign in to your tenant, open **Monetize AI → Finops Config**, and use the sidebar to configure organizations, providers, governance, and monitoring. ## Recommended setup order 1. Organization hierarchy 2. Model providers and pricing 3. Org budgets and model allowlists 4. User keys 5. Routing rules 6. Simulator 7. Connect applications | Step | Page | Why | | ---- | ------------------------------------------------------------- | ------------------------------------------------------------------------------- | | 1 | [Organization](/finops/organization) | Define regions, legal entities, and departments before scoping budgets and keys | | 2 | [Model Provider](/finops/model-provider) | Register providers, API keys, and per-model pricing | | 3 | [Organization → Budget & Models](/finops/organization/budget) | Set spend caps and allowed models per org | | 4 | [User Keys](/finops/user-keys) | Issue virtual keys for applications and teams | | 5 | [Routing Rules](/finops/routing-rules) | Direct traffic to preferred models or fallbacks | | 6 | [Simulator](/finops/simulator) | Test prompts and verify governance before production | | 7 | [Connect Your Apps](/finops/connect-your-apps) | Point client applications at the gateway with a virtual key | ## Access FinOps Config 1. Log in to **Monetize360** with your tenant credentials. 2. In the left sidebar, expand **Monetize AI**. 3. Open **Finops Config** — the module includes Dashboard, Organization, Model Provider, User Keys, Routing Rules, Rate Limit, Simulator, Telemetry Data, and Value Driver Metrics. Your tenant administrator provisions FinOps access. If you do not see **Finops Config**, contact your Monetize360 admin. ## What happens behind the scenes When you save configuration in FinOps Config, Monetize360 stores governance data in your tenant database. The FinOps AI Gateway reads that configuration at request time — you never edit gateway files or deploy infrastructure yourself. **Flow:** Admin → UI UI → Gateway App → Gateway --- # FinOps AI Gateway URL: /finops Monetize360 SaaS for governing, routing, and monitoring enterprise AI consumption. *** title: "FinOps AI Gateway" description: "Monetize360 SaaS for governing, routing, and monitoring enterprise AI consumption." ------------------------------------------------------------------------------------------------- FinOps AI Gateway is the **Monetize360** module for enterprise AI governance. Configure providers, budgets, routing, and virtual keys through the Finops Config UI — then let applications call a single OpenAI-compatible API with full cost control and audit visibility.
FinOps dashboard overview
## Deployment architecture Client agents (LangChain, Spring AI, and other SDKs) send requests with budget keys (`user_key`, `dept_key`, `agent_key`, `model_key`). The **FinOps AI Gateway** enforces cache, budget, and routing decisions in under 10 ms p99, then forwards approved traffic to the route gateway and GPU clusters. Telemetry streams asynchronously through Kafka into the billing pipeline, which syncs balances back to the gateway budget store.
FinOps AI Gateway deployment architecture — client agents, gateway budget engine, route gateway, GPU clusters, and async billing pipeline
## What you get * **[Unified API](/finops/connect-your-apps)** — One gateway URL for 20+ AI providers. Point existing SDKs at your tenant endpoint. * **[Organization governance](/finops/organization)** — Hierarchical budgets, model allowlists, and rate limits by region, entity, and department. * **[Virtual keys](/finops/user-keys)** — Issue keys per application or team with scoped access and spend caps. * **[Intelligent routing](/finops/routing-rules)** — CEL-based rules with fallbacks to optimize cost and reliability. * **[FinOps dashboard](/finops/dashboard)** — AI spend, value delivered, routing savings, and token trends in one view. * **[Simulator](/finops/simulator)** — Test prompts and watch governance react in real time before going live. ## Get started * **[Getting started](/finops/getting-started)** — Recommended setup order and how to open Finops Config in Monetize360. * **[Connect your apps](/finops/connect-your-apps)** — Gateway URL, virtual key authentication, and a minimal API example. *** ## Finops Config modules | Module | Purpose | | ---------------------------------------------------- | --------------------------------------- | | [Dashboard](/finops/dashboard) | Executive KPIs and trend charts | | [Organization](/finops/organization) | Hierarchy, budgets, models, rate limits | | [Model Provider](/finops/model-provider) | Providers, keys, model pricing | | [User Keys](/finops/user-keys) | Virtual keys for applications | | [Routing Rules](/finops/routing-rules) | Model and provider routing | | [Rate Limit](/finops/rate-limit) | Token and request throttling | | [Simulator](/finops/simulator) | Interactive governance testing | | [Telemetry Data](/finops/telemetry) | Row-level consumption and cost | | [Value Driver Metrics](/finops/value-driver-metrics) | Business value attribution | *** ## How it works You configure policy in Monetize360. Applications send requests to the managed gateway. Spend, routing, and blocks are enforced automatically — no infrastructure files or code deployments on your side. --- # Rate Limit URL: /finops/rate-limit Configure tenant-wide token and request rate limits in FinOps Config. *** title: "Rate Limit" description: "Configure tenant-wide token and request rate limits in FinOps Config." ------------------------------------------------------------------------------------ Rate limits at the Finops Config top level apply globally or can complement organization- and key-level limits configured elsewhere. ## Access Open **Finops Config → Rate Limit**. ## Create a rate limit 1. Click **+ Create**. 2. Configure token limits: * **Token Max Limit** — maximum tokens per window * **Token Reset Duration** — window length (e.g. `1h`, `1d`) 3. Configure request limits: * **Request Max Limit** — maximum requests per window * **Request Reset Duration** — window length 4. Optionally scope to a **Virtual Key**, **Provider**, or **Governed Organization**. 5. Click **Submit**. ## Monitoring limits The [Simulator](/finops/simulator) shows real-time usage bars under **Limits** on each governance hierarchy card. When exceeded, responses display rate-limit errors before reaching the upstream provider. ## Related * [Organization Rate Limits](/finops/organization/rate-limits) — per-department throttling * [User Keys](/finops/user-keys) — key-scoped limits --- # Routing Rules URL: /finops/routing-rules Direct AI requests to specific models and providers using CEL-based routing rules. *** title: "Routing Rules" description: "Direct AI requests to specific models and providers using CEL-based routing rules." ------------------------------------------------------------------------------------------------- Routing rules let you redirect requests based on conditions — model requested, metadata, query parameters, budget state, and more. Rules can target a different provider/model and define fallback chains. ## Access Open **Finops Config → Routing Rules**. ## How routing works
Routing rules evaluation flow
When a request arrives, the gateway evaluates rules in priority order. The first matching rule can change the target provider and model. If the primary target fails, configured fallbacks are tried. ## Create a routing rule 1. Click **+ Create**. 2. Set **Name** and optional **Description**. 3. Enable **Enabled** to activate the rule. 4. Write a **CEL Expression** — the condition that must be true for this rule to match (e.g. always `true` for a catch-all demo rule). 5. Choose **Provider** and **Model** targets — leave blank to keep the incoming request's provider/model. 6. Set **Fallbacks** — comma-separated fallback model identifiers if the primary target is unavailable. 7. Scope the rule: * **Organization** — applies to all keys under that org subtree * **Scope Organization** — runtime routing scope (mutually exclusive with virtual key scope in most cases) * **Virtual Key Id** — applies only to one key 8. Set **Priority** — lower numbers evaluate first. 9. Click **Submit**. ## Verify routing Open the [Simulator](/finops/simulator), send a prompt, and look for the **Routed** banner when the used model differs from what you selected. Hover the rule name to see the CEL expression, target, and fallbacks. ## Related * [Simulator](/finops/simulator) — live routing verification * [Dashboard](/finops/dashboard) — **Saved via Routing** KPI reflects routing savings --- # Security URL: /finops/security How FinOps AI Gateway protects credentials, enforces access control, and isolates tenant data. *** title: "Security" description: "How FinOps AI Gateway protects credentials, enforces access control, and isolates tenant data." ------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' FinOps AI Gateway runs as a managed **Monetize360** service. Security is built into the platform — tenant isolation, encrypted credentials, and token-based access for applications. ## Tenant isolation Each Monetize360 tenant has its own database. FinOps configuration, virtual keys, budgets, routing rules, and inference logs are stored only in your tenant — never shared across customers. ## Application authentication Applications never receive upstream provider API keys. Instead: 1. An administrator creates a [virtual key](/finops/user-keys) in Finops Config. 2. Monetize360 issues a signed **JWT** for that key. 3. Applications send the JWT in the `Authorization: Bearer` header (or supported alternative headers). 4. The gateway validates the token, resolves the tenant, and enforces governance before calling any provider. See [Connect Your Apps](/finops/connect-your-apps) for integration details. ## Provider credentials Provider API keys are stored encrypted in your tenant and used only by the gateway service. Rotate keys in **Model Provider → Keys** without redeploying applications. ## Governance enforcement Every request is checked against active policy before reaching an upstream model: * [Budget](/finops/organization/budget) limits * [Rate limits](/finops/rate-limit) * [Model allowlists](/finops/organization/models) * [Routing rules](/finops/routing-rules) Blocked requests return clear errors — test enforcement safely in the [Simulator](/finops/simulator). ## Audit and telemetry Inference activity is logged to your tenant for [Telemetry Data](/finops/telemetry) and dashboard reporting. Use export and history features for compliance review. ## Access control Access to Finops Config itself is controlled by Monetize360 role-based permissions. Only authorized administrators can create virtual keys, view provider credentials, or change routing policy. Contact your Monetize360 administrator for SSO, role assignments, and data residency questions specific to your deployment. --- # Simulator URL: /finops/simulator Test prompts against virtual keys and inspect live budget, rate limit, and routing behavior. *** title: "Simulator" description: "Test prompts against virtual keys and inspect live budget, rate limit, and routing behavior." ----------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' The **Simulator** lets you send real inference requests through the FinOps AI Gateway and see governance take effect immediately — without writing code or deploying a client application.
FinOps Simulator with conversation panel and governance hierarchy
## When to use it * Validate [budgets](/finops/organization/budget) before production traffic hits a cap * Confirm [routing rules](/finops/routing-rules) redirect to the expected model * Reproduce rate-limit and model-block errors safely * Demo FinOps behavior to stakeholders ## Layout The page has two panels: | Panel | Purpose | | -------------------------------- | ------------------------------------------------------------------ | | **Conversation** (left) | Chat-style prompt/response testing | | **Governance hierarchy** (right) | Live budget, limit, and routing state for the selected virtual key | ## Step-by-step 1. Open **Finops Config → Simulator**. 2. On the right, select a **Virtual key** from the dropdown (active keys from [User Keys](/finops/user-keys)). 3. Review the **Governance hierarchy** cards — each shows **Budget**, **Limits**, and **Routing** for that scope. 4. Choose a **model** (`provider / model`) in the compose bar. 5. Type a prompt or pick a **Suggested prompt** preset, then send (Enter) or click the send button. 6. Inspect the response: * **Routed** banner — requested model differed from the model actually used; hover for rule name and CEL expression * **Error alerts** — budget exceeded, rate limited, or model/provider blocked * **Details** (chart icon) — tokens, cost, latency, and routing metadata 7. Use **Load history** to pull prior turns from gateway logs for this key. 8. Use **Refresh** to reload models and governance without clearing the chat. 9. Use **Clear** to reset the on-screen conversation only. ## Conversation controls | Control | Action | | --------------------- | ------------------------------------------------------------------------------ | | **Load history** | Fetches paginated inference logs for the selected virtual key | | **Refresh** | Reloads governance hierarchy and available models | | **Clear** | Clears the in-session chat display | | **Suggested prompts** | Nine FinOps-themed presets (cost drivers, budget alerts, routing policy, etc.) | | **Query params** | Key=value pairs sent with the request so routing rules can match on metadata | ## Governance hierarchy Cards appear in evaluation order from most specific to global: **Hierarchy:** Virtual key scope → Model scope → Organization chain → Global scope Each card shows: * **Budget** — `$used / $max · N% used` with color coding (green under 70%, amber 70–89%, red 90%+) * **Limits** — request and/or token rate-limit usage, or "None" * **Routing** — rule names; click to see status, CEL expression, target provider/model, and fallbacks The breadcrumb above the cards (e.g. `Engineering (UK) → UK Entity → EMEA → tokensystem`) reflects the virtual key's **Governance Scope Organization** walking up the [organization tree](/finops/organization). Budget and limit counters **refresh automatically** every second while a virtual key is selected. ## Auto-fire Toggle **Auto-fire** on the right panel to send a random suggested prompt every second. Useful for stress-testing rate limits and watching budget bars move under sustained load. Auto-fire sends real gateway requests and consumes budget. Use only in non-production tenants or with test keys. ## Error types you may see | Alert | Meaning | | ---------------------------------------------- | ------------------------------------------------------------------------ | | Budget Exceeded | A budget at virtual key, org, model, or global scope blocked the request | | Rate Limited / Token Limited / Request Limited | A rate limit window was exhausted | | Provider Blocked / Model Blocked | The model or provider is not allowed for this virtual key | | Virtual Key Blocked | The key is inactive or otherwise denied | ## Related * [User Keys](/finops/user-keys) * [Routing Rules](/finops/routing-rules) * [Telemetry Data](/finops/telemetry) --- # Telemetry Data URL: /finops/telemetry Review actual token consumption, cost, and usage by agent, department, and model. *** title: "Telemetry Data" description: "Review actual token consumption, cost, and usage by agent, department, and model." ------------------------------------------------------------------------------------------------ **Telemetry Data** provides row-level visibility into AI consumption across your tenant. Use it for chargeback, anomaly detection, and reconciling dashboard KPIs. ## Actual Token Consumption Open **Finops Config → Telemetry Data** (or the **Actual Token Consumption** view).
Actual Token Consumption table with agent, cost, department, and model columns
## Table columns | Column | Description | | -------------------- | ---------------------------------------------------------- | | **Agent** | Application or agent identifier that initiated the request | | **Cost** | Calculated spend for the row | | **Consumption Date** | Date of usage | | **Department** | Department attributed to the consumption | | **Currency** | Currency for the cost field | | **Provider** | Upstream provider used (after routing) | | **Vendor** | In-house vs. external classification | | **Model** | Model used for the request | | **Input Tokens** | Prompt tokens consumed | Use **Enter Department** and **Enter Agent** filters to narrow results. ## Toolbar actions | Action | Purpose | | ----------- | ------------------------------------------- | | **Refresh** | Reload the latest data | | **History** | View audit history for records | | **Export** | Download data for spreadsheets or BI tools | | **Columns** | Show or hide columns | | **Filter** | Advanced filtering | | **+ Sync** | Sync consumption data from the gateway logs | ## Related * [Dashboard](/finops/dashboard) — aggregated KPIs and trends * [Value Driver Metrics](/finops/value-driver-metrics) — business value attribution * [Simulator](/finops/simulator) — generate test traffic and verify logging --- # User Keys URL: /finops/user-keys Issue virtual keys that applications use to access the FinOps AI Gateway with governance attached. *** title: "User Keys" description: "Issue virtual keys that applications use to access the FinOps AI Gateway with governance attached." ----------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' **User Keys** (virtual keys) are how applications authenticate to the FinOps AI Gateway. Each key carries an organization scope, optional budgets, rate limits, and model restrictions. ## Access Open **Finops Config → User Keys**. ## Create a virtual key 1. Click **+ Create**. 2. Set **Name** — a recognizable label (e.g. `Dev user 2`, `Production chatbot`). 3. Set **Description** (optional). 4. Choose **Organization** — the tenant visibility org for this key. 5. Set **Governance Scope Organization** when budget, rate limit, and routing should follow a different org than the visibility org. 6. Toggle **Is Active** on to allow traffic. 7. Optionally enable **Calendar Aligned** for budgets that reset on calendar boundaries (day/week/month/year in UTC). 8. Click **Submit**. ## What a virtual key controls | Capability | Configured via | | --------------------------- | ---------------------------------------------------------------------------- | | Model allowlist / blocklist | [Organization Models](/finops/organization/models) or key-scoped model rules | | Spend cap | [Organization Budget](/finops/organization/budget) or key-level budget | | Request/token throttling | [Rate Limit](/finops/rate-limit) or org-level limits | | Routing behavior | [Routing Rules](/finops/routing-rules) scoped to the key or its org | ## Model rules for a virtual key When creating a model rule, select the virtual key in the **Virtual Key Id** field of **GovernanceVirtualKeyProviderConfig Save Flow**:
Virtual key scoped model configuration form
## Next steps * Test the key in the [Simulator](/finops/simulator) * Connect your application using [Connect Your Apps](/finops/connect-your-apps) Monetize360 issues a signed JWT for each virtual key. Applications send this token in the `Authorization` header — never embed provider API keys in client code. --- # Value Driver Metrics URL: /finops/value-driver-metrics Configure and track business value delivered by AI usage across departments. *** title: "Value Driver Metrics" description: "Configure and track business value delivered by AI usage across departments." ------------------------------------------------------------------------------------------- Value driver metrics connect AI consumption to business outcomes — enabling the **Value Delivered** KPI on the [Dashboard](/finops/dashboard) and department-level value trends. ## Access Open **Finops Config → Value driver Metrics**. ## Purpose While [Telemetry Data](/finops/telemetry) shows raw cost and tokens, value driver metrics answer: *what did this AI usage produce for the business?* Examples include tickets resolved, documents generated, revenue influenced, or hours saved — defined per your tenant's FinOps configuration. ## Dashboard integration The **Value Delivery Trend** chart on the dashboard uses these metrics. Switch between department tabs (**Overall**, Engineering, Finance, Sales, Marketing, Legal, Support) to compare teams. ## Workflow 1. Define value driver formulas or mappings in Value driver Metrics. 2. Ensure applications tag requests with department and agent metadata (via headers or query params where supported). 3. Review results on the [Dashboard](/finops/dashboard) and reconcile with [Telemetry Data](/finops/telemetry). ## Related * [Dashboard](/finops/dashboard) — Value Delivered and Value Delivery Trend * [Organization](/finops/organization) — department hierarchy for attribution --- # API Reference URL: /finops-api FinOps AI Gateway HTTP API for inference, integrations, and management. *** title: API Reference description: FinOps AI Gateway HTTP API for inference, integrations, and management. full: true ---------- Browse endpoints by category in the sidebar — **Models**, **Chat Completions**, **Rerank**, provider integrations, and management APIs. Content is generated from `ai-gateway/docs/openapi/openapi.json`. --- # Claude Code URL: /finops/cli-agents/claude-code Use Claude Code with FinOps to route through any provider and unlock advanced features like MCP tools and observability. *** title: "Claude Code" description: "Use Claude Code with FinOps to route through any provider and unlock advanced features like MCP tools and observability." --------------------------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' [Claude Code](https://www.claude.com/product/claude-code) brings AI-powered coding capabilities directly to your terminal. **Tested on Claude Code versions:** | Version | Released | | ------- | ---------- | | 2.1.143 | 2026-05-15 | | 2.1.132 | 2026-05-06 | | 2.1.131 | 2026-05-06 | | 2.1.129 | 2026-05-05 | | 2.1.128 | 2026-05-04 | If your Allowed Headers are already set to `*`, you can skip this note. If not and you face issues integrating FinOps with Claude Code, try switching to `*` or adding the specific headers required by your client. By default, FinOps whitelists: `Content-Type`, `Authorization`, `X-Requested-With`, `X-Stainless-Timeout`, and `X-Api-Key`. ## Installing Claude Code ```bash curl -fsSL https://claude.ai/install.sh | bash ``` For platform-specific instructions, visit [https://code.claude.com/docs/en/overview](https://code.claude.com/docs/en/overview). ## Authentication Methods There are two ways to authenticate Claude Code with FinOps: ### `ANTHROPIC_AUTH_TOKEN` (Recommended) Set `ANTHROPIC_AUTH_TOKEN` to your FinOps virtual key. Claude Code sends this token in the `Authorization: Bearer` header automatically. FinOps recognizes this header and uses the virtual key for routing and authentication. **Why this is recommended:** You do not need to log in to an Anthropic account. No Anthropic credentials are required, as FinOps handles everything through the virtual key. All code snippets below use this method. ### `ANTHROPIC_CUSTOM_HEADERS` (Alternative) Set `ANTHROPIC_CUSTOM_HEADERS` to `x-bf-vk: your-virtual-key`. This passes the virtual key as a custom header instead of the `Authorization` header. **Caveat:** Because the virtual key is sent as a custom header rather than as the bearer token, Claude Code falls back to standard Anthropic account authentication for the `Authorization` header. This means you still need to log in with an Anthropic account. No credits are needed on the Anthropic account since billing goes through your FinOps virtual key, but the account login is still required. ## Configuring Claude Code to work with FinOps **To avoid caching issues in Claude Code**, follow these steps: * Open your `settings.json` and remove the `model` field if it is present. This field overwrites the `env`-based model selection and can cause unexpected behavior. * Save the file. * Start Claude Code, run the `/logout` command, then restart Claude Code. * When prompted to choose an authentication method: * If you are using `ANTHROPIC_AUTH_TOKEN` (recommended), no Anthropic account login is required, so you can skip this step. * If you are using `ANTHROPIC_CUSTOM_HEADERS`, select **"Anthropic Console account · API usage billing"** when prompted.
Claude cli API selection
Claude Code supports multiple authentication methods. Choose the one that matches your account type. 1. **Update settings.json** Global `settings.json` is placed in your home folder. * macOS / Linux / WSL (User Global): `~/.claude/settings.json` * Windows (User Global): `%USERPROFILE%\.claude\settings.json` * Project-Specific: `.claude/settings.json` (located within your individual project's root directory) * Local Overrides: `.claude/settings.local.json` (also in the project root, used for personal preferences that aren't shared via Git) You will need to update the most granular `settings.json`. ### 1. Using alias 1. Add following routing rules in FinOps **`sonnet-model` route** * Keep it a global level and assign priority you want to assign * Add model condition as `model` `=` `sonnet-model`. This option is not available out of the box - so type this string and select `Create sonnet-model` * And add second header condition; to check if the `user-agent` starts with `claude-cli`. * And then you can map this model to any model you want. In the configuration given - we are using `vertex/claude-sonnet-4-6`.
sonnet-model routing example
**`haiku-model` route** * Repeat the above steps by replacing `sonnet-model` with `haiku-model`. 2. Update `settings.json` The JSON snippets below show only the `env` key. Merge them into your existing `settings.json` top-level object - do not paste them as a standalone file, or you will overwrite other settings like `permissions`, `model`, and `apiKeyHelper`. ```json "env": { "ANTHROPIC_BASE_URL": "{AI_GATEWAY_URL}/anthropic", "ANTHROPIC_AUTH_TOKEN": "your-virtual-key", "ANTHROPIC_DEFAULT_HAIKU_MODEL": "haiku-model", "ANTHROPIC_DEFAULT_SONNET_MODEL": "sonnet-model" } ``` ### 2. Using provider-specific model pinning #### Anthropic Update `settings.json` to pick Anthropic models. For Anthropic models, you don't need to prefix models with provider name. ```json "env": { "ANTHROPIC_BASE_URL": "{AI_GATEWAY_URL}/anthropic", "ANTHROPIC_AUTH_TOKEN": "your-virtual-key", "ANTHROPIC_DEFAULT_HAIKU_MODEL": "claude-haiku-4-6", "ANTHROPIC_DEFAULT_SONNET_MODEL": "claude-sonnet-4-6" } ``` #### Bedrock Update `settings.json` to pick Anthropic models on Bedrock. ```json "env": { "ANTHROPIC_BASE_URL": "{AI_GATEWAY_URL}/anthropic", "ANTHROPIC_AUTH_TOKEN": "your-virtual-key", "ANTHROPIC_DEFAULT_HAIKU_MODEL": "bedrock/global.anthropic.claude-haiku-4-6", "ANTHROPIC_DEFAULT_SONNET_MODEL": "bedrock/global.anthropic.claude-sonnet-4-6" } ``` If you don't pin using CLI - you can pin these in UI. Go to Dashboard > Models > Model Providers > AWS Bedrock > Key. And add deployments #### Vertex Update `settings.json` to pick Anthropic models on Vertex. ```json "env": { "ANTHROPIC_BASE_URL": "{AI_GATEWAY_URL}/anthropic", "ANTHROPIC_AUTH_TOKEN": "your-virtual-key", "ANTHROPIC_DEFAULT_HAIKU_MODEL": "vertex/claude-haiku-4-6", "ANTHROPIC_DEFAULT_SONNET_MODEL": "vertex/claude-sonnet-4-6" } ``` #### Azure Update `settings.json` to pick Anthropic models on Azure. ```json "env": { "ANTHROPIC_BASE_URL": "{AI_GATEWAY_URL}/anthropic", "ANTHROPIC_AUTH_TOKEN": "your-virtual-key", "ANTHROPIC_DEFAULT_HAIKU_MODEL": "azure/claude-haiku-4-6", "ANTHROPIC_DEFAULT_SONNET_MODEL": "azure/claude-sonnet-4-6" } ``` Azure-hosted models must support **tool use capabilities** for Claude Code to function properly. Verify tool calling support before configuring Azure models. ## Model Configuration Claude Code uses three model tiers: **Sonnet** (default), **Opus** (complex tasks), and **Haiku** (fast, lightweight). With FinOps, you can override these defaults to use any model from any provider. **Start with a Specific Model:** Launch Claude Code with a specific model using the `--model` flag: ```bash # Start with Opus claude --model claude-opus-4-5-20251101 # Start with Haiku for lightweight tasks claude --model claude-haiku-4-5-20251001 ``` ## Switching Models Mid-Session Use the `/model` command to switch models during an active session: ```bash # Using full model names /model claude-opus-4-5-20251101 # This will be used from anthropic provider /model claude-sonnet-4-5-20250929 # This will be used from anthropic provider # Using different providers dynamically via FinOps /model vertex/claude-haiku-4-5 /model azure/claude-sonnet-4-5 /model bedrock/claude-sonnet-4-5 ``` Run `/model` without arguments to check your current model. The switch is instantaneous and Claude Code seamlessly continues your conversation context with the new model. If you use Claude-specific features like **web search**, **computer use**, or **citations**, ensure the model you switch to also supports these capabilities. Non-Claude models or Claude models on certain providers may not support all features. ## Provider Compatibility **Not all providers work well with Claude Code**. Since Claude Code heavily relies on tool calling for file operations, terminal commands, and code editing, providers must properly support and stream tool call arguments. **Known Issues:** * **OpenRouter**: Does not stream function call arguments properly. Tool calls return with empty `arguments` fields, causing Claude Code to fail when attempting file operations or other tool-based actions. * **Some proxy providers**: May not fully implement the Anthropic API streaming specification for tool calls. If you experience issues with tool calls not executing properly, try switching to a different provider in your FinOps configuration. ## Checklist 1. Ensure the model selected is same as you configured in the `settings.json`.
Selected model in Claude cli
If this is not the case - 1. Select model using /config 2. Execute `/config` 3. Search for model 4. Select the correct model
Claude code model selection using /config
1. Or pass the model using `/model ` e.g., `/model sonnet-model` --- # Claude Desktop URL: /finops/cli-agents/claude-desktop Route Claude Desktop App traffic through FinOps for multi-provider routing, virtual keys, and observability. *** title: "Claude Desktop" description: "Route Claude Desktop App traffic through FinOps for multi-provider routing, virtual keys, and observability." --------------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' The [Claude Desktop App](https://claude.ai/download) brings Claude to your desktop with a chat interface and a built-in Code tab powered by [Claude Code](https://claude.com/product/claude-code). By routing the Code tab through FinOps, you get multi-provider routing, virtual keys, budget controls, and full observability. If your Allowed Headers are already set to `*`, you can skip this note. If not and you face issues integrating FinOps with Claude Desktop, try switching to `*` or adding the specific headers required by your client. By default, FinOps whitelists: `Content-Type`, `Authorization`, `X-Requested-With`, `X-Stainless-Timeout`, and `X-Api-Key`. ## How It Works The Claude Desktop App has two tabs with different routing behavior: | Tab | Traffic | FinOps Integration | | ------------ | ------------------------------------------------------------ | ------------------------------------------------------ | | **Code tab** | Uses the Anthropic Messages API (Claude Code under the hood) | Route inference through FinOps's `/anthropic` endpoint | | **Chat tab** | Connects directly to claude.ai | Connect to FinOps's `/mcp` endpoint for MCP tools | This guide covers configuring the **Code tab** for inference routing and the **Chat tab** for MCP tool access. ## Setup ### 1. Configure settings.json Open `~/.claude/settings.json` and add the FinOps endpoint and API key under the `env` key: ```json { "env": { "ANTHROPIC_API_KEY": "your-finops-virtual-key", "ANTHROPIC_BASE_URL": "{AI_GATEWAY_URL}/anthropic" } } ``` For production deployments: ```json { "env": { "ANTHROPIC_API_KEY": "your-finops-virtual-key", "ANTHROPIC_BASE_URL": "https://finops.example.com/anthropic" } } ``` You can open this file by running `/config` inside Claude Code, or by editing `~/.claude/settings.json` directly. These settings are shared between the Desktop app and the CLI. ### 2. Start a New Session Close any active session in the Code tab and start a new one for the settings to take effect. ## Amazon Bedrock via FinOps ### Setup Add the FinOps endpoint and pin model versions in `~/.claude/settings.json`: ```json { "env": { "ANTHROPIC_API_KEY": "finops-virtual-key", "ANTHROPIC_BASE_URL": "{AI_GATEWAY_URL}/anthropic", "ANTHROPIC_DEFAULT_SONNET_MODEL": "bedrock/global.anthropic.claude-sonnet-4-6", "ANTHROPIC_DEFAULT_HAIKU_MODEL": "bedrock/global.anthropic.claude-haiku-4-5-20251001-v1:0" } } ``` If you don't pin using settings.json - you can pin these in UI. Go to Dashboard > Models > Model Providers > AWS Bedrock > Key. And add deployments. Always pin model versions when using Bedrock. Without pinning, Claude Code aliases resolve to the latest version, which may not be enabled in your Bedrock account. ## Google Vertex AI via FinOps ### Setup ```json { "env": { "ANTHROPIC_API_KEY": "finops-virtual-key", "ANTHROPIC_BASE_URL": "{AI_GATEWAY_URL}/anthropic", "ANTHROPIC_DEFAULT_SONNET_MODEL": "vertex/claude-sonnet-4-6", "ANTHROPIC_DEFAULT_HAIKU_MODEL": "vertex/claude-haiku-4-5" } } ``` ## Azure via FinOps ### Setup ```json { "env": { "ANTHROPIC_API_KEY": "finops-virtual-key", "ANTHROPIC_BASE_URL": "{AI_GATEWAY_URL}/anthropic", "ANTHROPIC_DEFAULT_SONNET_MODEL": "azure/claude-sonnet-4-6", "ANTHROPIC_DEFAULT_HAIKU_MODEL": "azure/claude-haiku-4-5" } } ``` You will also have to map these model names to actual deployment names on FinOps dashboard. Azure-hosted models must support **tool use capabilities** for Claude Code to function properly. Verify tool calling support before configuring Azure models. ## Model Configuration The Code tab uses three model tiers: **Sonnet** (default), **Opus** (complex tasks), and **Haiku** (fast, lightweight). With FinOps, you can override these defaults to use any model from any provider. **Override Default Models:** Add to `~/.claude/settings.json`: ```json { "env": { "ANTHROPIC_DEFAULT_SONNET_MODEL": "openai/gpt-5", "ANTHROPIC_DEFAULT_OPUS_MODEL": "anthropic/claude-opus-4-5-20251101", "ANTHROPIC_DEFAULT_HAIKU_MODEL": "azure/claude-haiku-4-5" } } ``` Alternative models must support **tool use capabilities** for file operations, terminal commands, and code editing to work properly with Claude Code. ## MCP Integration (Chat Tab) The Chat tab supports MCP servers configured in `claude_desktop_config.json`. Connect to FinOps's MCP endpoint to give the Chat tab access to all your aggregated MCP tools: **Config file locations:** * **macOS**: `~/Library/Application Support/Claude/claude_desktop_config.json` * **Windows**: `%APPDATA%\Claude\claude_desktop_config.json` ```json { "mcpServers": { "finops": { "url": "{AI_GATEWAY_URL}/mcp", "headers": { "Authorization": "Bearer your-finops-virtual-key" } } } } ``` MCP servers in `claude_desktop_config.json` are for the **Chat tab only**. For MCP in the Code tab, configure servers in `~/.claude.json` or your project's `.mcp.json` file. See [MCP Gateway URL](/mcp/gateway-url) for full setup details. ## Enterprise Deployment For organization-wide FinOps routing, deploy a `managed-settings.json` file via MDM (Jamf, Kandji, Intune): * **macOS**: `/Library/Application Support/ClaudeCode/managed-settings.json` * **Windows**: `C:\Program Files\ClaudeCode\managed-settings.json` ```json { "env": { "ANTHROPIC_BASE_URL": "https://finops.example.com/anthropic", "ANTHROPIC_API_KEY": "org-finops-virtual-key" } } ``` Managed settings cannot be overridden by individual users, ensuring all Code tab traffic routes through FinOps. ## Observability All Claude Desktop Code tab requests through FinOps are logged. Monitor them at `{AI_GATEWAY_URL}/logs` - filter by provider, model, or search through conversation content to track usage patterns across your organization. ## Next Steps * [Provider Configuration](/finops/model-provider) - Configure AI providers in FinOps * [Virtual Keys](/finops/user-keys) - Set up usage limits and access control * [Built-in Observability](/finops/telemetry) - Monitor all AI traffic * [MCP Gateway URL](/mcp/gateway-url) - Full MCP server setup and tool filtering --- # Claude for Office URL: /finops/cli-agents/claude-for-office Use Claude for Office (Microsoft 365 add-in) with FinOps to route requests through any provider with virtual keys, budget controls, and observability. *** title: "Claude for Office" description: "Use Claude for Office (Microsoft 365 add-in) with FinOps to route requests through any provider with virtual keys, budget controls, and observability." --------------------------------------------------------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' [Claude for Office](https://marketplace.microsoft.com/en-us/product/saas/wa200009404?tab=overview) is Anthropic's Microsoft 365 add-in that brings Claude directly into Word, Excel, PowerPoint, and Outlook. By routing Claude for Office through FinOps, you get governance features like virtual keys, budget controls, rate limits, and built-in observability for all office-based AI usage across your organization.
Claude for Office with FinOps
## Setup ### 1. Install the Add-in Install the [Claude for Office add-in](https://marketplace.microsoft.com/en-us/product/saas/wa200009404?tab=overview) from the Microsoft AppSource marketplace within any Office application (Word, Excel, PowerPoint, or Outlook). Organization admins can also deploy it centrally via the Microsoft 365 admin center. ### 2. Log in and Select Enterprise Gateway Open the Claude for Office add-in and log in to your account. On the login screen, select **Enterprise Gateway** as your connection method. ### 3. Configure the API Endpoint Enter your FinOps endpoint as the **Base URL**: ``` https://finops.example.com/anthropic ``` For local development: ``` {AI_GATEWAY_URL}/anthropic ``` ### 4. Set Your API Key Enter your FinOps [virtual key](/finops/user-keys) or Anthropic API key in the **API Key** field. ### 5. Whitelist Required Headers If your Allowed Headers are already set to `*`, you can skip this step. Claude for Office requires the following headers to be in the Allowed Headers list. Go to **Settings > Client Settings** and add them as a comma-separated list: ``` anthropic-dangerous-direct-browser-access, anthropic-version, content-type, user-agent, x-api-key, x-stainless-arch, x-stainless-helper-method, x-stainless-lang, x-stainless-os, x-stainless-package-version, x-stainless-retry-count, x-stainless-runtime, x-stainless-runtime-version, x-stainless-timeout ``` ### 6. Enable CORS If your Allowed Origins are already set to `*`, you can skip this step. Claude for Office makes requests from the `pivot.claude.ai` domain. Go to **Settings > Client Settings** and add the following origin to your Allowed Origins list: ``` https://pivot.claude.ai ``` You're all set - Claude for Office will now route all requests through FinOps. ## How It Works Claude for Office uses the Anthropic Messages API natively. FinOps exposes a fully compatible Anthropic API at the `/anthropic` path, so the add-in works without any additional configuration beyond pointing it at your FinOps instance. FinOps automatically handles: * **Model routing** - requests are routed to the correct provider based on the model name * **Tool stripping** - server-side tools like `code_execution`, `web_search`, and `web_fetch` are automatically stripped to prevent API conflicts * **Model metadata** - token limits and capabilities are returned in list models responses for proper model selection in the add-in ## Using Other Providers (Azure, Vertex, Bedrock) By default, Claude for Office sends requests to the Anthropic API. To route requests through Azure, Vertex AI, or Amazon Bedrock instead, you have two options: ### Option 1: Set the Model Name Directly In the Claude for Office model selector, enter the provider-specific model name or deployment name. FinOps will automatically route the request to the correct provider based on the model identifier. For example: * **Azure**: Enter your Azure deployment name (e.g., `claude-opus-4-0`) * **Vertex AI**: Enter the Vertex model ID (e.g., `claude-opus-4@20250514`) * **Bedrock**: Enter the Bedrock model ID (e.g., `anthropic.claude-opus-4-0-20250514-v1:0`) ### Option 2: Use Routing Rules If you prefer to keep the default model names in Claude for Office and control routing server-side, create a [routing rule](/providers/routing-rules) in FinOps. This lets you route requests to any provider - with fallbacks - without changing anything in the add-in. For example, you can create a rule that matches requests from Claude for Office (based on the `origin` header) and routes them to Azure with a Vertex AI fallback:
Claude for Office routing rule
This approach is ideal for organization-wide deployments where you want centralized control over which provider handles Claude for Office traffic. ## Using Virtual Keys FinOps [Virtual Keys](/finops/user-keys) can be used as the API key in Claude for Office. This lets you: * Enforce per-user or per-team budgets and rate limits * Control which models and providers each user can access * Track usage and costs across your organization * Rotate credentials without updating every user's add-in configuration For organization-wide deployments, create separate virtual keys for each team or department to manage AI spend independently. ## Observability All Claude for Office requests through FinOps are logged. Monitor them at `{AI_GATEWAY_URL}/logs` - filter by provider, model, or search through conversation content to track usage patterns across your organization. ## Next Steps * [Provider Configuration](/finops/model-provider) - Configure AI providers in FinOps * [Virtual Keys](/finops/user-keys) - Set up usage limits and access control * [Built-in Observability](/finops/telemetry) - Monitor all AI traffic --- # Codex CLI URL: /finops/cli-agents/codex-cli Use OpenAI's Codex CLI with FinOps for powerful code generation with any provider. *** title: "Codex CLI" description: "Use OpenAI's Codex CLI with FinOps for powerful code generation with any provider." ------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' [Codex CLI](https://developers.openai.com/codex/cli/) provides powerful code generation and completion capabilities directly in your terminal. If your Allowed Headers are already set to `*`, you can skip this note. If not, and you face issues integrating FinOps with Codex CLI, try switching to `*` or adding the specific headers required by your client. By default, FinOps whitelists: `Content-Type`, `Authorization`, `X-Requested-With`, `X-Stainless-Timeout`, and `X-Api-Key`. ## Installing Codex CLI ```bash npm install -g @openai/codex ``` ## Configuring Codex CLI with FinOps Codex CLI always prefers OAuth over custom API keys. Make sure you run `/logout` before configuring the FinOps gateway with Codex. ### Update codex.toml Add the FinOps base URL and credentials to your global `~/.codex/config.toml` or project-specific `.codex/config.toml`: ```bash export OPENAI_API_KEY= ``` ```toml openai_base_url="{AI_GATEWAY_URL}/openai/v1" env_key="OPENAI_API_KEY" model = "openai/gpt-5.4" ``` Always run `codex` from the same terminal session where you exported variables, or restart the terminal after changing your profile. GUI-launched terminals or IDEs may not pick up shell-profile exports unless the environment is configured there as well. ## Using Non-OpenAI models Codex CLI defaults to [websocket mode](https://developers.openai.com/api/docs/guides/websocket-mode) for the Responses API and automatically falls back to HTTPS if the WebSocket connection fails. Non-OpenAI models are not supported in WebSocket mode, because in this mode, the server is expected to maintain the conversation context. If you are using non-OpenAI models, you must enable HTTPS mode. To enable https for Codex CLI by default, add these settings in your `config.toml`: ```toml model_provider = "openai_http" [model_providers.openai_http] name = "OpenAI HTTP" wire_api = "responses" supports_websockets = false base_url = "{AI_GATEWAY_URL}/openai/v1" ``` ## Model Configuration Use the `--model` flag to start Codex with a specific model: ```bash codex --model openai/gpt-5-codex codex --model openai/gpt-5.4-pro ``` You can also switch models mid-session with the `/model` command: ```bash /model openai/gpt-5.4-pro /model openai/gpt-5-codex ``` ## Using Non-OpenAI Models with Codex CLI FinOps automatically translates OpenAI API requests to other providers, so you can use Codex CLI with models from Anthropic, Google, Mistral, and more. Use the `provider/model-name` format to specify any FinOps-configured model: ```bash # Start with an Anthropic model codex --model anthropic/claude-sonnet-4-5-20250929 # Start with a Google model codex --model gemini/gemini-2.5-pro # Switch mid-session /model anthropic/claude-sonnet-4-5-20250929 /model mistral/mistral-large-latest ``` ### Supported Providers FinOps supports the following providers with the `provider/model-name` format: `openai`, `azure`, `gemini`, `vertex`, `bedrock`, `mistral`, `groq`, `cerebras`, `cohere`, `perplexity`, `xai`, `ollama`, `openrouter`, `huggingface`, `nebius`, `parasail`, `replicate`, `vllm`, `sgl` Non-OpenAI models **must support tool use** for Codex CLI to work properly. Codex CLI relies on tool calling for file operations, terminal commands, and code editing. Models without tool use support will fail on most operations. --- # Cursor URL: /finops/cli-agents/cursor Add FinOps as a custom model in Cursor, configure MCP tools, and use virtual keys for team access control. *** title: "Cursor" description: "Add FinOps as a custom model in Cursor, configure MCP tools, and use virtual keys for team access control." ------------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' [Cursor](https://cursor.com) is an AI-powered IDE that supports OpenAI-compatible APIs and MCP (Model Context Protocol). By connecting Cursor to FinOps, you get access to any provider/model in your FinOps configuration, plus MCP tools and governance features like virtual keys.
Setting up FinOps for Cursor
If your Allowed Headers are already set to `*`, you can skip this note. If not and you face issues integrating FinOps with Cursor, try switching to `*` or adding the specific headers required by your client. By default, FinOps whitelists: `Content-Type`, `Authorization`, `X-Requested-With`, `X-Stainless-Timeout`, and `X-Api-Key`. ## Setup 1. **Open Cursor Settings** Press `Cmd`+`,` (macOS) or `Ctrl`+`,` (Windows/Linux) and navigate to **Models**. 2. **Enter your API key** In the **OpenAI API Key** field, enter your FinOps virtual key or provider API key. 3. **Override the base URL** Toggle **Override OpenAI Base URL** to ON and enter your FinOps endpoint: For cursor you need publicly accessible link for FinOps. For deployed instances, use your FinOps deployment URL (e.g., `https://finops.example.com/cursor`). 4. **Add custom models** (optional) Type a model name in the **Add or search model** field using the `provider/model-name` format:
Adding a custom model in Cursor
Examples: `anthropic/claude-sonnet-4-5-20250929`, `openai/gpt-5`, `gemini-2.5-pro` | Provider | Format | Example | | ------------------- | ---------------------- | -------------------------------------- | | Anthropic | `anthropic/model-name` | `anthropic/claude-sonnet-4-5-20250929` | | Gemini | `model-name` | `gemini-2.5-pro` | | OpenAI | `openai/model-name` | `openai/gpt-5` | | Bedrock | `bedrock/model-name` | `bedrock/anthropic.claude-3` | | Vertex (non-Gemini) | `vertex/model-name` | `vertex/text-bison` | | Other providers | `provider/model-name` | `groq/llama-3.3-70b-versatile` | ## Using Virtual Keys FinOps [Virtual Keys](/finops/user-keys) can be used as the OpenAI API Key in Cursor. Virtual keys let you enforce budgets, rate limits, and provider access controls for each user or team. ## Model Selection Cursor assigns models to different features - **Chat**, **Agent**, **Inline Edit**, and **Tab Completion**. After configuring FinOps, you can assign any `provider/model-name` to each feature for optimal cost and performance: * Use a powerful model like `openai/gpt-5` or `anthropic/claude-sonnet-4-5-20250929` for Agent mode * Use a fast model like `groq/llama-3.3-70b-versatile` for Tab completion ## Using Multiple Providers FinOps routes requests to the correct provider based on the model name. Use the `provider/model-name` format to access any configured provider through the single OpenAI-compatible endpoint: ``` anthropic/claude-sonnet-4-5-20250929 openai/gpt-5 gemini/gemini-2.5-pro mistral/mistral-large-latest ``` ### Supported Providers FinOps supports the following providers with the `provider/model-name` format: `openai`, `anthropic`, `azure`, `gemini`, `vertex`, `bedrock`, `mistral`, `groq`, `cerebras`, `cohere`, `perplexity`, `xai`, `ollama`, `openrouter`, `huggingface`, `nebius`, `parasail`, `replicate`, `vllm`, `sgl` Non-native models **must support tool use** for Cursor's agent mode and inline editing to work properly. Models without tool use support will only work for basic chat. Cursor's "Override OpenAI Base URL" is a global setting that applies to all OpenAI-compatible models. This works well with FinOps since FinOps handles routing to the correct provider based on the model name. ## Observability All Cursor requests through FinOps are logged. Monitor them at `{AI_GATEWAY_URL}/logs` - filter by provider, model, or search through conversation content. --- # Gemini CLI URL: /finops/cli-agents/gemini-cli Use Google's Gemini CLI with FinOps for advanced reasoning capabilities with any provider. *** title: "Gemini CLI" description: "Use Google's Gemini CLI with FinOps for advanced reasoning capabilities with any provider." --------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' [Gemini CLI](https://github.com/google-gemini/gemini-cli) is Google's powerful coding assistant with advanced reasoning capabilities. If your Allowed Headers are already set to `*`, you can skip this note. If not and you face issues integrating FinOps with Gemini CLI, try switching to `*` or adding the specific headers required by your client. By default, FinOps whitelists: `Content-Type`, `Authorization`, `X-Requested-With`, `X-Stainless-Timeout`, and `X-Api-Key`. ## To install Gemini CLI ```bash npm install -g @google/gemini-cli ``` ## Configuring Gemini CLI to work with FinOps Gemini CLI supports multiple authentication methods. Choose the one that matches your account type. ### Google account (OAuth) Log in with your Google account for free-tier access (60 requests/min, 1,000 requests/day). 1. **Set the FinOps base URL** ```bash export GOOGLE_GEMINI_BASE_URL={AI_GATEWAY_URL}/genai ``` 2. **Run Gemini CLI and sign in** ```bash gemini ``` Select **Login with Google** and authenticate via your browser. All traffic automatically routes through FinOps. ### API key based usage For users with a Gemini API key (obtain one from [Google AI Studio](https://aistudio.google.com/apikey)): 1. **Configure environment variables** ```bash export GEMINI_API_KEY=your-api-key # Gemini API key or FinOps virtual key export GOOGLE_GEMINI_BASE_URL={AI_GATEWAY_URL}/genai ``` 2. **Run Gemini CLI** ```bash gemini ``` Select **Use Gemini API Key** in the CLI prompt for authentication.
Gemini CLI authentication
### Google Cloud / Vertex AI For enterprise users with Vertex AI access: ```bash export GOOGLE_API_KEY=your-api-key # Google API key or FinOps virtual key export GOOGLE_GENAI_USE_VERTEXAI=true export GOOGLE_GEMINI_BASE_URL={AI_GATEWAY_URL}/genai gemini ``` For paid Code Assist License users, set your Google Cloud project: `export GOOGLE_CLOUD_PROJECT="your-project-id"` Now all Gemini CLI traffic flows through FinOps, giving you access to any provider/model configured in your FinOps setup, plus observability and governance. ## Model Configuration Use the `-m` flag to start Gemini CLI with a specific model: ```bash gemini -m gemini-2.5-flash gemini -m gemini-2.5-pro ``` ## Using Non-Google Models with Gemini CLI FinOps automatically translates GenAI API requests to other providers, so you can use Gemini CLI with models from OpenAI, Anthropic, Mistral, and more. Use the `provider/model-name` format to specify any FinOps-configured model. ```bash # Start with an OpenAI model gemini -m openai/gpt-5 # Start with an Anthropic model gemini -m anthropic/claude-sonnet-4-5-20250929 # Start with a Groq model gemini -m groq/llama-3.3-70b-versatile ``` ### Supported Providers FinOps supports the following providers with the `provider/model-name` format: `openai`, `azure`, `gemini`, `vertex`, `bedrock`, `mistral`, `groq`, `cerebras`, `cohere`, `perplexity`, `xai`, `ollama`, `openrouter`, `huggingface`, `nebius`, `parasail`, `replicate`, `vllm`, `sgl` Non-Google models **must support tool use** for Gemini CLI to work properly. Gemini CLI relies on tool calling for file operations, terminal commands, and code editing. Models without tool use support will fail on most operations. --- # Overview URL: /finops/cli-agents Use FinOps with LibreChat, Claude Code, Codex CLI, Gemini CLI, Qwen Code, and more by pointing each tool at the correct FinOps endpoint. *** title: "Overview" description: "Use FinOps with LibreChat, Claude Code, Codex CLI, Gemini CLI, Qwen Code, and more by pointing each tool at the correct FinOps endpoint." ------------------------------------------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' ## Overview FinOps provides **100% compatible endpoints** for OpenAI, Anthropic, and Gemini APIs, making it seamless to integrate with any agent that uses these providers. Point each agent at the FinOps URL shape it expects (see [Configuration](#configuration) below and the guide for your tool). That unlocks: * **Universal Model Access**: Use **any provider/model** configured in FinOps with any agent (e.g., use GPT-5 with Claude Code, or Claude Sonnet 4.5 with Codex CLI) * **MCP Tools Integration**: All Model Context Protocol tools configured in FinOps become available to your agents * **Built-in Observability**: Monitor all agent interactions in real-time through FinOps's logging dashboard * **Load Balancing**: Automatically distribute requests across multiple providers and regions * **Advanced Features**: Governance, caching, failover, and more - all transparent to your agent If your Allowed Headers are already set to `*`, you can skip this note. If not and you face issues integrating FinOps with your CLI agent, try switching to `*` or adding the specific headers required by your client. By default, FinOps whitelists: `Content-Type`, `Authorization`, `X-Requested-With`, `X-Stainless-Timeout`, and `X-Api-Key`. ## CLI Agents * **[LibreChat](/finops/cli-agents/librechat)** — Open-source chat client supporting multiple providers * **[Open WebUI](/finops/cli-agents/open-webui)** — ChatGPT-like open-source chat interface * **[Claude Code](/finops/cli-agents/claude-code)** — AI-powered coding directly in your terminal * **[Claude for Office](/finops/cli-agents/claude-for-office)** — Claude in Word, Excel, PowerPoint, and Outlook * **[Claude Desktop](/finops/cli-agents/claude-desktop)** — Route Claude Desktop App's Code tab through any provider * **[Codex CLI](/finops/cli-agents/codex-cli)** — OpenAI's powerful code generation CLI * **[Gemini CLI](/finops/cli-agents/gemini-cli)** — Google's coding assistant with advanced reasoning * **[Qwen Code](/finops/cli-agents/qwen-code)** — Alibaba's coding assistant * **[Opencode](/finops/cli-agents/opencode)** — Terminal-based coding assistant by SST ## Editors * **[Cursor](/finops/cli-agents/cursor)** — AI-powered IDE with MCP integration and virtual key support * **[Zed Editor](/finops/cli-agents/zed-editor)** — High-performance editor with AI integration * **[Roo Code](/finops/cli-agents/roo-code)** — AI-powered VS Code extension with multi-provider support ## Configuration **OpenAI-compatible URL shape** varies by client: tools such as **Codex CLI** need the API base to end with **`/v1`** (e.g. `https://your-gateway/openai/v1`). Official OpenAI SDKs often take `https://your-gateway/openai` and add `/v1` to request paths. Use the page for your agent to avoid 404s or wrong-host errors. Agent integrations work with your existing FinOps configuration. Ensure you have: * **Providers configured**: See [Provider Configuration](/finops/model-provider) for setup details * **Optional: MCP tools**: See [MCP Integration](/mcp/overview) to enhance agent capabilities ## Monitoring Agent Traffic All agent interactions are automatically logged and can be monitored at `{AI_GATEWAY_URL}/logs`. You can filter by provider, model, or search through conversation content to track your agents' performance.
Agent Monitoring
For complete monitoring capabilities, see [Built-in Observability](/finops/telemetry). ## MCP Tools Integration This feature is only available on `v1.4.0-prerelease1` and above. FinOps exposes all configured MCP tools through a dedicated MCP server endpoint at `/mcp`. This allows external MCP clients (Claude Code, Cursor, and other MCP-compatible applications) to connect directly and access your tools. ### Connect Claude Code to FinOps MCP Add FinOps as an MCP server to Claude Code: ```bash claude mcp add --transport http finops {AI_GATEWAY_URL}/mcp ``` **Using Virtual Key Authentication:** If you have virtual key authentication enabled in FinOps, connect using the JSON configuration format: ```bash claude mcp add-json finops '{"type":"http","url":"{AI_GATEWAY_URL}/mcp","headers":{"Authorization":"Bearer bf-virtual-key"}}' ``` Replace `bf-virtual-key` with your actual FinOps virtual key. Claude Code will only have access to the specific MCP tools permitted by the virtual key's configuration. To grant access to additional tools, verify or modify the virtual key's MCP tool permissions in the FinOps dashboard. ### Supported Agents You can connect any MCP-compatible client to FinOps's MCP server: * **Claude Code** - Add via `claude mcp add` command * **Cursor IDE** - Configure in cursor settings * **Custom Applications** - Any app implementing the MCP protocol ### Tool Access Control Control which tools each client can access using Virtual Keys: * Create a Virtual Key for each client/environment * Configure which MCP servers and tools the key can access * FinOps automatically enforces these permissions For complete setup instructions and tool filtering options, see [MCP Gateway URL](/mcp/gateway-url). ## Next Steps * **[Provider Configuration](/finops/model-provider)** - Configure AI providers for your agents * **[Governance](/finops/user-keys)** - Set usage limits and policies for your agents * **[Integrations](/finops/integrations/what-is-an-integration)** - Understand how FinOps works with existing AI provider SDKs --- # LibreChat URL: /finops/cli-agents/librechat Integrate LibreChat with FinOps to access any AI provider through a modern open-source chat interface with virtual keys and observability. *** title: "LibreChat" description: "Integrate LibreChat with FinOps to access any AI provider through a modern open-source chat interface with virtual keys and observability." --------------------------------------------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' [LibreChat](https://github.com/danny-avila/LibreChat) is a modern, open-source chat client that supports multiple AI providers. By adding FinOps as a custom provider, you get access to any model configured in FinOps through a familiar chat interface, plus governance features like virtual keys and built-in observability. If your Allowed Headers are already set to `*`, you can skip this note. If not and you face issues integrating FinOps with LibreChat, try switching to `*` or adding the specific headers required by your client. By default, FinOps whitelists: `Content-Type`, `Authorization`, `X-Requested-With`, `X-Stainless-Timeout`, and `X-Api-Key`. ## Setup ### 1. Install LibreChat Follow the [LibreChat documentation](https://www.librechat.ai/docs/local) for local setup. There are multiple installation options (Docker, npm, etc.). ### 2. Add FinOps as a Custom Provider Add the following to your `librechat.yaml` file: ```yaml custom: - name: "FinOps" apiKey: "dummy" baseURL: "{AI_GATEWAY_URL}/v1" models: default: ["openai/gpt-4o"] fetch: true titleConvo: true titleModel: "openai/gpt-4o" summarize: false summaryModel: "openai/gpt-4o" forcePrompt: false modelDisplayLabel: "FinOps" iconURL: /media/architecture.png ``` | Field | Description | | ---------------- | ---------------------------------------------------------------------- | | `apiKey` | FinOps virtual key if authentication is enabled; use `dummy` otherwise | | `baseURL` | FinOps gateway URL + `/v1` (LibreChat uses OpenAI format) | | `models.default` | Default models to show. Use FinOps model IDs (`provider/model`) | | `models.fetch` | Set `true` to fetch available models from FinOps | | `titleConvo` | Use AI for conversation title generation | | `titleModel` | Model for title generation | | `summarize` | Enable chat summary generation | | `summaryModel` | Model for summaries | Set `models.fetch: true` to automatically discover all models configured in FinOps. This keeps your LibreChat model list in sync with your FinOps provider configuration. If you're running LibreChat in Docker, it does not automatically use `librechat.yaml`. See [Step 1 of the LibreChat custom endpoints guide](https://www.librechat.ai/docs/quick_start/custom_endpoints#step-1-create-or-edit-a-docker-override-file) for how to mount or override the config. ### 3. Docker Networking Choose the correct `baseURL` for your setup: | Setup | baseURL | | -------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | LibreChat and FinOps on same host | `{AI_GATEWAY_URL}/v1` | | LibreChat in Docker Desktop, FinOps on host | `http://host.docker.internal:8080/v1` | | LibreChat in Docker Engine (Linux), FinOps on host | Add `--add-host=host.docker.internal:host-gateway` to `docker run`, or `extra_hosts: ["host.docker.internal:host-gateway"]` in Compose, then use `http://host.docker.internal:8080/v1` | | Both in same Docker network | `http://finops-container-name:8080/v1` | ### 4. Run LibreChat Start LibreChat. FinOps will appear as a provider with all configured models available. ## Virtual Keys When FinOps has [virtual key authentication](/finops/user-keys) enabled, set `apiKey` to your virtual key: ```yaml apiKey: "bf-your-virtual-key-here" ``` This lets you enforce usage limits, budgets, and access control per user or team. For team deployments, create a separate virtual key for each team or environment - each key can have its own rate limits, budgets, and provider access rules configured in the FinOps dashboard. ## Model Selection LibreChat displays models from the `models.default` list or fetches them from FinOps when `models.fetch` is enabled. Use FinOps model IDs in `provider/model` format to access any configured provider: ```yaml models: default: - "openai/gpt-5" - "anthropic/claude-sonnet-4-5-20250929" - "gemini/gemini-2.5-pro" - "groq/llama-3.3-70b-versatile" fetch: true ``` * Use powerful models like `openai/gpt-5` or `anthropic/claude-sonnet-4-5-20250929` for complex conversations * Use fast models like `groq/llama-3.3-70b-versatile` for quick responses * Set `titleModel` and `summaryModel` to lighter models to reduce cost for metadata generation ## Using Multiple Providers FinOps routes requests to the correct provider based on the model name. Use the `provider/model-name` format to access any configured provider through the single `/v1` endpoint: ``` anthropic/claude-sonnet-4-5-20250929 openai/gpt-5 gemini/gemini-2.5-pro mistral/mistral-large-latest ``` ### Supported Providers FinOps supports the following providers with the `provider/model-name` format: `openai`, `azure`, `gemini`, `vertex`, `bedrock`, `mistral`, `groq`, `cerebras`, `cohere`, `perplexity`, `xai`, `ollama`, `openrouter`, `huggingface`, `nebius`, `parasail`, `replicate`, `vllm`, `sgl` LibreChat connects to FinOps via a single OpenAI-compatible endpoint. FinOps handles routing to the correct provider based on the model name - no per-provider configuration needed in LibreChat. ## Observability All LibreChat traffic through FinOps is logged. Monitor it at `{AI_GATEWAY_URL}/logs` - filter by provider, model, or search through conversation content to track usage across your team. ## Next Steps * [Provider Configuration](/finops/model-provider) - Configure AI providers in FinOps * [Virtual Keys](/finops/user-keys) - Set up usage limits and access control --- # Open WebUI URL: /finops/cli-agents/open-webui Integrate Open WebUI with FinOps to access any AI provider through a modern open-source chat interface with virtual keys and observability. *** title: "Open WebUI" description: "Integrate Open WebUI with FinOps to access any AI provider through a modern open-source chat interface with virtual keys and observability." ---------------------------------------------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' [Open WebUI](https://github.com/open-webui/open-webui) is a modern, open-source chat interface that supports OpenAI-compatible APIs. By adding FinOps as a connection, you get access to any model configured in FinOps through a familiar ChatGPT-like interface, plus governance features like virtual keys and built-in observability. If your Allowed Headers are already set to `*`, you can skip this note. If not and you face issues integrating FinOps with Open WebUI, try switching to `*` or adding the specific headers required by your client. By default, FinOps whitelists: `Content-Type`, `Authorization`, `X-Requested-With`, `X-Stainless-Timeout`, and `X-Api-Key`. ## Setup ### 1. Install Open WebUI Follow the [Open WebUI documentation](https://docs.openwebui.com/getting-started/installation/) for installation. Open WebUI can run via Docker, Docker Compose, or Kubernetes. ### 2. Add FinOps as a Connection If running Open WebUI in Docker and FinOps is on the host machine, use `http://host.docker.internal:8080/v1` instead of `localhost`. 1. Open Open WebUI in your browser 2. Go to **⚙️ Admin Settings** → **Connections** → **OpenAI** 3. Click **➕ Add Connection** 4. Configure the following: | Field | Value | | ----------- | ------------------------------------------------------------------------------------------ | | **URL** | `{AI_GATEWAY_URL}/v1` (or your FinOps host, e.g. `https://finops.yourcompany.com/v1`) | | **API Key** | Your FinOps virtual key if authentication is enabled; otherwise leave empty or use `dummy` | 5. Click **Save**
Adding FinOps as a connection in Open WebUI Admin Settings
### 3. Model Discovery Open WebUI fetches available models from FinOps's `/v1/models` endpoint. If auto-detection fails or you want to filter which models appear, add model IDs to the **Model IDs (Filter)** allowlist in the connection settings. Use FinOps model IDs in `provider/model` format (e.g. `openai/gpt-5`, `anthropic/claude-sonnet-4-5-20250929`).
FinOps models listed in the Open WebUI model selector
### 4. Start Chatting Select your FinOps connection's model from the chat model selector and start chatting.
Image generation and chat in Open WebUI powered by FinOps
## Virtual Keys When FinOps has [virtual key authentication](/finops/user-keys) enabled, set **API Key** in the connection to your virtual key. This lets you enforce usage limits, budgets, and access control per user or team. For team deployments, create separate Open WebUI connections (or use different API keys per connection) - each virtual key can have its own rate limits, budgets, and provider access rules configured in the FinOps dashboard. ## Model Selection Open WebUI displays models fetched from FinOps or those you add to the Model IDs allowlist. Use FinOps model IDs in `provider/model` format to access any configured provider: * Use powerful models like `openai/gpt-5` or `anthropic/claude-sonnet-4-5-20250929` for complex conversations * Use fast models like `groq/llama-3.3-70b-versatile` for quick responses ## Using Multiple Providers FinOps routes requests to the correct provider based on the model name. Use the `provider/model-name` format to access any configured provider through the single `/v1` endpoint: ``` anthropic/claude-sonnet-4-5-20250929 openai/gpt-5 gemini/gemini-2.5-pro mistral/mistral-large-latest ``` ### Supported Providers FinOps supports the following providers with the `provider/model-name` format: `openai`, `azure`, `gemini`, `vertex`, `bedrock`, `mistral`, `groq`, `cerebras`, `cohere`, `perplexity`, `xai`, `ollama`, `openrouter`, `huggingface`, `nebius`, `parasail`, `replicate`, `vllm`, `sgl` Open WebUI connects to FinOps via a single OpenAI-compatible endpoint. FinOps handles routing to the correct provider based on the model name - no per-provider configuration needed in Open WebUI. ## Multimodality Open WebUI supports image generation and vision (image understanding). You can use FinOps for both. ### Image Generation Set a FinOps provider/model as your **image inference engine** for DALL·E-style image generation: 1. Go to **⚙️ Admin Settings** → **Settings** → **Images** 2. Set **Image Generation Engine** to **Open AI** 3. Configure: * **API Endpoint URL**: `{AI_GATEWAY_URL}/v1` (or your FinOps host + `/v1`) * **API Key**: Your FinOps virtual key if authentication is enabled * **Model**: FinOps model ID in `provider/model` format (e.g. `openai/dall-e-3`, `openai/gpt-image-1`) FinOps routes image generation requests to the configured provider. Use any image-capable model in your FinOps configuration (OpenAI DALL·E, GPT-Image, or other providers that support `/v1/images/generations`).
Image generation setup in Open WebUI Admin Settings
### Vision (Image Understanding) Chat models that support vision (e.g. `openai/gpt-4o`, `anthropic/claude-sonnet-4-5`) work through your main FinOps connection. When you select a vision-capable model in the chat selector, you can attach images to your messages - Open WebUI sends them to FinOps, which routes to the correct provider. ## Docker Networking Choose the correct URL for your setup: | Setup | URL | | ------------------------------------ | -------------------------------------- | | Open WebUI and FinOps on same host | `{AI_GATEWAY_URL}/v1` | | Open WebUI in Docker, FinOps on host | `http://host.docker.internal:8080/v1` | | Both in same Docker network | `http://finops-container-name:8080/v1` | ## Environment Variables (Alternative) You can also configure FinOps via environment variables when running Open WebUI: ```bash # Single connection OPENAI_API_BASE_URLS="{AI_GATEWAY_URL}/v1" OPENAI_API_KEYS="your-finops-virtual-key" # Multiple connections (semicolon-separated) OPENAI_API_BASE_URLS="{AI_GATEWAY_URL}/v1;https://other-gateway.com/v1" OPENAI_API_KEYS="key1;key2" ``` ## Observability All Open WebUI traffic through FinOps is logged. Monitor it at `{AI_GATEWAY_URL}/logs` - filter by provider, model, or search through conversation content to track usage across your team. ## Next Steps * [Provider Configuration](/finops/model-provider) - Configure AI providers in FinOps * [Virtual Keys](/finops/user-keys) - Set up usage limits and access control --- # Opencode URL: /finops/cli-agents/opencode Use Opencode with FinOps to access any AI provider through a terminal-based coding assistant with virtual keys and observability. *** title: "Opencode" description: "Use Opencode with FinOps to access any AI provider through a terminal-based coding assistant with virtual keys and observability." ------------------------------------------------------------------------------------------------------------------------------------------------ import { Callout } from 'fumadocs-ui/components/callout' [Opencode](https://github.com/sst/opencode) is an AI-powered coding application that supports OpenAI-compatible APIs. By pointing it at FinOps, you get access to any provider/model in your FinOps configuration, plus governance features like virtual keys, built-in observability, and per-model options for reasoning effort, thinking budget, and more.
Opencode with FinOps
If your Allowed Headers are already set to `*`, you can skip this note. If not and you face issues integrating FinOps with OpenCode, try switching to `*` or adding the specific headers required by your client. By default, FinOps whitelists: `Content-Type`, `Authorization`, `X-Requested-With`, `X-Stainless-Timeout`, and `X-Api-Key`. ## Setup ### 1. Configure OpenCode to work with FinOps OpenCode uses a JSON config file (`opencode.json`) to configure providers. Point your provider's `baseURL` to FinOps. ### Using OpenAI-compatible endpoint Route OpenAI and other providers through FinOps's OpenAI endpoint: ```jsonc { "$schema": "https://opencode.ai/config.json", "provider": { "openai": { "name": "FinOps", "options": { "baseURL": "{AI_GATEWAY_URL}/openai", "apiKey": "your-finops-key" }, "models": { "openai/gpt-5": {}, "anthropic/claude-sonnet-4-5-20250929": {}, "gemini/gemini-2.5-pro": {} } } }, "model": "openai/gpt-5" } ``` ### Using Anthropic endpoint Route Anthropic models through FinOps's Anthropic endpoint: ```jsonc { "$schema": "https://opencode.ai/config.json", "provider": { "anthropic": { "name": "FinOps", "options": { "baseURL": "{AI_GATEWAY_URL}/anthropic/v1", "apiKey": "your-finops-key" }, "models": { "anthropic/claude-sonnet-4-5-20250929": {} } } }, "model": "anthropic/claude-sonnet-4-5-20250929" } ``` You can also use the `/connect` command in the OpenCode TUI to configure credentials interactively, then update the `baseURL` in your config file. ## Virtual Keys When FinOps has [virtual key authentication](/finops/user-keys) enabled, set `apiKey` in your provider options to your virtual key: ```jsonc "options": { "baseURL": "{AI_GATEWAY_URL}/openai", "apiKey": "bf-your-virtual-key-here" } ``` This lets you enforce usage limits, budgets, and access control per user or environment. For team deployments, create a separate virtual key for each team - each key can have its own rate limits, budgets, and provider access rules configured in the FinOps dashboard. ## Model Selection Set your default models in `opencode.json`: ```jsonc { "model": "openai/gpt-5", "small_model": "anthropic/claude-haiku-4-5" } ``` Switch models in the TUI with `ctrl`+`p`
Opencode model selection
* Use powerful models like `openai/gpt-5` or `anthropic/claude-sonnet-4-5-20250929` for complex coding tasks * Use fast models like `groq/llama-3.3-70b-versatile` for quick completions * Set `small_model` to a lighter model for faster, lower-cost operations ## Using Multiple Providers FinOps routes requests to the correct provider based on the model name. Use the `provider/model-name` format to access any configured provider through the single OpenAI endpoint: ``` anthropic/claude-sonnet-4-5-20250929 openai/gpt-5 gemini/gemini-2.5-pro mistral/mistral-large-latest ``` You can configure models from different providers with per-model options: ```jsonc { "$schema": "https://opencode.ai/config.json", "theme": "opencode", "autoupdate": true, "provider": { "openai": { "name": "FinOps", "options": { "baseURL": "{AI_GATEWAY_URL}/openai", "apiKey": "your-finops-key" }, "models": { "openai/gpt-5": { "options": { "reasoningEffort": "high", "textVerbosity": "low", "reasoningSummary": "auto", "include": [ "reasoning.encrypted_content" ] } }, "anthropic/claude-sonnet-4-5-20250929": { "options": { "thinking": { "type": "enabled", "budgetTokens": 16000 } } } } } } } ``` ### Supported Providers FinOps supports the following providers with the `provider/model-name` format: `openai`, `azure`, `gemini`, `vertex`, `bedrock`, `mistral`, `groq`, `cerebras`, `cohere`, `perplexity`, `xai`, `ollama`, `openrouter`, `huggingface`, `nebius`, `parasail`, `replicate`, `vllm`, `sgl` Non-native models **must support tool use** for OpenCode to work properly. OpenCode relies on tool calling for file operations, terminal commands, and code editing. Models without tool use support will fail on most operations. OpenCode connects to FinOps via a single endpoint. FinOps handles routing to the correct provider based on the model name - no per-provider configuration needed. ## Observability All OpenCode traffic through FinOps is logged. Monitor it at `{AI_GATEWAY_URL}/logs` - filter by provider, model, or search through conversation content to track usage. ## Next Steps * [Provider Configuration](/finops/model-provider) - Configure AI providers in FinOps * [Virtual Keys](/finops/user-keys) - Set up usage limits and access control --- # Qwen Code URL: /finops/cli-agents/qwen-code Use Alibaba's Qwen Code with FinOps for AI-powered coding with any provider, virtual keys, and observability. *** title: "Qwen Code" description: "Use Alibaba's Qwen Code with FinOps for AI-powered coding with any provider, virtual keys, and observability." ---------------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' [Qwen Code](https://github.com/QwenLM/qwen-code) is Alibaba's powerful coding assistant with advanced reasoning capabilities. By connecting it to FinOps, you get access to any provider/model in your FinOps configuration, plus governance features like virtual keys and built-in observability. If your Allowed Headers are already set to `*`, you can skip this note. If not and you face issues integrating FinOps with Qwen Code, try switching to `*` or adding the specific headers required by your client. By default, FinOps whitelists: `Content-Type`, `Authorization`, `X-Requested-With`, `X-Stainless-Timeout`, and `X-Api-Key`. ## Setup ### 1. Install Qwen Code ```bash npm install -g @qwen-code/qwen-code ``` ### 2. Configure FinOps as a Model Provider Qwen Code uses `~/.qwen/settings.json` to configure model providers. Add FinOps as an OpenAI-compatible provider: ```json { "modelProviders": { "openai": [ { "id": "openai/gpt-5", "name": "GPT-5 (via FinOps)", "baseUrl": "{AI_GATEWAY_URL}/openai", "envKey": "OPENAI_API_KEY" }, { "id": "anthropic/claude-sonnet-4-5-20250929", "name": "Claude Sonnet 4.5 (via FinOps)", "baseUrl": "{AI_GATEWAY_URL}/openai", "envKey": "OPENAI_API_KEY" } ] }, "security": { "auth": { "selectedType": "openai" } }, "model": { "name": "openai/gpt-5" } } ``` ### 3. Set Your API Key Set the `OPENAI_API_KEY` environment variable to your FinOps virtual key or provider API key: ```bash export OPENAI_API_KEY=your-finops-virtual-key ``` Alternatively, use a `.env` file in `~/.qwen/.env`: ``` OPENAI_API_KEY=your-finops-virtual-key ``` ### 4. Run Qwen Code ```bash qwen ``` You can also use environment variables for a minimal setup. Set `OPENAI_BASE_URL` and `OPENAI_API_KEY`, then run `qwen`. Note: some Qwen Code versions prioritize `settings.json` over env vars - use `settings.json` for reliable configuration. ## Virtual Keys When FinOps has [virtual key authentication](/finops/user-keys) enabled, set `OPENAI_API_KEY` to your virtual key. This lets you enforce usage limits, budgets, and access control per user or environment. For team deployments, create a separate virtual key for each team - each key can have its own rate limits, budgets, and provider access rules configured in the FinOps dashboard. ## Model Selection Use the `/model` command to switch between models at runtime. All models configured in your `modelProviders` appear in the picker. ```bash # Launch with a specific model qwen --model "anthropic/claude-sonnet-4-5-20250929" ``` * Use powerful models like `openai/gpt-5` or `anthropic/claude-sonnet-4-5-20250929` for complex coding tasks * Use fast models like `groq/llama-3.3-70b-versatile` for quick completions ## Using Multiple Providers FinOps routes requests to the correct provider based on the model name. Use the `provider/model-name` format in your `modelProviders` config to access any configured provider through the single OpenAI endpoint: ``` anthropic/claude-sonnet-4-5-20250929 openai/gpt-5 gemini/gemini-2.5-pro mistral/mistral-large-latest ``` Add multiple models to your `modelProviders.openai` array - they all use the same FinOps `baseUrl` and `envKey`. ### Supported Providers FinOps supports the following providers with the `provider/model-name` format: `openai`, `azure`, `gemini`, `vertex`, `bedrock`, `mistral`, `groq`, `cerebras`, `cohere`, `perplexity`, `xai`, `ollama`, `openrouter`, `huggingface`, `nebius`, `parasail`, `replicate`, `vllm`, `sgl` Non-native models **must support tool use** for Qwen Code to work properly. Qwen Code relies on tool calling for file operations, terminal commands, and code editing. Models without tool use support will fail on most operations. Qwen Code connects to FinOps via a single OpenAI-compatible endpoint. FinOps handles routing to the correct provider based on the model name - no per-provider configuration needed. ## Observability All Qwen Code traffic through FinOps is logged. Monitor it at `{AI_GATEWAY_URL}/logs` - filter by provider, model, or search through conversation content to track usage. ## Next Steps * [Provider Configuration](/finops/model-provider) - Configure AI providers in FinOps * [Virtual Keys](/finops/user-keys) - Set up usage limits and access control --- # Roo Code URL: /finops/cli-agents/roo-code Use Roo Code with FinOps to access any AI provider through a powerful VS Code extension with virtual keys and observability. *** title: "Roo Code" description: "Use Roo Code with FinOps to access any AI provider through a powerful VS Code extension with virtual keys and observability." ------------------------------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' [Roo Code](https://roo-code.net/) is an AI-powered VS Code extension that supports OpenAI-compatible APIs. By connecting it to FinOps, you get access to any provider/model in your FinOps configuration, plus governance features like virtual keys and built-in observability. If your Allowed Headers are already set to `*`, you can skip this note. If not and you face issues integrating FinOps with Roo Code, try switching to `*` or adding the specific headers required by your client. By default, FinOps whitelists: `Content-Type`, `Authorization`, `X-Requested-With`, `X-Stainless-Timeout`, and `X-Api-Key`. ## Setup ### 1. Install Roo Code Install the [Roo Code extension](https://marketplace.visualstudio.com/items?itemName=RooCodeInc.roo-code) from the VS Code marketplace. ### 2. Create an API Configuration Profile 1. Open **Settings** (click the gear icon) → **Providers** 2. Click the **+** button to create a new profile 3. Select **OpenAI Compatible** as the provider 4. Configure the following: | Field | Value | | ------------ | -------------------------------------------------------------------------------------------------------- | | **Base URL** | `{AI_GATEWAY_URL}/openai` (or your FinOps host, e.g. `https://finops.yourcompany.com/openai`) | | **API Key** | Your FinOps virtual key if authentication is enabled; otherwise use `dummy` or leave empty | | **Model** | FinOps model ID in `provider/model` format (e.g. `anthropic/claude-sonnet-4-5-20250929`, `openai/gpt-5`) |
Roo Code FinOps configuration
### 3. Verify the Connection Ask Roo which model it's using - it should respond with the FinOps model ID you configured (e.g. `anthropic/claude-sonnet-4-5`).
Roo Code model verification
Roo Code supports multiple API configuration profiles. Create separate profiles for different FinOps virtual keys or model combinations, then switch between them via the profile dropdown in Settings or during chat. ## Virtual Keys When FinOps has [virtual key authentication](/finops/user-keys) enabled, set **API Key** in your Roo Code profile to your virtual key. This lets you enforce usage limits, budgets, and access control per user or team. For team deployments, create a separate configuration profile for each team - each can use a different virtual key with its own rate limits, budgets, and provider access rules configured in the FinOps dashboard. ## Model Selection Roo Code lets you assign models per mode (Code, Ask, Architect, Debug, Orchestrator). Use FinOps model IDs in `provider/model` format to access any configured provider: * Use powerful models like `openai/gpt-5` or `anthropic/claude-sonnet-4-5-20250929` for complex coding tasks * Use fast models like `groq/llama-3.3-70b-versatile` for quick completions * Link different profiles to different modes in the **Prompts** tab for optimal cost and performance ## Using Multiple Providers FinOps routes requests to the correct provider based on the model name. Use the `provider/model-name` format to access any configured provider through the single OpenAI-compatible endpoint: ``` anthropic/claude-sonnet-4-5-20250929 openai/gpt-5 gemini/gemini-2.5-pro mistral/mistral-large-latest ``` ### Supported Providers FinOps supports the following providers with the `provider/model-name` format: `openai`, `azure`, `gemini`, `vertex`, `bedrock`, `mistral`, `groq`, `cerebras`, `cohere`, `perplexity`, `xai`, `ollama`, `openrouter`, `huggingface`, `nebius`, `parasail`, `replicate`, `vllm`, `sgl` Roo Code requires **native tool calling** (OpenAI-compatible function calling). Models without tool use support cannot be used with Roo Code. Ensure the model you select supports tool calling. Roo Code connects to FinOps via a single OpenAI-compatible endpoint. FinOps handles routing to the correct provider based on the model name - no per-provider configuration needed. ## MCP Server Integration Roo Code supports MCP (Model Context Protocol). You can connect it to FinOps's MCP server to access all tools configured in FinOps. See [MCP Gateway URL](/mcp/gateway-url) for setup instructions. ## Observability All Roo Code traffic through FinOps is logged. Monitor it at `{AI_GATEWAY_URL}/logs` - filter by provider, model, or search through conversation content to track usage. ## Next Steps * [Provider Configuration](/finops/model-provider) - Configure AI providers in FinOps * [Virtual Keys](/finops/user-keys) - Set up usage limits and access control --- # Zed Editor URL: /finops/cli-agents/zed-editor Integrate Zed editor with FinOps to use any AI provider for code assistance with virtual keys and observability. *** title: "Zed Editor" description: "Integrate Zed editor with FinOps to use any AI provider for code assistance with virtual keys and observability." ------------------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' [Zed](https://zed.dev/) is a high-performance editor with built-in AI assistant support. It can connect to any OpenAI-compatible API, making FinOps a natural fit for universal model access across providers, plus governance features like virtual keys and built-in observability.
Zed editor integration
If your Allowed Headers are already set to `*`, you can skip this note. If not and you face issues integrating FinOps with Zed, try switching to `*` or adding the specific headers required by your client. By default, FinOps whitelists: `Content-Type`, `Authorization`, `X-Requested-With`, `X-Stainless-Timeout`, and `X-Api-Key`. ## Setup ### 1. Configure FinOps Provider Add FinOps to Zed's `language_models.openai_compatible` configuration. This is typically in your Zed settings (JSON) or workspace config. ```json "language_models": { "openai_compatible": { "FinOps": { "api_url": "{AI_GATEWAY_URL}/openai", "available_models": [ { "name": "anthropic/claude-sonnet-4.5", "max_tokens": 200000, "max_output_tokens": 4096, "capabilities": { "tools": true, "images": true, "parallel_tool_calls": true, "prompt_cache_key": false } }, { "name": "openai/gpt-4o", "max_tokens": 128000, "max_output_tokens": 4096, "capabilities": { "tools": true, "images": true, "parallel_tool_calls": true, "prompt_cache_key": false } }, { "name": "openai/gpt-5", "max_tokens": 256000, "max_output_tokens": 4096, "capabilities": { "tools": true, "images": true, "parallel_tool_calls": true, "prompt_cache_key": false } } ] } } } ``` Replace `{AI_GATEWAY_URL}/openai` with your FinOps gateway URL + `/openai`. ### 2. Model Capabilities | Field | Description | | --------------------- | ---------------------------------------------------- | | `tools` | Enable tool/function calling | | `images` | Enable image input (vision) | | `parallel_tool_calls` | Support multiple tool calls in one response | | `prompt_cache_key` | Enable prompt caching (set `false` if not supported) | Use FinOps model IDs in `provider/model` format (e.g. `openai/gpt-5`, `anthropic/claude-sonnet-4.5`). Ensure these models are configured in FinOps. ### 3. Reload Workspace After changing the configuration, reload the workspace so Zed recognizes and reloads the provider list. ## Virtual Keys When FinOps has [virtual key authentication](/finops/user-keys) enabled, add an `api_key` field to the FinOps provider config (check Zed's documentation for the exact field name - it may vary by version): ```json "FinOps": { "api_url": "{AI_GATEWAY_URL}/openai", "api_key": "bf-your-virtual-key-here", "available_models": [...] } ``` This lets you enforce usage limits, budgets, and access control per user or team. For team deployments, create a separate virtual key for each team or environment - each key can have its own rate limits, budgets, and provider access rules configured in the FinOps dashboard. ## Model Selection Zed lets you assign models to different AI features. Use FinOps model IDs in `provider/model` format to access any configured provider: * Use powerful models like `openai/gpt-5` or `anthropic/claude-sonnet-4-5-20250929` for complex code generation and refactoring * Use fast models like `groq/llama-3.3-70b-versatile` for quick completions and inline suggestions ## Using Multiple Providers FinOps routes requests to the correct provider based on the model name. Use the `provider/model-name` format to access any configured provider through the single OpenAI-compatible endpoint: ``` anthropic/claude-sonnet-4-5-20250929 openai/gpt-5 gemini/gemini-2.5-pro mistral/mistral-large-latest ``` ### Supported Providers FinOps supports the following providers with the `provider/model-name` format: `openai`, `azure`, `gemini`, `vertex`, `bedrock`, `mistral`, `groq`, `cerebras`, `cohere`, `perplexity`, `xai`, `ollama`, `openrouter`, `huggingface`, `nebius`, `parasail`, `replicate`, `vllm`, `sgl` Non-native models **must support tool use** for Zed's AI features (code actions, refactoring) to work properly. Models without tool use support will only work for basic chat and completions. Zed connects to FinOps via a single OpenAI-compatible endpoint. FinOps handles routing to the correct provider based on the model name - no per-provider configuration needed. ## Observability All Zed requests through FinOps are logged. Monitor them at `{AI_GATEWAY_URL}/logs` - filter by provider, model, or search through conversation content to track usage. ## Next Steps * [Provider Configuration](/finops/model-provider) - Configure AI providers in FinOps * [Virtual Keys](/finops/user-keys) - Set up usage limits and access control --- # Langchain SDK URL: /finops/integrations/langchain-sdk Use FinOps as a drop-in proxy for Langchain applications with zero code changes. *** title: "Langchain SDK" description: "Use FinOps as a drop-in proxy for Langchain applications with zero code changes." ----------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' Since Langchain already provides multi-provider abstraction and chaining capabilities, FinOps adds enterprise features like governance, semantic caching, MCP tools, observability, etc, on top of your existing setup. **Endpoint:** `/langchain` **Provider Compatibility:** This integration only works for AI providers that both Langchain and FinOps support. If you're using a provider specific to Langchain that FinOps doesn't support (or vice versa), those requests will fail. *** ## Setup ### Python ```python {7} from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage # Configure client to use FinOps llm = ChatOpenAI( model="gpt-4o-mini", openai_api_base="{AI_GATEWAY_URL}/langchain", # Point to FinOps openai_api_key="dummy-key" # Keys managed by FinOps ) response = llm.invoke([HumanMessage(content="Hello!")]) print(response.content) ``` ### JavaScript ```javascript {7} import { ChatOpenAI } from "@langchain/openai"; // Configure client to use FinOps const llm = new ChatOpenAI({ model: "gpt-4o-mini", configuration: { baseURL: "{AI_GATEWAY_URL}/langchain", // Point to FinOps }, openAIApiKey: "dummy-key" // Keys managed by FinOps }); const response = await llm.invoke("Hello!"); console.log(response.content); ``` *** ## Provider/Model Usage Examples Your existing Langchain provider switching works unchanged through FinOps: ### Python ```python from langchain_openai import ChatOpenAI from langchain_anthropic import ChatAnthropic from langchain_google_genai import ChatGoogleGenerativeAI from langchain_core.messages import HumanMessage base_url = "{AI_GATEWAY_URL}/langchain" # OpenAI models via Langchain openai_llm = ChatOpenAI( model="gpt-4o-mini", openai_api_base=base_url ) # Anthropic models via Langchain anthropic_llm = ChatAnthropic( model="claude-3-sonnet-20240229", anthropic_api_url=base_url ) # Google models via Langchain google_llm = ChatGoogleGenerativeAI( model="gemini-1.5-flash", google_api_base=base_url ) # All work the same way openai_response = openai_llm.invoke([HumanMessage(content="Hello GPT!")]) anthropic_response = anthropic_llm.invoke([HumanMessage(content="Hello Claude!")]) google_response = google_llm.invoke([HumanMessage(content="Hello Gemini!")]) ``` ### JavaScript ```javascript import { ChatOpenAI } from "@langchain/openai"; import { ChatAnthropic } from "@langchain/anthropic"; import { ChatGoogleGenerativeAI } from "@langchain/google-genai"; const baseURL = "{AI_GATEWAY_URL}/langchain"; // OpenAI models via Langchain const openaiLlm = new ChatOpenAI({ model: "gpt-4o-mini", configuration: { baseURL } }); // Anthropic models via Langchain const anthropicLlm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", clientOptions: { baseURL } }); // Google models via Langchain const googleLlm = new ChatGoogleGenerativeAI({ model: "gemini-1.5-flash", baseURL }); // All work the same way const openaiResponse = await openaiLlm.invoke("Hello GPT!"); const anthropicResponse = await anthropicLlm.invoke("Hello Claude!"); const googleResponse = await googleLlm.invoke("Hello Gemini!"); ``` *** ## Adding Custom Headers Add FinOps-specific headers for governance and tracking. Different LangChain provider classes support different methods for adding custom headers: ### Python ### ChatOpenAI Use `default_headers` parameter for OpenAI models: ```python from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage llm = ChatOpenAI( model="gpt-4o-mini", openai_api_base="{AI_GATEWAY_URL}/langchain", default_headers={ "x-bf-vk": "your-virtual-key", } ) response = llm.invoke([HumanMessage(content="Hello!")]) print(response.content) ``` ### ChatAnthropic Use `default_headers` parameter for Anthropic models: ```python from langchain_anthropic import ChatAnthropic from langchain_core.messages import HumanMessage llm = ChatAnthropic( model="claude-3-sonnet-20240229", anthropic_api_url="{AI_GATEWAY_URL}/langchain", default_headers={ "x-bf-vk": "your-virtual-key", # Virtual key for governance } ) response = llm.invoke([HumanMessage(content="Hello!")]) print(response.content) ``` ### ChatGoogleGenerativeAI Use `additional_headers` parameter for Google/Gemini models: ```python from langchain_google_genai import ChatGoogleGenerativeAI from langchain_core.messages import HumanMessage llm = ChatGoogleGenerativeAI( model="gemini-2.5-flash", google_api_base="{AI_GATEWAY_URL}/langchain", additional_headers={ "x-bf-vk": "your-virtual-key", # Virtual key for governance } ) response = llm.invoke([HumanMessage(content="Hello!")]) print(response.content) ``` ### ChatBedrockConverse For Bedrock models, there are two approaches: **Method 1: Using the client's event system (after initialization)** ```python from langchain_aws import ChatBedrockConverse from langchain_core.messages import HumanMessage llm = ChatBedrockConverse( model="us.anthropic.claude-haiku-4-5-20251001-v1:0", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/langchain", aws_access_key_id="dummy-access-key", aws_secret_access_key="dummy-secret-key", max_tokens=2000 ) def add_bifrost_headers(request, **kwargs): """Add custom headers to Bedrock requests""" request.headers.add_header("x-bf-vk", "your-virtual-key") # Register header injection for all Bedrock operations llm.client.meta.events.register_first( "before-sign.bedrock-runtime.*", add_bifrost_headers ) response = llm.invoke([HumanMessage(content="Hello!")]) print(response.content) ``` **Method 2: Pre-configuring a boto3 client** ```python from langchain_aws import ChatBedrockConverse from langchain_core.messages import HumanMessage import boto3 # Create and configure boto3 client bedrock_client = boto3.client( service_name="bedrock-runtime", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/langchain", aws_access_key_id="dummy-access-key", aws_secret_access_key="dummy-secret-key" ) def add_bifrost_headers(request, **kwargs): """Add custom headers to Bedrock requests""" request.headers.add_header("x-bf-vk", "your-virtual-key") # Register header injection before creating LLM bedrock_client.meta.events.register_first( "before-sign.bedrock-runtime.*", add_bifrost_headers ) # Pass the configured client to ChatBedrockConverse llm = ChatBedrockConverse( model="us.anthropic.claude-haiku-4-5-20251001-v1:0", client=bedrock_client, max_tokens=2000 ) response = llm.invoke([HumanMessage(content="Hello!")]) print(response.content) ``` ### JavaScript ### ChatOpenAI Use `defaultHeaders` in configuration for OpenAI models: ```javascript import { ChatOpenAI } from "@langchain/openai"; const llm = new ChatOpenAI({ model: "gpt-4o-mini", configuration: { baseURL: "{AI_GATEWAY_URL}/langchain", defaultHeaders: { "x-bf-vk": "your-virtual-key", // Virtual key for governance } } }); const response = await llm.invoke("Hello!"); console.log(response.content); ``` ### ChatAnthropic Use `defaultHeaders` in clientOptions for Anthropic models: ```javascript import { ChatAnthropic } from "@langchain/anthropic"; const llm = new ChatAnthropic({ model: "claude-3-sonnet-20240229", clientOptions: { baseURL: "{AI_GATEWAY_URL}/langchain", defaultHeaders: { "x-bf-vk": "your-virtual-key", // Virtual key for governance } } }); const response = await llm.invoke("Hello!"); console.log(response.content); ``` ### ChatGoogleGenerativeAI Use `additionalHeaders` for Google/Gemini models: ```javascript import { ChatGoogleGenerativeAI } from "@langchain/google-genai"; const llm = new ChatGoogleGenerativeAI({ model: "gemini-2.5-flash", baseURL: "{AI_GATEWAY_URL}/langchain", additionalHeaders: { "x-bf-vk": "your-virtual-key", // Virtual key for governance } }); const response = await llm.invoke("Hello!"); console.log(response.content); ``` *** ## Reasoning/Thinking Models Control extended reasoning capabilities for models that support thinking/reasoning modes. ### Azure OpenAI Models For Azure OpenAI reasoning models, use `ChatOpenAI` with the `reasoning` parameter and Azure-specific headers: ### Python ```python from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage # Azure OpenAI with reasoning control llm = ChatOpenAI( model="azure/gpt-5.1", # Azure deployment name base_url="{AI_GATEWAY_URL}/langchain", api_key="dummy-key", reasoning={ "effort": "high", # "minimal" | "low" | "medium" | "high" "summary": "detailed" # "auto" | "concise" | "detailed" }, default_headers={ "authorization": "Bearer your-azure-api-key", "x-bf-azure-endpoint": "https://your-resource.openai.azure.com" } ) response = llm.invoke([HumanMessage(content="Solve this complex problem...")]) ``` ### JavaScript ```javascript import { ChatOpenAI } from "@langchain/openai"; // Azure OpenAI with reasoning control const llm = new ChatOpenAI({ model: "azure/gpt-5.1", // Azure deployment name configuration: { baseURL: "{AI_GATEWAY_URL}/langchain", defaultHeaders: { "authorization": "Bearer your-azure-api-key", "x-bf-azure-endpoint": "https://your-resource.openai.azure.com" } }, openAIApiKey: "dummy-key", reasoning: { effort: "high", summary: "detailed" } }); const response = await llm.invoke("Solve this complex problem..."); ``` ### OpenAI Models For OpenAI reasoning models, use `ChatOpenAI` with the `reasoning` parameter: ### Python ```python from langchain_openai import ChatOpenAI from langchain_core.messages import HumanMessage # OpenAI with reasoning control llm = ChatOpenAI( model="gpt-5", base_url="{AI_GATEWAY_URL}/langchain", api_key="dummy-key", max_tokens=2000, reasoning={ "effort": "high", "summary": "detailed" } ) response = llm.invoke([HumanMessage(content="Solve this complex problem...")]) ``` ### JavaScript ```javascript import { ChatOpenAI } from "@langchain/openai"; const llm = new ChatOpenAI({ model: "gpt-5", configuration: { baseURL: "{AI_GATEWAY_URL}/langchain" }, openAIApiKey: "dummy-key", reasoning: { effort: "high", summary: "detailed" } }); const response = await llm.invoke("Solve this complex problem..."); ``` ### Bedrock Models (Anthropic & Nova) Both Anthropic Claude and Amazon Nova models support reasoning/thinking capabilities via Bedrock. Use `ChatBedrockConverse` with model-specific configuration formats. ### Python #### Anthropic Claude Models ```python from langchain_aws import ChatBedrockConverse from langchain_core.messages import HumanMessage # Bedrock Claude with reasoning control llm = ChatBedrockConverse( model="us.anthropic.claude-opus-4-5-20251101-v1:0", region_name="dummy-region", endpoint_url="{AI_GATEWAY_URL}/langchain", aws_access_key_id="dummy-access-key", aws_secret_access_key="dummy-secret-key", max_tokens=2000, additional_model_request_fields={ # Anthropic format "reasoning_config": { "type": "enabled", "budget_tokens": 1500, # Control thinking token budget } } ) response = llm.invoke([HumanMessage(content="Reason through this problem...")]) ``` #### Amazon Nova Models ```python from langchain_aws import ChatBedrockConverse from langchain_core.messages import HumanMessage # Bedrock Nova with reasoning control llm = ChatBedrockConverse( model="global.amazon.nova-2-lite-v1:0", region_name="dummy-region", endpoint_url="{AI_GATEWAY_URL}/langchain", aws_access_key_id="dummy-access-key", aws_secret_access_key="dummy-secret-key", max_tokens=2000, additional_model_request_fields={ # Nova format "reasoningConfig": { "type": "enabled", "maxReasoningEffort": "high", # "low" | "medium" | "high" } } ) response = llm.invoke([HumanMessage(content="Reason through this problem...")]) ``` **Model-Specific Configuration:** * **Anthropic Claude models** use `reasoning_config` (snake\_case) with `budget_tokens` to control the token budget for reasoning * **Amazon Nova models** use `reasoningConfig` (camelCase) with `maxReasoningEffort` to control reasoning intensity ("low", "medium", "high") ### Google/Vertex AI Models For Google Gemini 2.5 models (Pro, Flash) and Gemini 3, use `ChatGoogleGenerativeAI` with the `thinking_budget` parameter: ### Python ```python from langchain_google_genai import ChatGoogleGenerativeAI from langchain_core.messages import HumanMessage # Gemini with thinking budget control llm = ChatGoogleGenerativeAI( model="gemini/gemini-2.5-flash", # or "vertex/gemini-2.5-flash" base_url="{AI_GATEWAY_URL}/langchain", api_key="dummy-key", max_tokens=4000, thinking_budget=1024, # 0=disable, -1=dynamic, >0=constrained token budget include_thoughts=True, # Include reasoning in response ) response = llm.invoke([HumanMessage(content="Reason through this problem...")]) ``` **Experimental Module:** `ChatGoogleGenerativeAI` is a recently released module that deprecates `ChatVertexAI`. It may have some issues or breaking changes. If you encounter problems, you can use `ChatAnthropic` with `model="gemini/..."` or `model="vertex/..."` as an alternative, which provides stable access to Gemini and Vertex AI models through FinOps. *** ## Embeddings LangChain's `OpenAIEmbeddings` class can be used to generate embeddings through FinOps: ```python from langchain_openai import OpenAIEmbeddings # Create embeddings instance embeddings = OpenAIEmbeddings( model="text-embedding-3-small", base_url="{AI_GATEWAY_URL}/langchain", api_key="dummy-key" ) # Embed a single query query_embedding = embeddings.embed_query("What is machine learning?") # Embed multiple documents doc_embeddings = embeddings.embed_documents([ "Machine learning is a subset of AI", "Deep learning uses neural networks", "NLP helps computers understand text" ]) ``` **Provider Compatibility Limitation:** LangChain's `OpenAIEmbeddings` class converts text to int array before sending to the API. While OpenAI's API supports both text strings and int arrays as input, other providers like Cohere, Bedrock, and Gemini only accept text strings. **This means `OpenAIEmbeddings` only works reliably with OpenAI embedding models.** Using it with other providers (e.g., `model="cohere/embed-v4.0"`) will fail because those providers cannot process int array inputs. ### Cross-Provider Embeddings For embedding models from other providers (Cohere, Bedrock, Gemini, etc.), you can use `GoogleGenerativeAIEmbeddings` from the `langchain_google_genai` package. This module sends text strings directly and works across multiple providers: ```python from langchain_google_genai import GoogleGenerativeAIEmbeddings # Works with any provider's embedding models embeddings = GoogleGenerativeAIEmbeddings( model="cohere/cohere-embed-v4.0", # or bedrock/..., gemini/..., etc. base_url="{AI_GATEWAY_URL}/langchain", api_key="dummy-key" ) query_embedding = embeddings.embed_query("What is machine learning?") doc_embeddings = embeddings.embed_documents([ "Machine learning is a subset of AI", "Deep learning uses neural networks" ]) ``` *** ## Supported Features The Langchain integration supports all features that are available in both the Langchain SDK and FinOps core functionality. Your existing Langchain chains and workflows work seamlessly with FinOps's enterprise features. 😄 *** ## Next Steps * **[Governance Features](../finops/getting-started)** - Virtual keys and team management * **[Semantic Caching](../features/semantic-caching)** - Intelligent response caching * **[Configuration](../finops/getting-started)** - Provider setup and API key management --- # LiteLLM SDK URL: /finops/integrations/litellm-sdk Use FinOps as a drop-in proxy for LiteLLM applications with zero code changes. *** title: "LiteLLM SDK" description: "Use FinOps as a drop-in proxy for LiteLLM applications with zero code changes." --------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' Since LiteLLM already provides multi-provider abstraction, FinOps adds enterprise features like governance, semantic caching, MCP tools, observability, etc, on top of your existing setup. **Endpoint:** `/litellm` **Provider Compatibility:** This integration only works for AI providers that both LiteLLM and FinOps support. If you're using a provider specific to LiteLLM that FinOps doesn't support (or vice versa), those requests will fail. *** ## Setup ### Python ```python {7} from litellm import completion # Configure client to use FinOps response = completion( model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}], base_url="{AI_GATEWAY_URL}/litellm" # Point to FinOps ) print(response.choices[0].message.content) ``` *** ## Provider/Model Usage Examples Your existing LiteLLM provider switching works unchanged through FinOps: ### Python ```python {4} from litellm import completion # All your existing LiteLLM patterns work the same base_url = "{AI_GATEWAY_URL}/litellm" # OpenAI models openai_response = completion( model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello GPT!"}], base_url=base_url ) # Anthropic models anthropic_response = completion( model="claude-3-sonnet-20240229", messages=[{"role": "user", "content": "Hello Claude!"}], base_url=base_url ) # Google models google_response = completion( model="gemini/gemini-1.5-flash", messages=[{"role": "user", "content": "Hello Gemini!"}], base_url=base_url ) # Azure models azure_response = completion( model="azure/gpt-4o", messages=[{"role": "user", "content": "Hello Azure!"}], base_url=base_url ) ``` *** ## Adding Custom Headers Add FinOps-specific headers for governance and tracking: ### Python ```python from litellm import completion # Add custom headers for FinOps features response = completion( model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}], base_url="{AI_GATEWAY_URL}/litellm", extra_headers={ "x-bf-vk": "your-virtual-key", # Virtual key for governance } ) print(response.choices[0].message.content) ``` *** ## Supported Features The LiteLLM integration supports all features that are available in both the LiteLLM SDK and FinOps core functionality. Your existing LiteLLM code works seamlessly with FinOps's enterprise features. 😄 *** ## Next Steps * **[Governance Features](../finops/getting-started)** - Virtual keys and team management * **[Semantic Caching](../features/semantic-caching)** - Intelligent response caching * **[Configuration](../finops/getting-started)** - Provider setup and API key management --- # Passthrough URL: /finops/integrations/passthrough Forward provider-native requests through FinOps with full core pipeline processing, including logs and observability. *** title: "Passthrough" description: "Forward provider-native requests through FinOps with full core pipeline processing, including logs and observability." ------------------------------------------------------------------------------------------------------------------------------------ ## Overview Passthrough integrations let you call provider-native API paths and payloads through FinOps without route-level request/response conversion. When you use passthrough endpoints, the request still flows through FinOps core logic. You keep FinOps features such as logging and observability while sending provider-native paths and bodies. *** ## Endpoints * `/openai_passthrough` Default provider: `openai` * `/anthropic_passthrough` Default provider: `anthropic` * `/azure_passthrough` Default provider: `azure` * `/genai_passthrough` Default provider: `gemini` (with automatic Vertex detection for clients configured to use Vertex) *** ## How It Works 1. Send your request to a passthrough endpoint (OpenAI, Anthropic, Azure, or GenAI passthrough). 2. The integration strips the passthrough prefix and forwards the remaining provider-native path/body. 3. FinOps handles provider execution through core inference and plugin pipelines. 4. Response status, headers, and body are returned as passthrough output (for both stream and non-stream requests). *** ## Provider Selection Rules ### OpenAI Passthrough * Uses `openai` as the default provider. ### Anthropic Passthrough * Uses `anthropic` as the default provider. ### Azure Passthrough * Uses `azure` as the default provider. * Requires an Azure key with `endpoint` configured. Query parameters (including any `api-version`) are forwarded as-is from the caller — FinOps does not inject any version. ### GenAI Passthrough * Uses `gemini` by default. * Automatically switches to `vertex` when Vertex patterns are detected, such as: * URL path containing `/projects/{PROJECT_ID}/locations/{LOCATION}/` * Request body `model` containing a Vertex resource path * OAuth token pattern typically used for Vertex (`Bearer ya29...`) *** ## Usage Examples ### OpenAI Passthrough ### Python SDK ```python import openai client = openai.OpenAI( base_url="{AI_GATEWAY_URL}/openai_passthrough/v1", api_key="dummy-key" ) response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": "hello from passthrough"}] ) print(response.choices[0].message.content) ``` ### cURL ```bash curl -X POST "{AI_GATEWAY_URL}/openai_passthrough/v1/chat/completions" \ -H "content-type: application/json" \ -H "authorization: Bearer sk-your-openai-key" \ -d '{ "model": "gpt-4o-mini", "messages": [{"role":"user","content":"hello from passthrough"}] }' ``` ### Anthropic Passthrough ### Python SDK ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic_passthrough", api_key="dummy-key" ) response = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=1024, messages=[{"role": "user", "content": "hello from passthrough"}] ) print(response.content[0].text) ``` ### cURL ```bash curl -X POST "{AI_GATEWAY_URL}/anthropic_passthrough/v1/messages" \ -H "content-type: application/json" \ -H "x-api-key: your-anthropic-key" \ -H "anthropic-version: 2023-06-01" \ -d '{ "model": "claude-sonnet-4-20250514", "max_tokens": 1024, "messages": [{"role":"user","content":"hello from passthrough"}] }' ``` ### Azure Passthrough ### Azure OpenAI SDK ```python from openai import AzureOpenAI client = AzureOpenAI( azure_endpoint="{AI_GATEWAY_URL}/azure_passthrough", api_key="dummy-key", api_version="2024-10-21", # passed through as-is in the query string ) response = client.chat.completions.create( model="gpt-4o", # your Azure deployment name messages=[{"role": "user", "content": "hello from azure passthrough"}] ) print(response.choices[0].message.content) ``` ### OpenAI SDK ```python from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/azure_passthrough/openai/v1/", api_key="dummy-key", ) response = client.responses.create( model="gpt-4.1", # your Azure deployment name input="hello from azure passthrough", ) print(response.output_text) ``` ### Anthropic SDK (Anthropic on Azure) ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/azure_passthrough", api_key="dummy-key", ) response = client.messages.create( model="claude-sonnet-4-20250514", max_tokens=1024, messages=[{"role": "user", "content": "hello from azure passthrough"}] ) print(response.content[0].text) ``` ### cURL ```bash curl -X POST "{AI_GATEWAY_URL}/azure_passthrough/openai/deployments/gpt-4o/chat/completions" \ -H "content-type: application/json" \ -d '{ "messages": [{"role": "user", "content": "hello from azure passthrough"}] }' ``` ### GenAI Passthrough (Gemini) ### Python SDK ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="dummy-key", http_options=HttpOptions(base_url="{AI_GATEWAY_URL}/genai_passthrough") ) response = client.models.generate_content( model="gemini-2.5-flash", contents="hello from passthrough" ) print(response.text) ``` ### cURL ```bash curl -X POST "{AI_GATEWAY_URL}/genai_passthrough/v1beta/models/gemini-2.5-flash:generateContent" \ -H "content-type: application/json" \ -H "x-goog-api-key: your-gemini-key" \ -d '{ "contents":[{"parts":[{"text":"hello from passthrough"}]}] }' ``` ### GenAI Passthrough (Vertex-style request) ### Python SDK ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( vertexai=True, api_key="dummy-key", http_options=HttpOptions(base_url="{AI_GATEWAY_URL}/genai_passthrough") ) response = client.models.generate_content( model="gemini-2.5-flash", contents="hello from vertex passthrough" ) print(response.text) ``` ### cURL ```bash curl -X POST "{AI_GATEWAY_URL}/genai_passthrough/v1/projects/my-project/locations/us-central1/publishers/google/models/gemini-2.5-flash:generateContent" \ -H "content-type: application/json" \ -H "authorization: Bearer ya29.your-vertex-token" \ -d '{ "contents":[{"parts":[{"text":"hello from vertex passthrough"}]}] }' ``` *** ## Notes * Use passthrough when you need a provider endpoint that is not directly supported by FinOps integration routes yet. * For Azure passthrough, auth headers (`api-key`, `x-api-key`, OAuth token) are always sourced from the FinOps key config and never forwarded from the client request. --- # Pydantic AI SDK URL: /finops/integrations/pydanticai-sdk Use FinOps as a drop-in proxy for Pydantic AI agents with zero code changes. *** title: "Pydantic AI SDK" description: "Use FinOps as a drop-in proxy for Pydantic AI agents with zero code changes." ------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' Pydantic AI is a Python agent framework that brings FastAPI-like ergonomics to GenAI development. Since Pydantic AI uses standard provider SDKs under the hood, FinOps adds enterprise features like governance, semantic caching, MCP tools, observability, etc, on top of your existing agent setup. **Endpoint:** `/pydanticai` **Provider Compatibility:** This integration only works for AI providers that both Pydantic AI and FinOps support. Currently supported: OpenAI, Anthropic, and Google Gemini. *** ## Setup ### Python ```python {7-8} from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIChatModel from pydantic_ai.providers.openai import OpenAIProvider # Configure provider to use FinOps provider = OpenAIProvider( base_url="{AI_GATEWAY_URL}/pydanticai/v1", # Point to FinOps api_key="dummy-key" # Keys managed by FinOps, Or add virtual key ) model = OpenAIChatModel("gpt-4o-mini", provider=provider) # Create agent with FinOps-routed model agent = Agent(model, instructions="Be concise and helpful.") result = agent.run_sync("Hello! How are you?") print(result.output) ``` *** ## Provider/Model Usage Examples Your existing Pydantic AI provider switching works unchanged through FinOps: ### Python ```python {7,10,14} from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIChatModel from pydantic_ai.models.anthropic import AnthropicModel from pydantic_ai.models.google import GoogleModel from pydantic_ai.providers.openai import OpenAIProvider from pydantic_ai.providers.anthropic import AnthropicProvider from pydantic_ai.providers.google import GoogleProvider base_url = "{AI_GATEWAY_URL}/pydanticai" # OpenAI models via Pydantic AI openai_provider = OpenAIProvider(base_url=f"{base_url}/v1") openai_model = OpenAIChatModel("gpt-4o-mini", provider=openai_provider) openai_agent = Agent(openai_model) # Anthropic models via Pydantic AI # Note: Anthropic SDK adds /v1 internally, so we don't append it here anthropic_provider = AnthropicProvider(base_url=base_url) anthropic_model = AnthropicModel("claude-3-haiku-20240307", provider=anthropic_provider) anthropic_agent = Agent(anthropic_model) # Google Gemini models via Pydantic AI google_provider = GoogleProvider(base_url=base_url, api_key="dummy-key") google_model = GoogleModel("gemini-2.0-flash", provider=google_provider) google_agent = Agent(google_model) # All work the same way openai_result = openai_agent.run_sync("Hello GPT!") anthropic_result = anthropic_agent.run_sync("Hello Claude!") gemini_result = google_agent.run_sync("Hello Gemini!") print(openai_result.output) print(anthropic_result.output) print(gemini_result.output) ``` *** ## Tool Calling Pydantic AI's powerful tool system works seamlessly through FinOps: ### Python ```python {7} from pydantic_ai import Agent, RunContext, Tool from pydantic_ai.models.openai import OpenAIChatModel from pydantic_ai.providers.openai import OpenAIProvider from dataclasses import dataclass # Configure FinOps provider = OpenAIProvider(base_url="{AI_GATEWAY_URL}/pydanticai/v1") model = OpenAIChatModel("gpt-4o-mini", provider=provider) # Define tools as functions def get_weather(location: str) -> str: """Get the current weather for a location.""" return f"The weather in {location} is 72°F and sunny." def calculate(expression: str) -> str: """Perform a mathematical calculation.""" result = eval(expression) # Use safe evaluation in production return f"The result is {result}" # Create agent with tools agent = Agent( model, tools=[get_weather, calculate], instructions="You can check weather and do calculations." ) result = agent.run_sync("What's the weather in Boston?") print(result.output) ``` *** ## Tools with Dependency Injection Use `RunContext` to pass dependencies to your tools: ### Python ```python {12} from pydantic_ai import Agent, RunContext, Tool from pydantic_ai.models.openai import OpenAIChatModel from pydantic_ai.providers.openai import OpenAIProvider from dataclasses import dataclass @dataclass class UserContext: user_id: int user_name: str # Configure FinOps provider = OpenAIProvider(base_url="{AI_GATEWAY_URL}/pydanticai/v1") model = OpenAIChatModel("gpt-4o-mini", provider=provider) def get_user_info(ctx: RunContext[UserContext]) -> str: """Get information about the current user.""" return f"User: {ctx.deps.user_name} (ID: {ctx.deps.user_id})" agent = Agent( model, deps_type=UserContext, tools=[Tool(get_user_info, takes_ctx=True)], instructions="You can look up user information." ) # Pass dependencies at runtime deps = UserContext(user_id=123, user_name="Alice") result = agent.run_sync("What is my user information?", deps=deps) print(result.output) ``` *** ## Structured Output Define response types using Pydantic models: ### Python ```python {13} from pydantic import BaseModel, Field from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIChatModel from pydantic_ai.providers.openai import OpenAIProvider # Define structured output type class CityInfo(BaseModel): city: str = Field(description="Name of the city") country: str = Field(description="Country where the city is located") population: int = Field(description="Approximate population") # Configure FinOps provider = OpenAIProvider(base_url="{AI_GATEWAY_URL}/pydanticai/v1") model = OpenAIChatModel("gpt-4o-mini", provider=provider) # Agent with typed output agent = Agent( model, output_type=CityInfo, instructions="Extract city information from user queries." ) result = agent.run_sync("Tell me about Tokyo, Japan") # result.output is typed as CityInfo print(f"City: {result.output.city}") print(f"Country: {result.output.country}") print(f"Population: {result.output.population}") ``` *** ## Streaming Responses Stream responses in real-time for better UX: ### Python ```python {7} import asyncio from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIChatModel from pydantic_ai.providers.openai import OpenAIProvider # Configure FinOps provider = OpenAIProvider(base_url="{AI_GATEWAY_URL}/pydanticai/v1") model = OpenAIChatModel("gpt-4o-mini", provider=provider) agent = Agent(model, instructions="Tell engaging stories.") async def stream_story: async with agent.run_stream("Tell me a short story about a robot.") as response: async for chunk in response.stream_text: print(chunk, end="", flush=True) print # Newline at end asyncio.run(stream_story) ``` *** ## Adding Custom Headers Add FinOps-specific headers for governance and tracking: ### Python ```python {15} from httpx import AsyncClient from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIChatModel from pydantic_ai.providers.openai import OpenAIProvider # Create HTTP client with custom headers http_client = AsyncClient( headers={ "x-bf-vk": "your-virtual-key", # Virtual key for governance } ) # Configure provider with custom client provider = OpenAIProvider( base_url="{AI_GATEWAY_URL}/pydanticai/v1", http_client=http_client ) model = OpenAIChatModel("gpt-4o-mini", provider=provider) agent = Agent(model) result = agent.run_sync("Hello!") print(result.output) ``` *** ## Multi-turn Conversations Maintain conversation history across multiple turns: ### Python ```python {6} from pydantic_ai import Agent from pydantic_ai.models.openai import OpenAIChatModel from pydantic_ai.providers.openai import OpenAIProvider # Configure FinOps provider = OpenAIProvider(base_url="{AI_GATEWAY_URL}/pydanticai/v1") model = OpenAIChatModel("gpt-4o-mini", provider=provider) agent = Agent(model, instructions="Remember context from previous messages.") # First turn result1 = agent.run_sync("My name is Alice and I live in Paris.") # Second turn - pass message history to maintain context result2 = agent.run_sync( "What is my name and where do I live?", message_history=result1.all_messages ) print(result2.output) # Should mention Alice and Paris ``` *** ## Supported Features The Pydantic AI integration supports all features available in both the Pydantic AI SDK and FinOps core functionality: | Feature | Supported | | ------------------------ | --------- | | Chat Completions | ✅ | | Tool/Function Calling | ✅ | | Structured Output | ✅ | | Streaming | ✅ | | Multi-turn Conversations | ✅ | | Dependency Injection | ✅ | | OpenAI Models | ✅ | | Anthropic Models | ✅ | | Google Gemini Models | ✅ | | Embeddings | ✅ | | Speech/TTS | ✅ | | Transcription | ✅ | Your existing Pydantic AI agents work seamlessly with FinOps's enterprise features. 😄 *** ## Next Steps * **[Governance Features](../finops/getting-started)** - Virtual keys and team management * **[Semantic Caching](../features/semantic-caching)** - Intelligent response caching * **[Configuration](../finops/getting-started)** - Provider setup and API key management --- # What is an integration? URL: /finops/integrations/what-is-an-integration Protocol adapters that translate between FinOps's unified API and provider-specific API formats like OpenAI, Anthropic, and Google GenAI. *** title: "What is an integration?" description: "Protocol adapters that translate between FinOps's unified API and provider-specific API formats like OpenAI, Anthropic, and Google GenAI." -------------------------------------------------------------------------------------------------------------------------------------------------------- ## Overview An integration is a protocol adapter that translates between FinOps's unified API and provider-specific API formats. Each integration handles request transformation, response normalization, and error mapping between the external API contract and FinOps's internal processing pipeline. Integrations enable you to utilize FinOps's features like governance, MCP tools, load balancing, semantic caching, multi-provider support, and more, all while preserving your existing SDK-based architecture. FinOps handles all the overhead of structure conversion, requiring only a single URL change to switch from direct provider APIs to FinOps's gateway. FinOps converts the request/response format of the provider API to the FinOps API format based on the integration used, so you don't have to. *** ## Quick Migration ### **Before (Direct Provider)** ```python import openai client = openai.OpenAI( api_key="your-openai-key" ) ``` ### **After (FinOps)** ```python {4} import openai client = openai.OpenAI( base_url="{AI_GATEWAY_URL}/openai", # Point to FinOps api_key="dummy-key" # Keys are handled in FinOps now ) ``` **That's it!** Your application now benefits from FinOps's features with no other changes. *** ## Supported Integrations 1. [OpenAI](/finops/integrations/openai-sdk/index) 2. [Anthropic](/finops/integrations/anthropic-sdk) 3. [Google GenAI](/finops/integrations/genai-sdk) 4. [LiteLLM](/finops/integrations/litellm-sdk) 5. [Langchain](/finops/integrations/langchain-sdk) 6. [AWS Bedrock](/finops/integrations/bedrock-sdk) *** ## Provider-Prefixed Models Use multiple providers seamlessly by prefixing model names with the provider: ### OpenAI ```python import openai # Single client, multiple providers client = openai.OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="dummy" # API keys configured in FinOps ) # OpenAI models response1 = client.chat.completions.create( model="gpt-4o-mini", # (default OpenAI since it's OpenAI's SDK) messages=[{"role": "user", "content": "Hello!"}] ) ``` ### Anthropic ```python import openai # Anthropic models using OpenAI SDK format response2 = client.chat.completions.create( model="anthropic/claude-3-sonnet-20240229", messages=[{"role": "user", "content": "Hello!"}] ) ``` ### Azure ```python import openai # Azure models response4 = client.chat.completions.create( model="azure/gpt-4o", messages=[{"role": "user", "content": "Hello!"}] ) ``` ### Vertex ```python import openai # Google Vertex models response3 = client.chat.completions.create( model="vertex/gemini-pro", messages=[{"role": "user", "content": "Hello!"}] ) ``` ### Ollama ```python import openai # Local Ollama models response5 = client.chat.completions.create( model="ollama/llama3.1:8b", messages=[{"role": "user", "content": "Hello!"}] ) ``` *** ## Direct API Usage For custom HTTP clients or when you have existing provider-specific setup and want to use FinOps gateway without restructuring your codebase: ```python {5,18,31,} import requests # Fully OpenAI compatible endpoint response = requests.post( "{AI_GATEWAY_URL}/openai/v1/chat/completions", headers={ "Authorization": f"Bearer {openai_key}", "Content-Type": "application/json" }, json={ "model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Hello!"}] } ) # Fully Anthropic compatible endpoint response = requests.post( "{AI_GATEWAY_URL}/anthropic/v1/messages", headers={ "Content-Type": "application/json", }, json={ "model": "claude-3-sonnet-20240229", "max_tokens": 1000, "messages": [{"role": "user", "content": "Hello!"}] } ) # Fully Google GenAI compatible endpoint response = requests.post( "{AI_GATEWAY_URL}/genai/v1beta/models/gemini-1.5-flash/generateContent", headers={ "Content-Type": "application/json", }, json={ "contents": [ {"parts": [{"text": "Hello!"}]} ], "generation_config": { "max_output_tokens": 1000, "temperature": 1 } } ) ``` *** ## Listing Models All integrations support listing available models through their respective list models endpoints (e.g., `/openai/v1/models`, `/anthropic/v1/models`). By default, list models requests return models from **all configured providers** in FinOps. ### Filtering by Provider You can control which provider's models to list using the `x-bf-list-models-provider` header: ### Python ```python import openai client = openai.OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="dummy-key" ) # List models from all providers (default behavior) all_models = client.models.list # List models from a specific provider only openai_models = client.models.list( extra_headers={ "x-bf-list-models-provider": "openai" } ) anthropic_models = client.models.list( extra_headers={ "x-bf-list-models-provider": "anthropic" } ) ``` ### JavaScript ```javascript import OpenAI from "openai"; const openai = new OpenAI({ baseURL: "{AI_GATEWAY_URL}/openai", apiKey: "dummy-key", }); // List models from all providers (default behavior) const allModels = await openai.models.list; // List models from a specific provider only const openaiModels = await openai.models.list({ headers: { "x-bf-list-models-provider": "openai", }, }); const anthropicModels = await openai.models.list({ headers: { "x-bf-list-models-provider": "anthropic", }, }); ``` ### cURL ```bash # List models from all providers (default) curl {AI_GATEWAY_URL}/openai/v1/models # List models from specific provider curl {AI_GATEWAY_URL}/openai/v1/models \ -H "x-bf-list-models-provider: openai" # Explicitly request all providers curl {AI_GATEWAY_URL}/openai/v1/models \ -H "x-bf-list-models-provider: all" ``` ### Header Behavior | Header Value | Behavior | | ------------------ | ---------------------------------------------- | | Not set (default) | Lists models from **all configured providers** | | `all` | Lists models from **all configured providers** | | `openai` | Lists models from **OpenAI provider only** | | `anthropic` | Lists models from **Anthropic provider only** | | `vertex` | Lists models from **Vertex AI provider only** | | Any valid provider | Lists models from that specific provider | ### Response Fields When listing models from all providers, some provider-specific fields may be empty or contain default values if the information is not available from all providers. This is normal behavior as different providers expose different model metadata. *** ## Migration Strategies ### **Gradual Migration** 1. **Start with development** - Test FinOps in dev environment 2. **Canary deployment** - Route 5% of traffic through FinOps 3. **Feature-by-feature** - Migrate specific endpoints gradually 4. **Full migration** - Switch all traffic to FinOps ### **Blue-Green Migration** ```python import os import random # Route traffic based on feature flag def get_base_url(provider: str) -> str: if os.getenv("USE_BIFROST", "false") == "true": return f"http://finops:8080/{provider}" else: return f"https://api.{provider}.com" # Gradual rollout def should_use_bifrost -> bool: rollout_percentage = int(os.getenv("BIFROST_ROLLOUT", "0")) return random.randint(1, 100) <= rollout_percentage ``` ### **Feature Flag Integration** ```python # Using feature flags for safe migration import openai from feature_flags import get_flag def create_client: if get_flag("use_bifrost_openai"): base_url = "http://finops:8080/openai" else: base_url = "https://api.openai.com" return openai.OpenAI( base_url=base_url, api_key=os.getenv("OPENAI_API_KEY") ) ``` *** ## Next Steps * **[HTTP Transport Overview](../finops/getting-started)** - Main HTTP transport guide * **[Endpoints](/finops-api)** - Complete API reference * **[Configuration](../finops/model-provider)** - Provider setup and config --- # Model Provider URL: /finops/model-provider Register AI providers, connect API keys, and manage models in FinOps Config. *** title: "Model Provider" description: "Register AI providers, connect API keys, and manage models in FinOps Config." ------------------------------------------------------------------------------------------- Model providers are the upstream AI services your gateway routes to — OpenAI, Anthropic, Google, Azure, custom endpoints, and more. Open **Finops Config → Model Provider** to browse configured providers, add new ones, and manage keys. Select a provider from the list to view its configured keys on the right.
Monetize360 Model Provider page with provider list and configured keys for a keyless provider
## Provider list | Column | Description | | ---------------------------------- | --------------------------------------------------------- | | **Name** | Unique identifier for this provider in your tenant | | **Status** | Whether the provider connection is healthy | | **Description** | Optional notes for administrators | | **Send Back Raw Request/Response** | Whether raw payloads are returned to clients (usually No) | | **Store Raw Request** | Whether full request bodies are persisted in logs | Click a provider name to open its detail tabs: **Keys**, **Model**, **Budget**, and **Rate Limit**. ## Create a provider Click **+ Create** on the list page.
ConfigProvider create form
### Basic fields | Field | Description | | ---------------------- | ----------------------------------------------------- | | **Name** | Display name for this provider configuration | | **Provider Type** | Standard provider (OpenAI, Anthropic, etc.) or custom | | **Base URL** | API endpoint — use the vendor URL or your proxy | | **Base Provider Type** | Underlying protocol when using a custom wrapper | ### Feature toggles | Toggle | Purpose | | -------------------- | ----------------------------------------------- | | **Chat Completion** | Enable chat/inference requests | | **Keyless Provider** | Provider does not require an API key | | **List Models** | Allow dynamic model discovery from the provider | Click **Edit Provider Config** on a provider to open advanced settings. Use the **API Structure** tab to enable or disable specific request types (chat completion, embeddings, image generation, rerank, OCR, and more) for that provider.
Provider configuration API Structure tab with Allowed Requests toggles
Click **Submit** to save, then add [API keys](/finops/model-provider/keys) and [model pricing](/finops/model-provider/models). ## Detail tabs | Tab | Documentation | | ----- | ------------------------------------------------ | | Keys | [Provider Keys](/finops/model-provider/keys) | | Model | [Provider Models](/finops/model-provider/models) | --- # Provider Keys URL: /finops/model-provider/keys Store and rotate API keys for model providers in FinOps Config. *** title: "Provider Keys" description: "Store and rotate API keys for model providers in FinOps Config." ------------------------------------------------------------------------------ Provider keys are the credentials the gateway uses when calling upstream AI APIs. They are stored encrypted in your tenant and never exposed to end-user applications. ## Access Navigate to **Model Provider →** select a provider **→ Keys**. ## Add a key 1. Click **+ Create**. 2. Enter a **Name** to identify this key (e.g. `production-openai-east`). 3. Paste the provider **API Key** or upload credentials as required by the provider type. 4. Click **Submit**. The gateway load-balances across multiple keys when more than one is configured for the same provider. ## Best practices * Use separate keys per environment (production vs. staging) by creating multiple provider configurations or named keys. * Rotate keys in Monetize360 when your vendor rotates them — update the key record and save; no application redeploy is required. * Applications never receive provider keys directly. They use [User Keys (virtual keys)](/finops/user-keys) instead. ## Related * [Model Provider](/finops/model-provider) — provider setup * [Connect Your Apps](/finops/connect-your-apps) — how applications authenticate --- # Provider Models URL: /finops/model-provider/models Define per-model input and output token pricing for cost tracking and budgets. *** title: "Provider Models" description: "Define per-model input and output token pricing for cost tracking and budgets." --------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' Each model under a provider needs pricing so FinOps can calculate spend, enforce budgets, and populate dashboard charts. Navigate to **Model Provider →** select a provider **→ Model**.
Provider model pricing table
## Model table | Column | Description | | ------------------------- | --------------------------------------------------------------------------- | | **Name** | Model identifier as sent in API requests (e.g. `gpt-4o-mini`, `qwen-turbo`) | | **Currency** | Currency for cost fields | | **Provider** | Parent provider name | | **Input Cost Per Token** | Price per input token | | **Output Cost Per Token** | Price per output token | ## Create a model 1. Click **+ Create**. 2. Enter the **Name** exactly as your application or provider expects it. 3. Set **Input Cost Per Token** and **Output Cost Per Token** for accurate [Dashboard](/finops/dashboard) and [Telemetry](/finops/telemetry) reporting. 4. Select the **Currency**. 5. Click **Submit**. If pricing is left at zero, requests still work but cost metrics will show $0. Set realistic rates for FinOps visibility. ## Related * [Organization Models](/finops/organization/models) — restrict which of these models each org may call * [Routing Rules](/finops/routing-rules) — redirect traffic between models on the same or different providers --- # Organization Budget URL: /finops/organization/budget Set spending limits and reset periods for organizations in FinOps Config. *** title: "Organization Budget" description: "Set spending limits and reset periods for organizations in FinOps Config." ---------------------------------------------------------------------------------------- Organization budgets cap AI spend for a specific entity in your hierarchy. When usage exceeds the limit, the gateway blocks further requests until the budget resets. ## Budget list Navigate to **Organization →** select an org **→ Budget**.
Organization budget table with max limit and current usage
| Column | Description | | ------------------------- | ------------------------------------------ | | **Max Limit** | Maximum spend allowed in the budget period | | **Last Reset** | When the current budget window started | | **Current Usage** | Spend consumed so far in this period | | **Governed Organization** | The organization this budget applies to | | **Currency** | Currency for the limit and usage amounts | ## Create a budget Click **+ Create** to open the **GovernanceBudget Save Flow**.
GovernanceBudget create form with max limit and reset duration
| Field | Description | | ------------------ | ---------------------------------------------------------------------------------------------------------------------------------- | | **Max Limit** | Dollar (or tenant currency) cap for the period — e.g. `100000` | | **Reset Duration** | How often the budget resets — enter a number and choose the unit (Hours, Days, Weeks, Months, Years). Examples: `1` Day, `1` Month | Click **Submit** to activate the budget. Usage updates automatically as applications consume tokens through the gateway. ## Tips * Set budgets at the **department** level for team accountability; roll up visibility on the [Dashboard](/finops/dashboard). * Use the [Simulator](/finops/simulator) to verify budget blocks before production traffic hits the limit. * Budgets can also be attached to virtual keys and model providers — see [User Keys](/finops/user-keys) and [Model Provider](/finops/model-provider). --- # Organization URL: /finops/organization Build your organizational hierarchy for FinOps governance — regions, legal entities, and departments. *** title: "Organization" description: "Build your organizational hierarchy for FinOps governance — regions, legal entities, and departments." -------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' Organizations define **who owns AI spend and policy**. Every budget, rate limit, model allowlist, and virtual key can be scoped to a node in this hierarchy.
Organization list with hierarchy and sub-types
## Organization types | Sub Type | Purpose | Example | | ---------------- | ----------------------- | ------------------------------------ | | **Region** | Geographic grouping | APAC, EMEA, North America | | **Legal Entity** | Corporate or tax entity | India Entity, UK Entity, US entity | | **Department** | Functional team | Engineering, Finance, Support, Legal | ## Hierarchy Organizations form a tree. A department typically rolls up through a legal entity and region to your tenant root (e.g. `tokensystem`). **Hierarchy:** tokensystem tenant → Region e.g. APAC → Legal Entity e.g. India Entity → Department e.g. Engineering ## Using the page 1. Open **Finops Config → Organization**. 2. Use **Enter Organization Name** to search. 3. Click an organization name (blue link) to open its detail view — **Budget**, **Rate Limit**, and **Model** tabs. 4. Use **+ Create** to add a new organization. Set **Parent Organization** and **Sub Type** so the hierarchy stays consistent. ## Detail views | Tab | Documentation | | ---------- | ------------------------------------------------------------ | | Budget | [Organization Budget](/finops/organization/budget) | | Rate Limit | [Organization Rate Limits](/finops/organization/rate-limits) | | Model | [Organization Models](/finops/organization/models) | Create your hierarchy before issuing virtual keys. Virtual keys inherit governance scope from their assigned organization. --- # Organization Models URL: /finops/organization/models Control which AI models an organization may use through allowed and blacklisted model rules. *** title: "Organization Models" description: "Control which AI models an organization may use through allowed and blacklisted model rules." ----------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' Organization model rules restrict which provider models are available to users and applications scoped to that organization. ## Model allowlist Navigate to **Organization →** select an org **→ Model**.
Organization model allowlist table
| Column | Description | | -------------------------- | ----------------------------------------------------- | | **Provider Name** | The configured model provider (e.g. `fakellm-openai`) | | **Allowed Model Name** | Models explicitly permitted for this organization | | **Blacklisted Model Name** | Models explicitly denied (optional) | | **Virtual Key Name** | When set, the rule applies to a specific virtual key | | **Org Name** | The governed organization | ## Create a model rule Click **+ Create** to open **GovernanceVirtualKeyProviderConfig Save Flow**.
Create organization model allowlist form
### Model section | Field | Description | | --------------------- | ----------------------------------------------------------- | | **Provider** | Select the model provider | | **Allowed Model** | Choose the model this org may use | | **Blacklisted Model** | Optionally block a specific model even if otherwise allowed | ### Scope section | Field | Description | | ------------------ | ---------------------------------------------------------------------------- | | **Virtual Key Id** | Link the rule to a specific virtual key, or leave scoped to the organization | Click **Submit** to save. Allowed-model rules work together with [User Keys](/finops/user-keys). A request must pass both organization and virtual-key model policies. ## Related * [Model Provider → Models](/finops/model-provider/models) — define which models exist and their pricing * [Simulator](/finops/simulator) — test that blocked models return clear errors --- # Organization Rate Limits URL: /finops/organization/rate-limits Throttle request and token volume per organization with configurable reset windows. *** title: "Organization Rate Limits" description: "Throttle request and token volume per organization with configurable reset windows." -------------------------------------------------------------------------------------------------- Organization rate limits protect the gateway and downstream providers from burst traffic originating from a specific team or entity. ## Access Navigate to **Organization →** select an org **→ Rate Limit**. ## Create a rate limit Click **+ Create** and configure: | Field | Description | | -------------------------- | ------------------------------------------------- | | **Token Max Limit** | Maximum tokens allowed in the reset window | | **Token Reset Duration** | How often token usage resets (e.g. 1 hour, 1 day) | | **Request Max Limit** | Maximum API requests allowed in the reset window | | **Request Reset Duration** | How often request count resets | | **Governed Organization** | The organization this limit applies to | ## Monitoring After saving, open the [Simulator](/finops/simulator) and select a virtual key scoped to this organization. The **Limits** row on each governance hierarchy card shows request and token usage bars updating in real time. When a limit is exceeded, the simulator displays a **Rate Limited**, **Token Limited**, or **Request Limited** alert on the blocked response. ## Related * [Rate Limit](/finops/rate-limit) — tenant-wide rate limit policies * [User Keys](/finops/user-keys) — virtual-key-level limits --- # Configuring Huddle Agents URL: /mbrix/agents/configuring-huddle-agents Learn how to configure and use HuddleMaster agents to orchestrate multiple agents in collaborative conversations *** title: Configuring Huddle Agents description: Learn how to configure and use HuddleMaster agents to orchestrate multiple agents in collaborative conversations ----------------------------------------------------------------------------------------------------------------------------- # Configuring Huddle Agents ## HuddleMaster Agent
Configuring Huddle Agents
You can build any agent and make it as huddleMaster (enable checkbox). HuddleMaster agent has capability (internally powered) to be able to invoke other agents involved in the huddle and collect responses from them if needed. It understands the user question, and determines which agent/agents in the huddle is/are suitable for this query, and fires sub-questions to them. Each sub agent executes to answer the query, and responds with answer. If the collected responses from subagents are satisfying, huddlemaster responds back with overall summary, if not, it goes into another loop, to clarify few more questions with the agents available, till its satisfied. Once satisfied, huddleMaster collates all information and responds back. In next huddle follow up question, you can dynamically keep on adding few more agents to the chat or remove existing agents from huddle, as required at runtime. Ideally the agent thats assigned role of huddleMaster - should be avoided with access of other tools and knowledgeVectors, since it can itself try to come up with answers by leveraging tools, instead of orchestrating with expert agents. Basic prompting is done internally for huddleMaster to instruct it to choose the right agent based on the information available. (It relies on sub-agents NAME, and DESCRIPTION). Hence its very important to have meaningful name and description configured for all agents, planned to be in the huddle. Therefore if you have any specific usecase or criteria to choose sub-agents based on something, that you should instruct correctly to huddleMaster agent in the system prompt. If the huddle master doesn't find any suitable subagents then it responds on its own. For ex: If query is "Hello Good morning", this query doesnt require subAgent invocation. HuddleMaster itself will respond saying "gm, how can I help you?". So how you want HuddleMaster to orchestrate the huddle, you can fine tune based on your needs, by tuning the system prompt of huddleMaster and giving it specific instructions on how to operate. At a given point of time, there can be only 1 huddleMaster among all agents configured. Its auto picked up during all huddles. ## Configuring HuddleMaster ### Enabling HuddleMaster To create a HuddleMaster agent: 1. Navigate to the **Agents** page 2. Click **"Add Agent"** or edit an existing agent 3. Configure the agent as usual 4. Enable the **"HuddleMaster"** checkbox 5. Save the agent configuration
Adding Agent Huddle Page
### Adding Agent Huddle Page To add a page with the Agent Huddle component: 1. Navigate to the **Builder** section 2. Click **"Add Page"** or create a new page 3. Select **"Standard Component"** from the component options 4. Choose **"Agent Huddle"** as the component type 5. Configure the page and save --- # Creating Agents URL: /mbrix/agents/creating-agents Learn how to create and configure AI agents with vectors, tools, and custom prompts *** title: Creating Agents description: Learn how to create and configure AI agents with vectors, tools, and custom prompts ------------------------------------------------------------------------------------------------ # Creating Agents Agents are created and configured through a comprehensive interface that allows you to set up their behavior, capabilities, and integrations. This guide walks you through the agent creation process. ## Getting Started To create a new agent: 1. Navigate to the **Agents** page 2. Click the **"Add Agent"** button 3. A modal opens with two options: * **Create from Scratch**: Start with a blank agent configuration * **Choose a Template**: Select a pre-configured template agent
Add Agent Modal
### Create from Scratch Select this option to build a new agent from the ground up. You'll configure all settings manually, giving you full control over the agent's behavior. ### Choose a Template Select this option to start with a pre-configured agent template. Templates provide: * Pre-filled Basic Details * Suggested vector configurations * Recommended tool selections * Sample system prompts After selecting a template, you can modify any settings as needed. ## Required Information * **Name**: Unique name for the agent (required) * **Description**: Description of the agent's purpose (required) * **AI Provider**: AI provider for the agent (required) * **Chat Model**: Specific chat model to use (required) * **System Prompt**: Instructions for the agent's behavior (required) ## Agent Configuration Tabs Agent creation consists of multiple configuration tabs: 1. **Basic Details**: Name, description, AI provider, and model 2. **Vector Configuration**: Configure vectors for RAG 3. **Agent Configuration**: Select tools the agent can use 4. **Prompt Configuration**: Configure system prompt and prompt library
Basic Details Tab

Basic Details

Agent Name

Provide a unique name for the agent (e.g., "Customer Support Agent", "Data Analyst Agent", "Report Generator").

Description

Provide a description explaining the agent's purpose and capabilities (e.g., "AI agent for answering customer questions and providing support").

Display Description

Optional user-friendly description displayed to users. If not provided, the description is used as display description.

AI Provider

Choose the AI provider for the agent:

  • OpenAI: OpenAI models (GPT-4, GPT-3.5, etc.)
  • Ollama: Local Ollama models
  • VertexAI: Google Vertex AI models (Gemini, etc.)

Available chat models will update based on your selection.

Chat Model

Choose the specific chat model to use. Different providers offer different models, and model selection affects capabilities and performance. More powerful models may have higher costs.

Advanced Settings

Configure additional settings:

  • Chat Memory: Enable to allow the agent to remember conversation history and provide context-aware responses
  • Inline Chart Rendering: Enable to allow the agent to render charts inline in responses
  • Database Connection: Select a database connection for tools that need database access
Vector Configuration Tab

Vector Configuration

Configure vectors for RAG (Retrieval-Augmented Generation). Select one or more vector stores to provide context for agent responses.

Select Vectors

Choose vector stores that contain relevant data for the agent's purpose.

Vector Parameters

For each selected vector, configure:

  • Top K: Number of results to retrieve (default: 5)
  • Similarity Threshold: Minimum similarity score (default: 0.2)
  • Data Source Filters: Filter to specific Objects, Files, or Reports (optional)

See Using Vectors with AI Agents for detailed vector configuration.

Agent Configuration Tab

Agent Configuration

Select Agent Configuration the agent can use:

  • Query Tools: Execute database queries on Objects
  • Search Tools: Search Objects, workflows, and reports
  • Report Tools: Generate and execute reports
  • Additional Tools: Other specialized tools

Note: Only select tools that are relevant to the agent's purpose. Too many tools may confuse the agent.

Prompt Configuration Tab

Prompt Configuration

System Prompt

Configure the system prompt that defines agent behavior. You can enter the prompt manually or click "Generate Prompt" / "Improve Prompt" to use AI to generate or improve the prompt based on your configuration.

Best Practices:

  • Provide clear instructions on the agent's role
  • Describe what the agent can do and its limitations
  • Include examples of good responses
  • Explain how to use available tools

Prompt Library

Create prompt library entries for common tasks. Each entry includes:

  • Icon: Visual identifier for the prompt
  • Capability: What the prompt enables (e.g., "Generate revenue report")
  • Prompt: The suggested prompt text
  • Description: Description of the capability

Use prompt library for common user queries, frequently performed tasks, and quick actions.

## Creating from Templates You can create agents from templates: 1. Navigate to Agents page 2. Click "Create from Template" (or similar) 3. Select a template agent 4. Template configuration is pre-filled 5. Modify as needed 6. Save the agent **Note**: Templates provide starting points with common configurations. ## Editing Agents To edit an existing agent: 1. Navigate to the Agents page 2. Find the agent in the list 3. Click the **"Edit"** icon next to the agent 4. The agent builder opens with existing configuration 5. Modify settings as needed 6. Click **"Save"** to apply changes **Note**: Changes take effect immediately. Test agents after making changes. ## Best Practices ### Agent Naming * **Descriptive Names**: Use clear names that indicate purpose * **Consistent Naming**: Use consistent naming conventions * **Include Context**: Include context in names (e.g., "Customer Support Agent") ### System Prompts * **Be Specific**: Provide specific instructions * **Include Examples**: Include examples of good behavior * **Tool Instructions**: Explain how to use tools * **Update Regularly**: Update prompts based on agent performance ### Vector Configuration * **Relevant Vectors**: Select vectors relevant to agent's purpose * **Appropriate Parameters**: Set appropriate top-K and threshold * **Test Configuration**: Test vector configuration with sample queries ### Tool Selection * **Relevant Tools**: Only select tools the agent needs * **Avoid Overload**: Don't select too many tools * **Test Tools**: Test that tools work correctly ### Prompt Library * **Common Tasks**: Add entries for common user tasks * **Clear Prompts**: Use clear, actionable prompts * **Regular Updates**: Update prompt library based on usage ## Related Introduction * [Agents Introduction](/mbrix/agents) - Overview of agents * [Using Agents](/mbrix/agents/using-agents) - Learn how to interact with agents * [Using Vectors with AI Agents](/mbrix/vectors/using-with-ai-agents) - Detailed vector configuration * [Vectors Introduction](/mbrix/vectors) - Understand vectors used with agents * [Connections Introduction](/mbrix/connections) - Learn about database connections --- # Agents Introduction URL: /mbrix/agents Learn about AI Agents - intelligent assistants that can interact with your data and perform tasks *** title: Agents Introduction description: Learn about AI Agents - intelligent assistants that can interact with your data and perform tasks -------------------------------------------------------------------------------------------------------------- # Agents AI Agents are intelligent assistants that can interact with your data, answer questions, perform tasks, and provide insights. They leverage large language models (LLMs) combined with tools and vector stores to provide context-aware, intelligent responses. ## What are AI Agents? AI Agents enable you to: * **Answer Questions**: Answer questions about your data using natural language * **Perform Tasks**: Execute tasks using AI tools (query data, generate reports, etc.) * **Provide Context**: Use vector stores for RAG (Retrieval-Augmented Generation) * **Interact Naturally**: Communicate using natural language conversations * **Access Your Data**: Query and analyze your Objects, workflows, and reports * **Generate Insights**: Provide insights and recommendations based on your data ## Key Concepts ### Agent Types Agents can be categorized by type: * **User Agents**: Custom agents created by users for specific purposes * **System Agents**: Pre-built system agents available for use * **Template Agents**: Template agents that can be used as starting points * **Internal Agents**: Internal system agents (not exposed to users) ### AI Providers Agents use AI providers for language models: * **OpenAI**: OpenAI models (GPT-4, GPT-3.5, etc.) * **Ollama**: Local Ollama models * **VertexAI**: Google Vertex AI models (Gemini, etc.) ### Chat Models Each provider offers different chat models: * **Model Selection**: Choose appropriate model for your use case * **Capabilities**: Different models have different capabilities * **Performance**: Models vary in performance and cost ### Vector Integration Agents can use vectors for RAG: * **Context Retrieval**: Retrieve relevant context from vector stores * **Semantic Search**: Use semantic search to find relevant information * **Multiple Vectors**: Configure multiple vectors for different context types * **Filtered Search**: Filter vector searches to specific data sources ### AI Tools Agents can use AI tools to perform actions: * **Query Tools**: Execute database queries on Objects * **Search Tools**: Search Objects, workflows, and reports * **Report Tools**: Generate and execute reports * **Custom Tools**: Additional tools for specific functionality ### Chat Memory Agents can maintain conversation memory: * **Context Awareness**: Remember previous conversation context * **Conversation History**: Maintain conversation history * **Contextual Responses**: Provide responses based on conversation history ## How Agents Work ### Agent Configuration Agents are configured with: 1. **Basic Information**: Name, description, system prompt 2. **AI Model**: Provider and chat model selection 3. **Vector Configuration**: Vector stores for RAG 4. **AI Tools**: Tools the agent can use 5. **Settings**: Chat memory, chart rendering, etc. ### Agent Execution When an agent receives a query: 1. **Query Processing**: Agent processes the user's query 2. **Context Retrieval**: Retrieves relevant context from vectors (if configured) 3. **Tool Selection**: Determines which tools to use (if needed) 4. **Tool Execution**: Executes tools to gather information or perform actions 5. **Response Generation**: Generates response using LLM with context and tool results 6. **Response Delivery**: Returns response to user ### RAG Process When vectors are configured: 1. **Query Analysis**: Agent analyzes user query 2. **Vector Search**: Searches configured vectors for relevant context 3. **Context Augmentation**: Adds retrieved context to prompt 4. **Response Generation**: Generates response with context ### Tool Usage When tools are configured: 1. **Tool Selection**: Agent determines which tools to use 2. **Tool Invocation**: Calls tools with appropriate parameters 3. **Result Processing**: Processes tool results 4. **Response Integration**: Integrates tool results into response ## Agent Features ### Natural Language Interaction * **Conversational Interface**: Chat-based interface for natural interaction * **Context Understanding**: Understands context and conversation history * **Clarification**: Asks clarifying questions when needed * **Multi-turn Conversations**: Supports multi-turn conversations ### Data Access * **Object Queries**: Query Object data using natural language * **Workflow Information**: Access workflow definitions and information * **Report Generation**: Generate and execute reports * **Data Analysis**: Analyze data and provide insights ### Vector Integration * **RAG Support**: Use vectors for Retrieval-Augmented Generation * **Semantic Search**: Semantic search across your data * **Context-Aware**: Context-aware responses using your data * **Multi-Vector Support**: Configure multiple vectors ### Tool Integration * **Query Execution**: Execute database queries * **Data Retrieval**: Retrieve data from Objects * **Report Generation**: Generate reports dynamically * **Task Automation**: Automate tasks using tools ### Customization * **System Prompts**: Customize agent behavior with system prompts * **Prompt Library**: Create prompt library entries for common tasks * **Tool Selection**: Choose which tools the agent can use * **Vector Configuration**: Configure vectors for specific use cases ## Using Agents Agents can be: * **Created**: Create custom agents for specific purposes * **Configured**: Configure agents with vectors, tools, and settings * **Used**: Interact with agents through chat interface * **Managed**: View, edit, and manage agents * **Templated**: Create agents from templates ## Getting Started 1. **[Creating Agents](/mbrix/agents/creating-agents)**: Learn how to create and configure agents 2. **[Using Agents](/mbrix/agents/using-agents)**: Understand how to interact with agents 3. **[Configuring Vectors for Agents](/mbrix/vectors/using-with-ai-agents)**: Learn how to configure vectors for RAG 4. **Configure Tools**: Select AI tools for your agents 5. **Test Agents**: Test agents with sample queries ## Related Introduction * [Vectors Introduction](/mbrix/vectors) - Understand vectors used for RAG with agents * [Objects Introduction](/mbrix/mobjects) - Learn about Objects that agents can query * [Workflows Introduction](/mbrix/workflows) - Understand workflows that agents can access * [Reports Introduction](/mbrix/reports) - Learn about reports that agents can generate --- # Using Agents URL: /mbrix/agents/using-agents Learn how to interact with AI agents through the chat interface *** title: Using Agents description: Learn how to interact with AI agents through the chat interface ---------------------------------------------------------------------------- # Using Agents Agents provide a conversational interface for interacting with your data and performing tasks. This guide explains how to use agents effectively. ## Accessing Agents ### From Agents Page 1. Navigate to the Agents page 2. Find the agent in the list 3. Click on the agent name or **"Chat"** button 4. The chat interface opens ### From Other Pages Agents can be accessed from: * **Builder Pages**: Agents linked to Builder pages * **Dashboard Widgets**: Agents embedded in dashboards * **Direct Links**: Direct links to agent chat interfaces ## Chat Interface ### Interface Overview The chat interface consists of: * **Agent Header**: Agent name and description * **Chat Messages**: Conversation history * **Input Area**: Text input for queries * **Send Button**: Submit query to agent ### Starting a Conversation 1. **Enter Query**: Type your question or request in the input area 2. **Submit**: Click "Send" or press Enter 3. **Wait for Response**: Agent processes your query and responds 4. **Continue Conversation**: Ask follow-up questions or make additional requests ### Query Examples **Data Questions**: * "Show me all customers from last month" * "What is the total revenue for Q1?" * "List all pending orders" **Task Requests**: * "Generate a report for customer orders" * "Create a workflow for order processing" * "Find all customers with overdue invoices" **Analysis Requests**: * "Analyze sales trends for the last 6 months" * "Compare revenue across different regions" * "What are the top 10 products by sales?" ## Agent Capabilities ### Data Queries Agents can query your data: * **Object Queries**: Query Object records using natural language * **Filtered Queries**: Apply filters and conditions * **Aggregated Queries**: Calculate sums, averages, counts, etc. * **Joined Queries**: Query across multiple Objects **Example**: "Show me all orders with status 'pending' from the last 7 days" ### Report Generation Agents can generate reports: * **Dynamic Reports**: Generate reports based on queries * **Custom Reports**: Create custom report configurations * **Chart Generation**: Generate charts and visualizations * **Data Export**: Export report data **Example**: "Generate a revenue report for last quarter grouped by product" ### Workflow Information Agents can provide information about workflows: * **Workflow Definitions**: Explain workflow configurations * **Workflow Usage**: Show how workflows are used * **Workflow Steps**: Explain workflow steps and logic **Example**: "Explain how the order processing workflow works" ### Context-Aware Responses When vectors are configured: * **Semantic Understanding**: Understand meaning, not just keywords * **Context Retrieval**: Retrieve relevant context from vectors * **Data-Aware**: Responses based on your actual data * **Domain-Specific**: Understand your domain and terminology ## Conversation Features ### Multi-Turn Conversations Agents support multi-turn conversations: * **Context Memory**: Agent remembers previous conversation * **Follow-up Questions**: Ask follow-up questions naturally * **Conversation History**: View conversation history * **Context Continuity**: Maintain context across turns **Example**: * User: "Show me customer orders" * Agent: \[Shows orders] * User: "What about last month?" * Agent: \[Shows last month's orders] ### Clarification Agents ask clarifying questions when needed: * **Missing Information**: Ask for missing information * **Ambiguous Queries**: Clarify ambiguous requests * **Confirmation**: Confirm understanding before proceeding **Example**: * User: "Generate a report" * Agent: "What type of report would you like? Please specify the data source and time period." ## Best Practices ### Query Formulation * **Be Specific**: Provide specific details in queries * **Natural Language**: Use natural language, not keywords * **Include Context**: Include relevant context * **Clear Requests**: Make clear, actionable requests ### Effective Queries **Good Queries**: * "Show me all customers who placed orders in the last 30 days" * "Generate a revenue report for Q1 2024 grouped by product category" * "What are the top 10 products by sales volume this year?" **Less Effective Queries**: * "customers orders" * "report" * "data" ### Follow-up Questions * **Build on Previous**: Build on previous responses * **Be Specific**: Ask specific follow-up questions * **Provide Context**: Reference previous conversation when needed ### Understanding Responses * **Read Carefully**: Read agent responses carefully * **Verify Data**: Verify data in responses when critical * **Ask for Clarification**: Ask for clarification if needed * **Request Details**: Request more details if responses are too brief ## Troubleshooting ### No Response If agent doesn't respond: * **Check Connection**: Verify internet connection * **Wait Longer**: Some queries take time to process * **Try Again**: Retry the query * **Simplify Query**: Try a simpler query ### Incorrect Responses If agent provides incorrect responses: * **Clarify Query**: Rephrase or clarify your query * **Provide More Context**: Provide more context * **Check Agent Configuration**: Verify agent has correct vectors and tools * **Review System Prompt**: Check if system prompt needs updates ### Tool Errors If tools fail: * **Check Permissions**: Verify agent has necessary permissions * **Verify Data**: Ensure data exists and is accessible * **Check Configuration**: Verify tool configuration * **Review Logs**: Check error logs for details ## Related Introduction * [Agents Introduction](/mbrix/agents) - Overview of agents * [Creating Agents](/mbrix/agents/creating-agents) - Learn how to create and configure agents * [Using Vectors with AI Agents](/mbrix/vectors/using-with-ai-agents) - Understand vector integration * [Vectors Introduction](/mbrix/vectors) - Learn about vectors used with agents --- # API Reference URL: /mbrix/api-reference Complete API reference for Monetize360 platform *** title: API Reference description: Complete API reference for Monetize360 platform ------------------------------------------------------------ # API Reference Monetize360 provides a comprehensive REST API for programmatic access to all platform features. ## Base URL ``` https://api.monetize360.com/v1 ``` ## Authentication All API requests require authentication using Bearer tokens: ```bash curl -H "Authorization: Bearer YOUR_API_TOKEN" \ https://api.monetize360.com/v1/workflows ``` ## API Endpoints ### Workflows Execute and manage workflows: ```http POST /workflows/{workflowId}/execute GET /workflows/{workflowId} GET /workflows/{workflowId}/executions GET /workflows/{workflowId}/executions/{executionId} ``` ### Objects (Data Models) Manage data models: ```http GET /mobjects POST /mobjects GET /mobjects/{mobjectId} PUT /mobjects/{mobjectId} DELETE /mobjects/{mobjectId} ``` ### MData (Records) CRUD operations on records: ```http POST /mobjects/{mobjectId}/mdata GET /mobjects/{mobjectId}/mdata/{mdataId} PUT /mobjects/{mobjectId}/mdata/{mdataId} DELETE /mobjects/{mobjectId}/mdata/{mdataId} GET /mobjects/{mobjectId}/mdata ``` ## Execute Workflow Start a workflow execution: ```http POST /workflows/{workflowId}/execute Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN { "data": { "customerId": "cust-123", "amount": 250.00, "action": "process" }, "async": false } ``` ### Response ```json { "executionId": "exec-789-xyz", "status": "completed", "startedAt": "2024-01-15T10:30:00Z", "completedAt": "2024-01-15T10:30:15Z", "output": { "orderId": "ord-456", "status": "success", "result": {...} } } ``` ## Query MData Query records with filters: ```http GET /mobjects/{mobjectId}/mdata?filter=status:eq:active&limit=50&offset=0 Authorization: Bearer YOUR_API_TOKEN ``` ### Query Parameters | Parameter | Type | Description | | --------- | ------- | ---------------------------------------- | | `filter` | string | Filter expression | | `limit` | integer | Maximum records to return (default: 50) | | `offset` | integer | Number of records to skip | | `sort` | string | Sort field and direction | | `fields` | string | Comma-separated list of fields to return | ### Filter Syntax ``` field:operator:value ``` Operators: * `eq` - Equals * `ne` - Not equals * `gt` - Greater than * `lt` - Less than * `gte` - Greater than or equal * `lte` - Less than or equal * `in` - In array * `contains` - Contains substring ## Create MData Insert a new record: ```http POST /mobjects/{mobjectId}/mdata Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN { "data": { "name": "John Doe", "email": "john@example.com", "status": "active", "tier": "premium" } } ``` ### Response ```json { "id": "7f8a2ea8-6d9a-5f3b-b9f7-9f7b6d9a2eb1", "mobjectId": "3f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea9", "data": { "name": "John Doe", "email": "john@example.com", "status": "active", "tier": "premium" }, "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T10:30:00Z" } ``` ## Update MData Update an existing record: ```http PUT /mobjects/{mobjectId}/mdata/{mdataId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN { "data": { "status": "inactive", "deactivatedAt": "2024-01-15T10:30:00Z" } } ``` ## Delete MData Delete a record: ```http DELETE /mobjects/{mobjectId}/mdata/{mdataId} Authorization: Bearer YOUR_API_TOKEN ``` ### Response ```json { "success": true, "message": "Record deleted successfully" } ``` ## Bulk Operations ### Bulk Insert Insert multiple records at once: ```http POST /mobjects/{mobjectId}/mdata/bulk Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN { "data": [ {"name": "Customer 1", "email": "c1@example.com"}, {"name": "Customer 2", "email": "c2@example.com"}, {"name": "Customer 3", "email": "c3@example.com"} ] } ``` ### Response ```json { "success": true, "totalProcessed": 3, "created": 3, "failed": 0, "data": [...] } ``` ## Error Handling All errors follow a consistent format: ```json { "error": { "code": "VALIDATION_ERROR", "message": "Invalid email address format", "details": { "field": "email", "value": "invalid-email" }, "timestamp": "2024-01-15T10:30:00Z" } } ``` ### HTTP Status Codes | Code | Description | | ---- | --------------------- | | 200 | Success | | 201 | Created | | 400 | Bad Request | | 401 | Unauthorized | | 403 | Forbidden | | 404 | Not Found | | 429 | Too Many Requests | | 500 | Internal Server Error | ## Rate Limiting API requests are rate limited: * **Standard**: 100 requests per minute * **Premium**: 1000 requests per minute * **Enterprise**: Custom limits Rate limit headers: ``` X-RateLimit-Limit: 100 X-RateLimit-Remaining: 95 X-RateLimit-Reset: 1705363260 ``` ## Pagination Large result sets are paginated: ```http GET /mobjects/{mobjectId}/mdata?limit=50&offset=0 ``` Response includes pagination metadata: ```json { "data": [...], "pagination": { "total": 500, "limit": 50, "offset": 0, "hasMore": true } } ``` ## Webhooks Configure webhooks to receive real-time notifications: ```http POST /webhooks Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN { "url": "https://your-app.com/webhook", "events": ["workflow.completed", "mdata.created"], "secret": "your-webhook-secret" } ``` ### Webhook Payload ```json { "event": "workflow.completed", "timestamp": "2024-01-15T10:30:00Z", "data": { "workflowId": "workflow-uuid", "executionId": "execution-uuid", "status": "completed", "output": {...} } } ``` ## SDK Support Official SDKs available: * **JavaScript/TypeScript**: `npm install @monetize360/sdk` * **Python**: `pip install monetize360` * **Java**: Maven/Gradle packages * **Go**: `go get github.com/monetize360/sdk-go` ### JavaScript Example ```javascript import { Monetize360Client } from '@monetize360/sdk'; const client = new Monetize360Client({ apiKey: 'YOUR_API_TOKEN', baseUrl: 'https://api.monetize360.com/v1' }); // Execute workflow const result = await client.workflows.execute('workflow-id', { data: { customerId: 'cust-123' } }); // Query MData const records = await client.mdata.query('mobject-id', { filter: 'status:eq:active', limit: 50 }); ``` ### Python Example ```python from monetize360 import Client client = Client(api_key='YOUR_API_TOKEN') # Execute workflow result = client.workflows.execute( workflow_id='workflow-id', data={'customerId': 'cust-123'} ) # Query MData records = client.mdata.query( mobject_id='mobject-id', filter='status:eq:active', limit=50 ) ``` ## Best Practices 1. **Use API Keys Securely**: Store in environment variables 2. **Handle Rate Limits**: Implement exponential backoff 3. **Validate Input**: Check data before sending 4. **Use Pagination**: For large datasets 5. **Handle Errors**: Implement proper error handling 6. **Use Webhooks**: For real-time updates 7. **Cache Responses**: When appropriate 8. **Monitor Usage**: Track API consumption ## Testing Use the API sandbox for testing: ``` https://sandbox.monetize360.com/v1 ``` Test credentials are provided in your developer portal. ## Support * **API Status**: [https://status.monetize360.com](https://status.monetize360.com) * **Documentation**: [https://docs.monetize360.com](https://docs.monetize360.com) * **Support**: [support@monetize360.com](mailto:support@monetize360.com) * **Community**: [https://community.monetize360.com](https://community.monetize360.com) --- # Introduction URL: /mbrix/application-builder Application Builder (Advance Builder in the UI) is MPilot's visual studio for pages and multi-screen applications. Compose layouts on a canvas, connect Data Grids and Reports, add logic in the Code panel, and publish live apps. *** title: "Introduction" description: "Application Builder (Advance Builder in the UI) is MPilot's visual studio for pages and multi-screen applications. Compose layouts on a canvas, connect Data Grids and Reports, add logic in the Code panel, and publish live apps." -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **Application Builder** — shown as **Advance Builder** in the product — lets teams ship internal tools and customer-facing apps without writing custom React frontends for every use case. You design visually, bind data with `{{ expressions }}`, and publish applications at `/apps/your-slug`. ## How you build When you open Advance Builder, you start from the **listing** — your workspace of pages and applications. From there you pick a path: * **Visual designer.** Drag components onto the canvas, configure in the Inspector, and wire event handlers. The clearest way to see layout and UX. * **Code panel.** Add variables, queries, functions, and computed values. The logic layer behind bindings and actions. * **Snapshot JSON.** Import or export full page definitions — including AI-generated layouts via Paste snapshot JSON. You can mix all three: scaffold with JSON or templates, then refine visually and add queries in Code. ## The anatomy of a workspace An Advance Builder asset is not just a canvas — it is a set of connected parts. The sidebar in this documentation mirrors that structure: * **Listing** — home for all pages and applications, organized in folders. * **Designer** — toolbar, nav rail (Components, Outline, Code, Screens), canvas, and Inspector. * **Code panel** — variables, queries, functions, computed values, and watchers. * **Components** — the widget library: UI chrome, inputs, and MPilot data embeds. * **Integrations** — connect List Views, Reports, Dashboards, Forms, Tables, and Picklists. * **Applications** — Shell layout + Screens + routes + a single Outlet for screen content. ## What you can build * **Internal admin tools.** Data grids, filters, and action menus over MPilot tables. * **Customer portals.** Multi-screen apps with navigation, search, and detail views. * **Dashboards.** Reports and Dashboard components embedded in a custom shell. * **Workflow UIs.** MFlow forms inside a branded application layout. ## Next steps * [What is Advance Builder?](/mbrix/application-builder/get-started/overview) — big picture and when to use it * [Designer layout](/mbrix/application-builder/designer/designer) — tour the visual workspace * [Component library](/mbrix/application-builder/components/library) — every widget and what it solves * [Walkthroughs](/mbrix/application-builder/walkthroughs/w1) — step-by-step build guides --- # Creating Pages URL: /mbrix/builder/creating-pages *** ## title: Creating Pages Pages are created using the Builder interface. Each page displays a single widget and can be configured with various settings to control its appearance and behavior. ## Required Information * **Title**: Display name for the page * **Widget Type**: The type of widget to display (Flow, Report, Data Grid, Dashboard, etc.) * **Widget Item**: The specific item to display (selected based on widget type) ## Configuration Steps
Page Configuration Steps Interface 1 Page Configuration Steps Interface 2 Page Configuration Steps Interface 3
### 1. Open Page Creation Dialog Navigate to the Builder interface and click the **"Add"** button (or similar action) to open the page creation dialog. ### 2. Enter Page Title Provide a descriptive title for the page. This title will be displayed in the navigation and on the page itself. **Description**: This is the name displayed for the page on the Mpilot screen. ### 3. Enter Page Description Provide an optional description explaining the purpose or usage of the page. **Description**: This is the description used for the page on the Mpilot screen. ### 4. Select Page Icon Choose an icon to visually represent the page. Icons help users quickly identify pages in navigation. **Description**: This is the icon used for the page on the Mpilot screen. ### 5. Configure Visibility Settings Configure how the page appears in the interface: #### Hide Page in Mpilot Toggle to show or hide this page in the Mpilot interface. When enabled, the page will not be visible to users. #### Show Create Flow When Data is Empty Toggle to show the create form directly on the page when there's no data. When enabled, users will see the form immediately instead of an empty grid. **Use Case**: Useful for pages with datagrids where you want users to be able to create records immediately. #### Hide Top and Left Nav Toggle to hide the top and left navigation, keeping only the logo. This provides a cleaner, more focused interface. **Use Case**: Useful for pages that should be displayed in a standalone or embedded context. ### 6. Link to Agent (Optional) Associate an AI agent with the page. When an agent is linked, it enables AI-powered features and conversational interfaces. **Description**: This is the agent that will be used for the page on the Mpilot screen. ### 7. Select Folder (Optional) Choose a folder to organize the page. Folders help organize pages for better management and navigation. **Description**: Choose the folder where this page will be organized. ### 8. Configure Widget Configure the widget that will be displayed on the page: #### Select Widget Type Choose the type of widget to display: * **Flow**: Display a workflow interface * **Report**: Display a report * **Data Grid**: Display a datagrid for viewing Object records * **Dashboard**: Display a dashboard with multiple components * **Estimator**: Display an estimator layout for price calculations * **Standard Components**: Display standard system components (Price Estimator, Day Ops, Audit Trail) * **View360**: Display a View360 layout for comprehensive record views * **Flow Chain**: Display a flow chain execution interface * **Link**: Display an external link or URL #### Select Widget Item Based on the selected widget type, choose the specific item to display: * **For Flow**: Select a workflow * **For Report**: Select a report * **For Data Grid**: Select a datagrid * **For Dashboard**: Select a dashboard * **For Estimator**: Select a workflow used for estimation * **For Standard Components**: Select from available standard components * **For View360**: Select a View360 layout * **For Flow Chain**: Select a flow chain * **For Link**: Enter a URL (e.g., `https://example.com`) ### 9. Save Page Click the **"Save"** button to create the page. After saving: * The page is created and appears in the Builder page list * The page can be accessed from the Mpilot interface (if not hidden) * The page can be edited, cloned, or deleted as needed ## Editing Existing Pages To edit an existing page: 1. Navigate to the Builder interface 2. Find the page in the page list 3. Click the **"Edit"** icon next to the page 4. The page creation dialog will open with existing configuration 5. Make your desired changes 6. Click **"Save"** to apply updates ## Cloning Pages To clone an existing page: 1. Navigate to the Builder interface 2. Find the page in the page list 3. Click the **"Clone"** icon next to the page 4. A new page will be created with the same configuration 5. Edit the cloned page as needed ## Reordering Folders and Pages ### Reordering Folders You can reorder folders in the Builder sidebar to organize your page structure: 1. Navigate to the Builder interface 2. Click the **reorder icon** (ArrowUpDown) in the sidebar header to enable bulk edit mode 3. Drag and drop folders in the sidebar tree to reorder them 4. Folders can be moved within the same level or to different parent folders 5. Click the **check icon** (✓) to save your changes 6. Click the **X icon** to cancel and revert to the original order **Note**: The "All Pages" and "Uncategorized" folders cannot be reordered and will remain at the top of the tree. ### Reordering Pages Pages are displayed in a grid format and can be filtered by folder. To change the order of pages: * **Within a Folder**: Pages within a folder are displayed in the order they were created or last modified * **Move Between Folders**: Change a page's folder by editing the page and selecting a different folder ## Best Practices ### Naming Conventions * Use descriptive titles that clearly indicate the page's purpose * Include context in the title (e.g., "Customer Orders Dashboard" instead of "Dashboard") * Use consistent naming patterns across related pages ### Widget Selection * Choose widget types that match your use case * Ensure the selected widget item exists and is properly configured * Test widget functionality after page creation ### Organization * Use folders to organize related pages together * Group pages by functional area or user role * Keep folder structures simple and intuitive ### Visibility Settings * Use "Hide Page" for pages that should only be accessed programmatically * Enable "Show Create Flow" for pages where users frequently create new records * Use "Hide Top and Left Nav" for embedded or standalone page contexts ### AI Agent Integration * Link agents to pages that benefit from AI assistance * Choose agents that match the page's purpose and content * Test agent functionality after linking ## Related Introduction * [Builder Introduction](/mbrix/builder) - Overview of Builder and pages * [Workflows Introduction](/mbrix/workflows) - Learn about workflows used as page widgets * [Datagrids Introduction](/mbrix/datagrids) - Understand datagrids used as page widgets * [Layouts Introduction](/mbrix/layouts) - Learn about layouts used as page widgets --- # Builder Introduction URL: /mbrix/builder *** ## title: Builder Introduction Builder is the page builder interface that allows you to create and manage application pages. Pages are customizable interfaces that can display various widgets and components, enabling you to build complete application experiences. ## What is Builder? Builder enables you to: * **Create Pages**: Build custom application pages with titles, icons, and descriptions * **Add Widgets**: Configure widgets to display content (flows, reports, datagrids, dashboards, etc.) * **Organize Pages**: Organize pages in folders for better management * **Associate Objects**: Link pages with Objects to provide context * **Enable AI Agents**: Associate AI agents with pages for intelligent interactions * **Configure Navigation**: Control page visibility and navigation behavior ## Page Components Each page consists of: ### Page Information * **Title**: Display name for the page * **Icon**: Visual icon representing the page * **Description**: Optional description explaining the page's purpose * **Folder**: Optional folder for organization ### Widget Configuration Pages can display one widget of the following types: * **Flow**: Display a workflow (MFlow) interface * **Report**: Display a report (MReport) * **Data Grid**: Display a datagrid (MDataGrid) for viewing Object records * **Dashboard**: Display a dashboard with multiple components * **Estimator**: Display an estimator layout for price calculations * **Standard Components**: Display standard system components * **View360**: Display a View360 layout for comprehensive record views * **Flow Chain**: Display a flow chain execution interface * **Link**: Display an external link or URL ### AI Agent Integration Pages can be associated with AI agents: * **Intelligent Interactions**: Enable AI-powered features * **Chat Interface**: Provide conversational interfaces * **Automated Assistance**: Enable automated help and guidance ## Page Settings ### Visibility Settings * **Hide Page**: Control whether the page appears in navigation * **Show Create Flow**: Enable workflow creation from the page * **Hide Top Left Nav**: Control navigation visibility ### Organization * **Folders**: Organize pages in a hierarchical folder structure * **Search**: Search pages by name * **Bulk Operations**: Reorder and manage multiple pages ## Using Builder Builder provides: 1. **Page List**: View all pages in a grid format 2. **Folder Navigation**: Navigate pages by folder using the sidebar tree 3. **Page Creation**: Create new pages with widget configuration 4. **Page Editing**: Edit existing pages and their configurations 5. **Page Cloning**: Clone pages to create similar pages quickly 6. **Page Deletion**: Remove pages that are no longer needed ## Getting Started 1. **[Creating Pages](/mbrix/builder/creating-pages)**: Learn how to create pages with step-by-step instructions 2. **Configure Widgets**: Select and configure widgets for your pages 3. **Organize Pages**: Use folders to organize pages for better management ## Related Introduction * [Objects Introduction](/mbrix/mobjects) - Understand the data models used in pages * [Workflows Introduction](/mbrix/workflows) - Learn about workflows displayed in pages * [Datagrids Introduction](/mbrix/datagrids) - Understand datagrids used as page widgets * [Layouts Introduction](/mbrix/layouts) - Learn about layouts displayed in pages --- # Configuring Dashboard Filters URL: /mbrix/dashboard/configuring-dashboard-filters Learn how to configure global filters for dashboards, including filter criteria, widget mapping, and join information *** title: Configuring Dashboard Filters description: Learn how to configure global filters for dashboards, including filter criteria, widget mapping, and join information ---------------------------------------------------------------------------------------------------------------------------------- # Configuring Dashboard Filters Dashboard filters allow you to apply global filters that affect multiple widgets on a dashboard. Filters can filter data across different Objects and widgets, enabling powerful cross-object filtering and data synchronization. ## What are Dashboard Filters? Dashboard filters enable you to: * **Filter Multiple Widgets**: Apply a single filter that affects multiple widgets simultaneously * **Cross-Object Filtering**: Filter data across different Objects using relationships * **Dynamic Filtering**: Change filter values to update all affected widgets in real-time * **Widget Mapping**: Map filter fields to widget-specific fields for flexible filtering * **Join Information**: Configure relationships between Objects for complex filtering scenarios ## How Dashboard Filters Work ### Filter Flow 1. **Filter Definition**: Define a filter using a reference object and field 2. **Filter Criteria**: Configure filter conditions (operator, value) 3. **Widget Mapping**: Map the filter field to fields in each widget 4. **Filter Application**: When filter value changes, all mapped widgets update automatically ### Key Concepts * **Reference Object**: The Object that provides the filter field * **Reference Field**: The field from the reference object used for filtering * **Widget Mapping**: Links filter fields to widget-specific fields * **Join Information**: Defines relationships between Objects for cross-object filtering ## Creating Filters ### 1. Open Filter Configuration Click the **"Add Filter"** button in the filters section of the dashboard designer to open the filter configuration modal. ### 2. Configure Filter Basic Information #### Filter Name Enter a descriptive name for the filter. This name will be displayed in the filter chips above the dashboard. **Required**: Yes **Field**: Filter Name **Best Practice**: Use clear, descriptive names that indicate what the filter does (e.g., "Date Range", "Customer Filter", "Status Filter"). #### Filter Description Provide an optional description explaining the filter's purpose or usage. **Required**: No **Field**: Filter Description ### 3. Select Reference Object Choose the Object that provides the filter field. This is the source object for your filter criteria. **Required**: Yes **How to select**: Use the dropdown to select an Object. The dropdown shows Objects that are used by widgets on the dashboard. **Note**: The reference object must be associated with at least one widget on the dashboard. ### 4. Select Reference Field Choose the field from the reference object that will be used for filtering. **Required**: Yes **How to select**: After selecting a reference object, use the field selector to choose a field. Available fields include: * Regular fields from the Object * Lookup fields (fields that reference other Objects) * System properties (id, created\_at, etc.) **Field Types**: You can filter by any field type (String, Number, Date, Picklist, Lookup, etc.). ### 5. Configure Filter Criteria Configure the filter condition using the query builder interface. #### Filter Operator Select the comparison operator for the filter: **String/Text Fields**: * **Equals (=)**: Exact match * **Not Equals (✕)**: Not equal to value * **Contains (🔍)**: Contains substring * **Not Contains (🔍✕)**: Does not contain substring * **Starts With (→)**: Begins with value * **Ends With (←)**: Ends with value * **Is Null (-)**: Field is null * **Is Not Null (+)**: Field is not null * **In (⊙)**: Field value is in list * **Not In (☒)**: Field value is not in list **Numeric Fields**: * **Equals (=)**: Equal to value * **Not Equals (✕)**: Not equal to value * **Greater Than (>)**: Greater than value * **Greater Than or Equal (>|)**: Greater than or equal to value * **Less Than (\<)**: Less than value * **Less Than or Equal (|\<)**: Less than or equal to value * **Between (\<>)**: Between two values * **Is Null (-)**: Field is null * **Is Not Null (+)**: Field is not null **Date Fields**: * **Equals (=)**: Equal to date * **Not Equals (✕)**: Not equal to date * **Greater Than (>)**: After date * **Greater Than or Equal (>|)**: On or after date * **Less Than (\<)**: Before date * **Less Than or Equal (|\<)**: On or before date * **Between (\<>)**: Between two dates * **Is Null (-)**: Field is null * **Is Not Null (+)**: Field is not null * **Date Literals**: Today, Yesterday, Last Week, Last Month, etc. **Picklist Fields**: * **Equals (=)**: Equal to picklist value * **Not Equals (✕)**: Not equal to picklist value * **In (⊙)**: Field value is in list of picklist values * **Not In (☒)**: Field value is not in list of picklist values * **Is Null (-)**: Field is null * **Is Not Null (+)**: Field is not null **How to select**: The operator dropdown automatically shows operators that are valid for the selected field's data type. #### Filter Value Enter the filter value based on the selected operator: **Single Value Operators** (Equals, Contains, Greater Than, etc.): * Enter a single value in the input field * For picklist fields, select from dropdown * For date fields, use date picker or date literals (Today, Yesterday, etc.) * For lookup fields, select from related Object records **Multiple Value Operators** (In, Not In): * Enter multiple values (tags mode) * Select multiple values from dropdown * For picklist fields, select multiple picklist values **Between Operator**: * Enter two values (start and end) * For dates, select date range * For numbers, enter min and max values **Null Operators** (Is Null, Is Not Null): * No value input required * Operator alone defines the condition **Value Input Types**: * **Text Input**: For string/text fields * **Number Input**: For numeric fields * **Date Picker**: For date fields * **Dropdown**: For picklist fields * **Typeahead**: For lookup fields (searches related Object records) ### 6. Configure Widget Mapping Map the filter field to fields in each widget that should be affected by this filter. #### Understanding Widget Mapping Widget mapping connects the filter field to widget-specific fields: * **Filter Field**: The reference field you selected (e.g., "Customer ID") * **Widget Field**: A field in a widget that should be filtered (e.g., "Order Customer ID") When the filter value changes, widgets with mappings update to show only records matching the filter. #### Add Widget Mappings For each widget on the dashboard: 1. **Select Widget**: The widget is automatically listed if it uses an Object related to the reference object 2. **Select Widget Field**: Choose the field in the widget that corresponds to the filter field 3. **Data Type Matching**: The widget field must have a compatible data type with the filter field **Required**: At least one widget mapping is required **How it works**: * Only widgets with mappings are affected by the filter * Widgets without mappings continue to show all data * Multiple widgets can be mapped to the same filter #### Widget Mapping Rules * **Data Type Compatibility**: Widget fields must have compatible data types with the filter field * **Field Availability**: Only fields from widgets that use Objects related to the reference object are available * **Multiple Mappings**: You can map the filter to multiple widgets * **Optional Mappings**: Not all widgets need to be mapped (only those you want filtered) ### 7. Join Information (Automatic) Join information is automatically generated when: * Filter fields reference other Objects (lookup fields) * Widget fields reference other Objects * Cross-object relationships exist **How it works**: The system automatically detects relationships and generates join information to enable cross-object filtering. **Manual Configuration**: Join information is typically handled automatically, but you can verify it in the filter configuration. ### 8. Save Filter Click **"Save"** to create the filter. The filter will: * Appear as a filter chip above the dashboard * Be available for editing and deletion * Apply to all widgets with mappings when values are set ## Managing Filters ### Viewing Filters Filters are displayed as chips above the dashboard: * **Filter Name**: Displayed as the chip label * **Filter Value**: Shows current filter value (if set) * **Operator Icon**: Visual indicator of the operator type * **Edit Icon**: Click to edit the filter * **Delete Icon**: Click to remove the filter ### Editing Filters To edit an existing filter: 1. Click the **Edit icon** (pencil icon) on the filter chip 2. The filter configuration modal opens with current settings 3. Modify filter name, description, criteria, or widget mappings 4. Click **"Save"** to apply changes **Note**: Editing a filter updates it for all widgets that use it. ### Removing Filters To remove a filter: 1. Click the **Delete icon** (X icon) on the filter chip 2. Confirm deletion in the confirmation dialog **Warning**: If a widget is deleted and it was the only widget mapped to a filter, the filter will also be deleted. You'll be notified about affected filters before deletion. ### Clearing Filter Values To clear a filter value without deleting the filter: 1. Click the **Clear icon** on the filter chip 2. The filter value is cleared, and all widgets show unfiltered data **Note**: Clearing a filter value doesn't delete the filter configuration. You can set a new value later. ### Applying Filters Filters are applied automatically when: * Filter value is set or changed * Dashboard is loaded with saved filter values * Filter is edited and saved **Real-time Updates**: Widgets update in real-time when filter values change. ## Multiple Filters ### Adding Multiple Filters You can add multiple filters to a dashboard: 1. Click **"Add Filter"** to create additional filters 2. Configure each filter independently 3. Each filter can have different reference objects, fields, and widget mappings ### Filter Combination Logic When multiple filters are active: * **AND Logic**: All active filters are applied together (records must match all filters) * **Independent Operation**: Each filter works independently * **Combined Effect**: Widgets show only records that match all active filters **Example**: If you have "Date Range" and "Status" filters active, widgets show records that match both the date range AND the status. ### Filter Priority * All filters have equal priority * Filters are applied in the order they were created (for display purposes) * No filter overrides another filter ## Best Practices ### Filter Design * **Meaningful Names**: Use clear, descriptive filter names * **Appropriate Fields**: Choose fields that make sense for filtering * **User-Friendly Values**: Use filters that users can easily understand and set ### Widget Mapping * **Map Relevant Widgets**: Only map widgets that should be filtered together * **Data Type Matching**: Ensure widget fields have compatible data types * **Test Mappings**: Verify that widget mappings work correctly after configuration ### Performance * **Limit Filter Count**: Avoid creating too many filters (typically 2-5 filters) * **Efficient Operators**: Use efficient operators (Equals is faster than Contains) * **Indexed Fields**: Prefer filtering on indexed fields for better performance ### User Experience * **Default Values**: Consider setting default filter values for common use cases * **Clear Labels**: Use filter names that clearly indicate what they filter * **Filter Documentation**: Add descriptions to explain filter purpose ### Cross-Object Filtering * **Relationship Understanding**: Understand Object relationships before configuring cross-object filters * **Join Verification**: Verify that join information is correctly generated * **Test Scenarios**: Test filters with different data scenarios ## Common Use Cases ### Date Range Filtering Filter widgets by date ranges: * **Reference Object**: Orders Object * **Reference Field**: Order Date * **Operator**: Between * **Widget Mapping**: Map to Order Date fields in report and datagrid widgets ### Status Filtering Filter widgets by status: * **Reference Object**: Tasks Object * **Reference Field**: Status (Picklist) * **Operator**: Equals or In * **Widget Mapping**: Map to Status fields in task-related widgets ### Customer Filtering Filter widgets by customer: * **Reference Object**: Customers Object * **Reference Field**: Customer ID * **Operator**: Equals * **Widget Mapping**: Map to Customer ID fields in order, invoice, and payment widgets ### Cross-Object Filtering Filter widgets using related Object data: * **Reference Object**: Customers Object * **Reference Field**: Customer Name (via lookup) * **Operator**: Contains * **Widget Mapping**: Map to Customer Name fields in order widgets (using join information) ## Related Introduction * [Creating Dashboards](/mbrix/dashboard/creating-dashboards) - Learn how to create dashboards * [Dashboard Introduction](/mbrix/dashboard) - Overview of dashboards * [Objects Introduction](/mbrix/mobjects) - Understand Objects and relationships used in filters * [Reports Introduction](/mbrix/reports) - Learn about reports used as dashboard widgets * [Datagrids Introduction](/mbrix/datagrids) - Understand datagrids used as dashboard widgets --- # Creating Dashboards URL: /mbrix/dashboard/creating-dashboards Learn how to create dashboards with step-by-step instructions *** title: Creating Dashboards description: Learn how to create dashboards with step-by-step instructions -------------------------------------------------------------------------- # Creating Dashboards Dashboards are created using the Dashboard Designer interface. Each dashboard combines multiple widgets (reports, datagrids, charts, etc.) into a single view with configurable filters and layout. ## Required Information * **Name**: Unique identifier for the dashboard (required) * **Description**: Optional description explaining the dashboard's purpose * **Widgets**: At least one widget to display (required) ## Configuration Steps ### 1. Open Dashboard Designer Navigate to the Dashboards page and click the **"Add Dashboard"** button (or similar action) to open the Dashboard Designer. ### 2. Enter Dashboard Name Provide a unique name for the dashboard. This name will be used to identify the dashboard throughout the system. **Required**: Yes **Field**: Dashboard Name **Description**: This is the name displayed for the dashboard. ### 3. Enter Dashboard Description Provide an optional description explaining the purpose or usage of the dashboard. **Required**: No **Field**: Dashboard Description **Description**: This is the description used for the dashboard. ### 4. Select Folder (Optional) Choose a folder to organize the dashboard. Folders help organize dashboards for better management and navigation. **Required**: No **Field**: Folder **Description**: Choose the folder where this dashboard will be organized. **How to select**: Use the dropdown to select from existing folders, or leave empty to place in the root or uncategorized folder. ### 5. Add Widgets Add widgets to your dashboard by dragging and dropping them from the widget panel onto the dashboard grid. #### Widget Types Available widget types include: **Reports**: * **Report Widgets**: Display reports (charts, tables, KPIs) created in the Reports section * **Search**: Use the search bar to find specific reports * **Pagination**: Load more reports if available **Data Grids**: * **Datagrid Widgets**: Display datagrids created in the Datagrids section * **Search**: Use the search bar to find specific datagrids * **Object Data**: Show Object records in table format **Standard Widgets**: * **Summary Ribbon**: Display summary statistics or KPIs * **Webpage**: Embed external web pages * **Image**: Display images * **Quick Action**: Provide quick action buttons * **Insight Card**: Display insights or key information * **Layout**: Display layouts created in the Layouts section * **Actionable Card**: Display cards with action buttons For detailed information about each widget type, including configuration options, size constraints, and use cases, see **[Dashboard Widget Types](/mbrix/dashboard/dashboard-widget-types)**. #### Adding Widgets **How to add**: 1. In the left sidebar, browse available widgets by category (Standard, Reports, Data Grids) 2. Drag a widget from the widget panel 3. Drop it onto the dashboard grid at your desired position 4. The widget is automatically added with default size and position **Widget Positioning**: * Widgets are positioned using a grid system (x, y coordinates) * Each widget has a default width (w) and height (h) in grid units * Widgets can be repositioned by dragging after they're added **Widget Sizing**: * Each widget type has minimum and maximum size constraints * Widgets can be resized by dragging their corners or edges * Size constraints prevent widgets from becoming too small or too large ### 6. Configure Widget Properties After adding a widget, configure its properties: #### Report Widgets * **Select Report**: Choose the specific report to display * **Widget Title**: Customize the widget title (optional) * **Widget Settings**: Configure report-specific settings #### Datagrid Widgets * **Select Datagrid**: Choose the specific datagrid to display * **Widget Title**: Customize the widget title (optional) * **Widget Settings**: Configure datagrid-specific settings #### Standard Widgets Each standard widget type has its own configuration options: * **Summary Ribbon**: Configure summary fields and display options * **Webpage**: Enter URL and configure display settings * **Image**: Upload or link to image and configure display * **Quick Action**: Configure action buttons and targets * **Insight Card**: Configure card content and styling * **Layout**: Select layout and configure display options * **Actionable Card**: Configure card content and actions ### 7. Arrange Widget Layout Organize widgets on the dashboard: **Repositioning Widgets**: * Drag widgets to different positions on the grid * Widgets automatically snap to grid positions * Multiple widgets can be arranged side by side or stacked **Resizing Widgets**: * Click and drag widget corners or edges to resize * Widgets respect minimum and maximum size constraints * Resize widgets to fit content or optimize space usage **Grid Layout**: * The dashboard uses a responsive grid layout system * Widgets are positioned using x, y coordinates * Grid units determine widget sizes and spacing ### 8. Configure Global Filters (Optional) Configure filters that apply to all widgets on the dashboard by clicking the **"Add Filter"** button in the filters section. Filters allow you to: * **Filter Multiple Widgets**: Apply a single filter that affects multiple widgets simultaneously * **Cross-Object Filtering**: Filter data across different Objects using relationships * **Widget Mapping**: Map filter fields to widget-specific fields for flexible filtering * **Dynamic Updates**: Change filter values to update all affected widgets in real-time For detailed information about configuring filters, including filter criteria, widget mapping, join information, and best practices, see **[Configuring Dashboard Filters](/mbrix/dashboard/configuring-dashboard-filters)**. ### 9. Preview Dashboard Click the **"Preview"** button to view the dashboard with live data: * **Live Data**: Widgets display actual data from Objects * **Filter Testing**: Test global filters and their effects on widgets * **Layout Verification**: Verify widget positioning and sizing * **Responsive Check**: Check how the dashboard looks on different screen sizes ### 10. Save Dashboard Click the **"Save"** button to save your dashboard configuration. **After Saving**: * The dashboard is created and appears in the Dashboards list * The dashboard can be edited, cloned, or deleted as needed * The dashboard can be embedded in Builder pages * The dashboard can be shared with team members ## Editing Existing Dashboards To edit an existing dashboard: 1. Navigate to the Dashboards list 2. Click the **"Edit"** icon next to the dashboard (or click on the dashboard name) 3. The Dashboard Designer will open with the existing configuration loaded 4. Make your desired changes to widgets, filters, layout, or settings 5. Click **"Save"** to apply your updates ## Cloning Dashboards To clone an existing dashboard: 1. Navigate to the Dashboards list 2. Click the **"Clone"** icon next to the dashboard 3. A new dashboard will be created with the same configuration 4. Edit the cloned dashboard as needed ## Deleting Dashboards To delete a dashboard: 1. Navigate to the Dashboards list 2. Click the **"Delete"** icon next to the dashboard 3. Confirm the deletion in the confirmation dialog **Note**: If a dashboard has filters that only map to widgets being deleted, those filters will also be deleted. You'll be notified about affected filters before deletion. ## Best Practices ### Widget Selection * **Relevant Widgets**: Add only widgets that are relevant to the dashboard's purpose * **Widget Variety**: Mix different widget types for comprehensive views * **Widget Count**: Limit the number of widgets to avoid clutter (typically 4-8 widgets) ### Layout Organization * **Logical Grouping**: Group related widgets together * **Visual Hierarchy**: Place important widgets in prominent positions * **Balanced Layout**: Distribute widgets evenly across the dashboard * **Responsive Design**: Consider how the layout works on different screen sizes ### Filter Configuration * **Meaningful Filters**: Configure filters that provide value to users * **Widget Mapping**: Ensure filters are properly mapped to relevant widgets * **Filter Testing**: Test filters to ensure they work correctly with all widgets * **Filter Documentation**: Use clear filter names and descriptions ### Performance * **Widget Count**: Limit the number of widgets to maintain performance * **Data Volume**: Consider data volume when configuring widgets * **Filter Efficiency**: Use efficient filter conditions to improve performance ### Organization * **Folders**: Organize dashboards in folders for better management * **Naming Conventions**: Use clear, descriptive names for dashboards * **Descriptions**: Add descriptions to explain dashboard purpose * **Regular Updates**: Update dashboards as data sources or requirements change ## Related Introduction * [Dashboard Widget Types](/mbrix/dashboard/dashboard-widget-types) - Detailed guide to all widget types * [Configuring Dashboard Filters](/mbrix/dashboard/configuring-dashboard-filters) - Detailed guide to configuring dashboard filters * [Dashboard Introduction](/mbrix/dashboard) - Overview of dashboards * [Reports Introduction](/mbrix/reports) - Learn about reports used as dashboard widgets * [Datagrids Introduction](/mbrix/datagrids) - Understand datagrids used as dashboard widgets * [Layouts Introduction](/mbrix/layouts) - Learn about layouts used as dashboard widgets * [Builder Introduction](/mbrix/builder) - Learn how to embed dashboards in Builder pages --- # Dashboard Widget Types URL: /mbrix/dashboard/dashboard-widget-types Learn about all available widget types in dashboards, their configuration options, and use cases *** title: Dashboard Widget Types description: Learn about all available widget types in dashboards, their configuration options, and use cases ------------------------------------------------------------------------------------------------------------- # Dashboard Widget Types Dashboards support various widget types that can be added to display different types of content and visualizations. Each widget type has specific configuration options, size constraints, and use cases. ## Widget Categories Widgets are organized into three categories: * **Reports**: Widgets that display reports (charts, tables, KPIs) * **Data Grids**: Widgets that display datagrids (Object data tables) * **Standard Widgets**: Built-in widgets for various purposes (Summary, Webpage, Image, Quick Action, Insight Card, Layout, Actionable Card) ## Report Widget Displays reports created in the Reports section. ### Overview Report widgets show report visualizations including charts, tables, KPIs, and other report types configured in the Reports section. ### Configuration * **Select Report**: Choose a report from the Reports list * **Widget Title**: Customize the widget title (optional, defaults to report name) * **Report Settings**: Configure report-specific settings (if enabled) ### Size Constraints * **Default Size**: 6 columns wide × 4 rows high * **Minimum Size**: 4 columns × 4 rows * **Maximum Size**: 12 columns × 12 rows * **KPI Reports**: Automatically sized to 2 columns wide when chart type is KPI ### Use Cases * Display charts and visualizations * Show KPI metrics * Display data tables from reports * Visualize aggregated data ### Features * Supports all report visualization types (Bar, Line, Pie, Table, KPI, etc.) * Can be filtered using dashboard global filters * Supports report-specific settings and interactions * Real-time data updates ## Datagrid Widget Displays datagrids created in the Datagrids section. ### Overview Datagrid widgets show Object data in table format using datagrid configurations created in the Datagrids section. ### Configuration * **Select Datagrid**: Choose a datagrid from the Datagrids list * **Widget Title**: Customize the widget title (optional, defaults to datagrid name) * **Datagrid Settings**: Configure datagrid-specific settings (if enabled) ### Size Constraints * **Default Size**: 6 columns wide × 8 rows high * **Minimum Size**: 4 columns × 8 rows * **Maximum Size**: 12 columns × 16 rows ### Use Cases * Display Object records in table format * Show filtered and sorted data * Display data with actions and drill-down capabilities * View related records ### Features * Supports all datagrid features (filtering, sorting, grouping, actions) * Can be filtered using dashboard global filters * Supports row actions and drill-down navigation * Real-time data updates ## Summary Ribbon Widget Displays a horizontal ribbon of KPI metrics from multiple reports. ### Overview Summary Ribbon widgets aggregate KPI values from multiple KPI reports into a single horizontal ribbon display, showing key metrics at a glance. ### Configuration * **Widget Title**: Enter a title for the summary ribbon * **Select KPI Reports**: Choose one or more KPI reports to display * **Report Selection**: Select from available KPI reports (reports with chart type "KPI") ### Size Constraints * **Default Size**: 12 columns wide × 4 rows high (full width) * **Minimum Size**: 4 columns × 2 rows * **Maximum Size**: 12 columns × 6 rows ### Use Cases * Display key performance indicators at the top of dashboards * Show summary metrics from multiple sources * Provide quick overview of important metrics * Display variance and goal comparisons ### Features * Aggregates multiple KPI reports * Shows KPI values with icons * Displays variance (if configured in KPI reports) * Shows goal comparisons * Customizable title and layout ## Webpage Widget Embeds external web pages within the dashboard. ### Overview Webpage widgets display external web pages in an iframe, allowing you to embed third-party content, documentation, or other web resources. ### Configuration * **URL**: Enter the URL of the webpage to display * **URL Validation**: System validates URL format ### Size Constraints * **Default Size**: 6 columns wide × 8 rows high * **Minimum Size**: 6 columns × 8 rows * **Maximum Size**: 12 columns × 12 rows ### Use Cases * Embed external documentation * Display third-party dashboards * Show web-based tools or applications * Include reference materials ### Features * Supports HTTPS and HTTP URLs * Handles iframe restrictions (X-Frame-Options) * Error handling for inaccessible pages * Responsive sizing ### Limitations * Some websites block iframe embedding (X-Frame-Options header) * Cross-origin restrictions may apply * Requires internet connectivity for external URLs ## Image Widget Displays images uploaded to the system. ### Overview Image widgets display images that have been uploaded to the system, allowing you to add visual content to dashboards. ### Configuration * **Upload Image**: Upload an image file or select an existing image * **Image Alt Text**: Enter alternative text for accessibility * **Image Fit**: Choose how the image fits in the widget: * **Contain**: Image fits within bounds, maintaining aspect ratio * **Cover**: Image covers entire area, may be cropped * **Fill**: Image fills area, may be stretched ### Size Constraints * **Default Size**: 4 columns wide × 4 rows high * **Minimum Size**: 2 columns × 2 rows * **Maximum Size**: 12 columns × 12 rows ### Use Cases * Display logos or branding * Show diagrams or charts * Include instructional images * Add visual context to dashboards ### Features * Image upload and management * Multiple image fit options * Responsive sizing * Image preview ## Quick Action Widget Provides quick navigation buttons to Builder pages. ### Overview Quick Action widgets display buttons that navigate to Builder pages, providing quick access to frequently used pages or workflows. ### Configuration * **Select Pages**: Choose one or more Builder pages to display as action buttons * **Page Selection**: Select from available Builder pages * **Alignment**: Choose button layout: * **Horizontal**: Buttons arranged in a row * **Vertical**: Buttons arranged in a column ### Size Constraints * **Default Size**: 8 columns wide × 6 rows high * **Minimum Size**: 2 columns × 4 rows * **Maximum Size**: 12 columns × 8 rows ### Use Cases * Provide quick access to frequently used pages * Create navigation shortcuts * Display workflow entry points * Show action buttons for common tasks ### Features * Multiple page selection * Customizable button layout * Page icons and descriptions displayed * Direct navigation to pages ## Insight Card Widget Displays a list of values from an Object field, showing recent or top records. ### Overview Insight Card widgets display a list of values from a specific field in an Object, sorted and limited to show the most relevant records. ### Configuration * **Widget Title**: Enter a title for the insight card * **Select Object**: Choose the Object to query * **Select Field**: Choose the field to display values from * **Icon**: Select an icon to represent the insight * **Limit**: Set the maximum number of values to display (default: 5) * **Sort Order**: Choose sorting: * **Ascending (ASC)**: Lowest to highest * **Descending (DESC)**: Highest to lowest * **Order By Field**: Select the field to sort by (typically the same as the display field) ### Size Constraints * **Default Size**: 4 columns wide × 4 rows high * **Minimum Size**: 2 columns × 2 rows * **Maximum Size**: 12 columns × 12 rows ### Use Cases * Display top customers * Show recent activities * List most popular items * Display trending values ### Features * Queries Object data directly * Supports sorting and limiting * Can be filtered using dashboard global filters * Displays field values as a list * Customizable icon and title ## Layout Widget Displays layouts created in the Layouts section. ### Overview Layout widgets display Simple Layouts created in the Layouts section, showing Object records in a form-like layout. ### Configuration * **Widget Title**: Enter a title for the layout widget * **Select Layout**: Choose a Simple Layout from the Layouts list * **Icon**: Select an icon to represent the layout ### Size Constraints * **Default Size**: 4 columns wide × 4 rows high * **Minimum Size**: 2 columns × 2 rows * **Maximum Size**: 12 columns × 12 rows ### Use Cases * Display Object records in a form layout * Show detailed record views * Display related records * Create custom data views ### Features * Displays Simple Layout configurations * Shows Object records with field groups * Supports layout-specific styling * Can be filtered using dashboard global filters ## Actionable Card Widget Displays Object records as cards with action buttons. ### Overview Actionable Card widgets display Object records as cards, each showing key information and action buttons that trigger workflows or flow chains. ### Configuration * **Card Name**: Enter a name for the actionable card widget * **Select Object**: Choose the Object to display records from * **Description**: Optional description * **Icon**: Select an icon for the card * **Field Configuration**: * **Primary Field**: Field to display as the main value * **Status Field**: Field to display as status indicator * **Secondary Field**: Additional field to display * **Query Configuration**: Configure which records to display: * **Select Fields**: Choose fields to retrieve * **Filter Criteria**: Define filter conditions * **Sort Order**: Set sorting options * **Limit**: Maximum number of records to display * **Actions**: Configure action buttons: * **Primary Action**: Main action button (FLOW or FLOW\_CHAIN) * **Secondary Action**: Additional action button (FLOW or FLOW\_CHAIN) * **Action Title**: Button label * **Action Icon**: Button icon * **Target**: Select workflow or flow chain to execute ### Size Constraints * **Default Size**: 4 columns wide × 4 rows high * **Minimum Size**: 2 columns × 2 rows * **Maximum Size**: 12 columns × 12 rows ### Use Cases * Display records with quick actions * Show task lists with action buttons * Display items requiring user action * Create interactive record displays ### Features * Displays Object records as cards * Supports multiple action buttons per card * Configurable field display * Action buttons trigger workflows or flow chains * Can be filtered using dashboard global filters * Supports implicit filters for actions ## Widget Size Guidelines ### Understanding Grid Units Dashboards use a grid system where: * **Columns**: Horizontal grid units (typically 12 columns per row) * **Rows**: Vertical grid units (height varies based on content) ### Size Recommendations * **Small Widgets** (2-4 columns): Quick actions, KPIs, insight cards * **Medium Widgets** (6-8 columns): Reports, datagrids, webpages * **Large Widgets** (10-12 columns): Full-width summaries, comprehensive reports ### Responsive Behavior * Widgets automatically adjust to available space * Minimum and maximum sizes prevent widgets from becoming too small or too large * Grid layout ensures widgets align properly ## Best Practices ### Widget Selection * **Choose Appropriate Widgets**: Select widget types that match your data and use case * **Mix Widget Types**: Combine different widget types for comprehensive dashboards * **Consider Size**: Plan widget sizes based on content and importance ### Widget Configuration * **Meaningful Titles**: Use clear, descriptive titles for widgets * **Appropriate Sizing**: Size widgets to fit content without wasting space * **Consistent Layout**: Maintain consistent widget sizes and alignment ### Performance * **Limit Widget Count**: Avoid too many widgets (typically 4-8 widgets per dashboard) * **Efficient Queries**: Configure widgets with efficient queries and filters * **Data Volume**: Consider data volume when configuring widgets ### User Experience * **Logical Grouping**: Group related widgets together * **Visual Hierarchy**: Place important widgets in prominent positions * **Clear Labels**: Use clear titles and descriptions ## Related Introduction * [Creating Dashboards](/mbrix/dashboard/creating-dashboards) - Learn how to add widgets to dashboards * [Dashboard Introduction](/mbrix/dashboard) - Overview of dashboards * [Reports Introduction](/mbrix/reports) - Learn about reports used as widgets * [Datagrids Introduction](/mbrix/datagrids) - Understand datagrids used as widgets * [Layouts Introduction](/mbrix/layouts) - Learn about layouts used as widgets --- # Dashboard Introduction URL: /mbrix/dashboard Learn about Dashboards - customizable interfaces that combine multiple widgets and visualizations *** title: Dashboard Introduction description: Learn about Dashboards - customizable interfaces that combine multiple widgets and visualizations -------------------------------------------------------------------------------------------------------------- # Dashboards Dashboards are customizable interfaces that combine multiple widgets (reports, datagrids, charts, etc.) into a single view. They provide a unified way to display and interact with data from multiple sources, enabling comprehensive data visualization and analysis. ## What are Dashboards? Dashboards enable you to: * **Combine Multiple Widgets**: Display reports, datagrids, charts, and other components in a single view * **Organize Layout**: Arrange widgets using a drag-and-drop grid layout system * **Apply Global Filters**: Configure filters that affect all widgets on the dashboard * **Customize Appearance**: Configure themes and layout settings * **Organize in Folders**: Organize dashboards in folders for better management * **Share Insights**: Create comprehensive views for stakeholders and decision-makers ## How Dashboards Work ### Widget-Based Architecture Dashboards are built using widgets: * **Widget Types**: Reports, datagrids, charts, KPIs, and other visualization components * **Grid Layout**: Widgets are positioned using a grid layout system (x, y coordinates, width, height) * **Responsive Design**: Widgets can be resized and repositioned to fit different screen sizes * **Independent Data Sources**: Each widget can display data from different Objects or sources ### Global Filters Dashboards support global filters that can be applied across all widgets: * **Filter Configuration**: Define filters using field conditions and expressions * **Widget Mapping**: Map filter fields to widget-specific fields * **Join Information**: Configure how filters apply when widgets use different Objects * **Dynamic Filtering**: Filters update all widgets in real-time when changed ## Dashboard Components ### Widgets Widgets are the building blocks of dashboards: * **Reports**: Display report visualizations (charts, tables, KPIs) * **Datagrids**: Show Object data in table format * **Charts**: Display various chart types (bar, line, pie, etc.) * **KPIs**: Show key performance indicators * **Custom Components**: Other custom visualization components ### Filters Global filters that apply to all widgets: * **Filter Fields**: Fields from Objects used for filtering * **Filter Criteria**: Conditions and expressions that define filter logic * **Widget Mappings**: How filter fields map to widget-specific fields * **Join Information**: Relationships between Objects for cross-object filtering ### Layout Grid-based layout system: * **Grid Positions**: Widgets positioned using x, y coordinates * **Widget Sizes**: Width (w) and height (h) in grid units * **Resizing**: Widgets can be resized within minimum and maximum constraints * **Drag and Drop**: Widgets can be repositioned by dragging ## Key Features ### Widget Management * **Add Widgets**: Add multiple widgets to a dashboard * **Remove Widgets**: Remove widgets that are no longer needed * **Resize Widgets**: Adjust widget sizes to fit content * **Reposition Widgets**: Move widgets to different positions * **Configure Widgets**: Set individual widget properties and settings ### Filter Management * **Global Filters**: Apply filters that affect all widgets * **Filter Mapping**: Map filter fields to widget-specific fields * **Dynamic Updates**: Filters update widgets in real-time * **Complex Conditions**: Support complex filter expressions and joins ### Organization * **Folders**: Organize dashboards in folders * **Search**: Search dashboards by name * **Cloning**: Clone existing dashboards to create similar ones * **Audit History**: Track changes to dashboards ## Using Dashboards Dashboards can be: * **Created**: Build new dashboards with widgets and filters * **Edited**: Modify widget layout, filters, and settings * **Viewed**: Display dashboards with live data * **Cloned**: Duplicate dashboards for variations * **Deleted**: Remove dashboards that are no longer needed * **Embedded**: Embed dashboards in Builder pages * **Shared**: Share dashboards with team members ## Getting Started 1. **[Creating Dashboards](/mbrix/dashboard/creating-dashboards)**: Learn how to create dashboards with step-by-step instructions 2. **[Dashboard Widget Types](/mbrix/dashboard/dashboard-widget-types)**: Learn about all available widget types and their configurations 3. **[Configuring Dashboard Filters](/mbrix/dashboard/configuring-dashboard-filters)**: Learn how to configure global filters for dashboards 4. **Add Widgets**: Add reports, datagrids, and other widgets to your dashboard 5. **Configure Filters**: Set up global filters that affect all widgets 6. **Arrange Layout**: Position and resize widgets for optimal display 7. **Save and View**: Save your dashboard and view it with live data ## Related Introduction * [Creating Dashboards](/mbrix/dashboard/creating-dashboards) - Step-by-step guide to creating dashboards * [Dashboard Widget Types](/mbrix/dashboard/dashboard-widget-types) - Detailed guide to all widget types * [Configuring Dashboard Filters](/mbrix/dashboard/configuring-dashboard-filters) - Detailed guide to configuring dashboard filters * [Reports Introduction](/mbrix/reports) - Learn about reports used as dashboard widgets * [Datagrids Introduction](/mbrix/datagrids) - Understand datagrids used as dashboard widgets * [Layouts Introduction](/mbrix/layouts) - Learn about layouts used as dashboard widgets * [Builder Introduction](/mbrix/builder) - Learn how to embed dashboards in Builder pages * [Objects Introduction](/mbrix/mobjects) - Understand the data sources used in dashboards --- # Creating Form Chains URL: /mbrix/form-chaining/creating-form-chains *** ## title: Creating Form Chains Form chains are created using the Form Chaining interface. Each form chain consists of multiple steps that execute in sequence, with the ability to pass data between steps. ## Required Information * **Name**: Unique identifier for the form chain (required) * **Description**: Optional description explaining the form chain's purpose * **Steps**: At least one step must be configured (required) ## Configuration Steps Form Chain Configuration Steps Interface ### 1. Open Form Chain Creation Dialog Navigate to the Form Chaining page and click the **"Form Chaining"** button (with plus icon) to open the creation dialog. ### 2. Enter Form Chain Name Provide a unique name for the form chain. This name will be used to identify the form chain throughout the system. ### 3. Add Steps Click the **"Add Step"** button to add steps to your form chain. Each step represents one form or datagrid in the sequence. ### 4. Configure Each Step For each step, configure the following: #### Select Step Type Choose the type of step: * **FLOW**: A workflow (MFlow) that displays a form * **GRID**: A datagrid (MDataGrid) that displays records #### Select Flow or Grid Based on the selected step type, choose the specific item: * **For FLOW steps**: Select a workflow (MFlow) from the dropdown * **For GRID steps**: Select a datagrid (MDataGrid) from the dropdown **Note**: When you change the step type, the selected flow/grid is cleared and must be reselected. #### Enter Step Name Provide a descriptive name for the step. This name will be displayed to users when executing the form chain. **Auto-generation**: If you don't enter a step name, it will be auto-generated from the selected flow or grid name. You can override this with a custom name. #### Configure Lookup ID (Optional) For both FLOW and GRID steps, you can optionally configure a lookup field ID. This is used to filter data based on previous step output. **How it works**: * For GRID steps: The lookup field filters the datagrid to show only records matching the previous step's output * For FLOW steps: The lookup field can be used to pass specific fields from previous output After selecting a flow or grid, available fields will appear in the Lookup ID dropdown. Select the field you want to use for filtering. **Note**: Lookup fields are automatically fetched when you select a flow or grid. #### Configure Use Previous Output Toggle whether this step should use the previous step's output as input. **How it works**: * When enabled: The output from the previous step is passed as input to this step * When disabled: The step uses its own configured input or no input **Note**: The first step cannot use previous output (toggle is disabled). ### 5. Reorder Steps Steps are executed in the order they appear in the table. You can reorder steps using drag and drop: 1. Click and hold the **drag handle** (grip icon) on the left side of a step row 2. Drag the step to the desired position 3. Release to drop the step in the new position **How it works**: The display order is automatically updated when you reorder steps. Steps execute sequentially from top to bottom. ### 6. Remove Steps To remove a step from the form chain: 1. Click the **delete icon** (trash icon) in the "Actions" column 2. The step is immediately removed from the table **Note**: After removing a step, the display order of remaining steps is automatically recalculated. ### 7. Save Form Chain Click the **"Create"** button to save the form chain. The system will validate: * Name is provided * At least one step exists * All steps have a flow or grid selected (based on step type) * All steps have a step name **After saving**: * The form chain is created and appears in the Form Chaining list * The form chain can be edited, executed, or deleted as needed * The form chain can be used in Builder pages as a widget ## Editing Existing Form Chains To edit an existing form chain: 1. Navigate to the Form Chaining page 2. Find the form chain in the list 3. Click the **"Edit"** icon (or click on the form chain name) in the actions dropdown 4. The form chain creation dialog will open with existing configuration 5. Make your desired changes to steps, step order, or configuration 6. Click **"Save"** to apply updates **Note**: When editing, all existing steps are loaded with their current configuration. You can add, remove, or reorder steps as needed. ## Step Configuration Details ### FLOW Steps FLOW steps execute workflows (MFlows) that display forms: * **Purpose**: Collect data from users through forms * **Input**: Can receive input from previous step output (if enabled) * **Output**: Produces output data that can be passed to the next step * **Lookup ID**: Optional field to filter or map specific fields from previous output ### GRID Steps GRID steps display datagrids (MDataGrids) showing records: * **Purpose**: Display and review data in a table format * **Input**: Can receive input from previous step output (if enabled) * **Lookup ID**: Used to filter the datagrid based on previous step output * **Use Case**: Review records related to data created in previous steps ### Data Flow Between Steps When "Use previous output as input" is enabled: 1. **Step 1 executes** and produces output (e.g., `{ orderId: "123", customerId: "456" }`) 2. **Step 2 receives** this output as input 3. **If Step 2 has a Lookup ID** configured (e.g., `orderId`), it uses that field to filter or map data 4. **Step 2 processes** the input and produces its own output 5. **Step 3 receives** Step 2's output, and so on This enables complex workflows where each step builds upon the previous step's results. ## Best Practices ### Naming Conventions * Use descriptive names that clearly indicate the form chain's purpose * Include context in the name (e.g., "Order Processing Chain" instead of "Chain 1") * Use consistent naming patterns across related form chains ### Step Names * Use clear, user-friendly step names that indicate what users will do * Avoid technical jargon in step names * Keep step names concise but descriptive ### Step Ordering * Order steps logically based on the workflow process * Place data collection steps before review/verification steps * Consider user experience when ordering steps ### Data Flow * Enable "Use previous output as input" for steps that need data from previous steps * Configure Lookup ID fields for GRID steps to filter related records * Test data flow between steps to ensure proper data passing ### Step Types * Use FLOW steps for data entry and user interactions * Use GRID steps for data review and verification * Mix FLOW and GRID steps to create comprehensive workflows ### Validation * Ensure all steps have valid flows or grids selected * Verify that lookup fields exist in the target flow/grid * Test form chains before deploying to production ## Related Introduction * [Form Chaining Introduction](/mbrix/form-chaining) - Overview of form chaining * [Workflows Introduction](/mbrix/workflows) - Learn about workflows used as form chain steps * [Datagrids Introduction](/mbrix/datagrids) - Understand datagrids used as form chain steps * [Builder Introduction](/mbrix/builder) - Learn how to use form chains in Builder pages --- # Form Chaining Introduction URL: /mbrix/form-chaining *** ## title: Form Chaining Introduction Form Chaining (also known as Flow Chain or Multiform) allows you to create sequences of forms and datagrids that execute in order. Each step can pass its output as input to the next step, enabling complex multi-step workflows and data collection processes. ## What is Form Chaining? Form Chaining enables you to: * **Chain Multiple Steps**: Link workflows (forms) and datagrids together in a sequence * **Pass Data Between Steps**: Use output from one step as input to the next step * **Create Multi-Step Processes**: Build complex workflows that require multiple user interactions * **Combine Forms and Grids**: Mix form-based steps with datagrid steps in a single chain * **Configure Lookup Fields**: Set up lookup fields for datagrid steps to filter related data ## How Form Chaining Works ### Step Types Each step in a form chain can be one of two types: * **FLOW**: A workflow (MFlow) that displays a form for data entry or processing * **GRID**: A datagrid (MDataGrid) that displays records in a table format ### Step Configuration Each step includes: * **Step Name**: A descriptive name for the step * **Step Type**: FLOW or GRID * **Target**: The specific workflow or datagrid to execute * **Use Previous Output**: Whether to use the previous step's output as input * **Lookup Field**: For GRID steps, a lookup field to filter records (optional) * **Display Order**: The order in which steps are executed ### Data Flow When steps are configured to use previous output: 1. **Step 1 executes** and produces output data 2. **Step 2 receives** the output from Step 1 as input 3. **Step 2 processes** the input and produces its own output 4. **Step 3 receives** the output from Step 2, and so on This enables data to flow through the chain, allowing each step to build upon the previous step's results. ## Use Cases ### Multi-Step Data Collection Collect data across multiple forms: * **Step 1**: Customer information form * **Step 2**: Order details form (pre-filled with customer ID from Step 1) * **Step 3**: Payment information form ### Form Followed by Data Review Submit a form and then review related records: * **Step 1**: Create order form * **Step 2**: View order items datagrid (filtered by order ID from Step 1) ### Sequential Approvals Multi-step approval processes: * **Step 1**: Submit request form * **Step 2**: Manager approval form * **Step 3**: Final approval form ### Data Entry and Verification Enter data and verify in a grid: * **Step 1**: Data entry form * **Step 2**: Verification datagrid showing entered records ## Form Chain Structure Each form chain consists of: * **Name**: Unique identifier for the form chain * **Description**: Optional description explaining the chain's purpose * **Configuration**: Array of steps that define the sequence * **Component Type**: Set to "FLOW\_CHAIN" to identify it as a form chain ## Using Form Chaining Form chains can be: * **Created**: Define a new form chain with multiple steps * **Edited**: Modify existing form chains and their step configurations * **Executed**: Run form chains to guide users through multi-step processes * **Used in Pages**: Display form chains as widgets in Builder pages * **Triggered from Datagrids**: Execute form chains as actions from datagrid rows ## Getting Started 1. **[Creating Form Chains](/mbrix/form-chaining/creating-form-chains)**: Learn how to create form chains with step-by-step instructions 2. **Configure Steps**: Add FLOW and GRID steps to your chain 3. **Set Data Flow**: Configure how data passes between steps 4. **Test Execution**: Test your form chain to ensure proper data flow ## Related Introduction * [Workflows Introduction](/mbrix/workflows) - Learn about workflows used as form chain steps * [Datagrids Introduction](/mbrix/datagrids) - Understand datagrids used as form chain steps * [Builder Introduction](/mbrix/builder) - Learn how to use form chains in Builder pages --- # Configuring Grid Actions URL: /mbrix/datagrids/configuring-actions *** ## title: Configuring Grid Actions The Grid Actions configuration dialog allows you to configure three main aspects of your datagrid: Actions, Drill-down, and General Settings. Each is organized in separate tabs for easy management.
Actions Tab Interface

Configure actions that can be triggered from the datagrid. Actions are divided into two types:

Action Types

  • Header Actions: Actions available at the grid level, displayed in the grid header
  • Row Actions: Actions available for each individual record row

Action Configuration

For each action, configure the following:

Action Name

A descriptive name for the action that will be displayed to users.

Icon

Select an icon to represent the action visually. Icons help users quickly identify action types.

Action Trigger

Choose how the action is triggered:

  • FORM: Open a form for creating or editing records
  • FLOW: Trigger a workflow with the selected record
  • FLOW\_CHAIN: Execute a flow chain
  • DOWNLOAD: Download data or files

Target

Select the specific target for the action:

  • For FORM: Choose the Form to open
  • For FLOW: Choose the workflow to execute
  • For FLOW\_CHAIN: Choose the flow chain to execute
  • For DOWNLOAD: Configure download parameters

Lookup Field

Specify which field from the current record should be passed to the target. This is useful for:

  • Passing record IDs to workflows
  • Pre-filling forms with record data
  • Filtering drill-down views based on selected records

Action Management

  • Add Action: Click to add a new action (Header or Row type)
  • Reorder Actions: Drag and drop actions to change their order
  • Remove Action: Delete actions that are no longer needed
Drill-Down Tab Interface

Configure drill-down links that allow users to navigate to related pages or detailed views when clicking on specific columns.

Enable Drill-Down

Toggle the switch to enable or disable drill-down functionality for the datagrid.

Drill-Down Types

Configure drill-down definitions with the following options:

  • Report: Navigate to another report/datagrid
  • Layout360: Navigate to a Layout360 view
  • Mixed Layout: Navigate to a mixed layout
  • Dashboard: Navigate to a dashboard page
  • Work Flow: Navigate to a workflow
  • My Tasks: Navigate to user tasks

Drill-Down Configuration

For each drill-down definition:

  1. Select Field: Choose the column field that will trigger the drill-down
  2. Select Type: Choose the drill-down target type (Report, Layout360, etc.)
  3. Select Target: Choose the specific target asset (report, layout, workflow, etc.)
  4. Configure Filter Mapping: Map fields from the current grid to filter the drill-down target

Multiple Drill-Down Definitions

You can configure multiple drill-down definitions for different fields, allowing different columns to navigate to different targets.

General Settings Tab Interface

Configure additional settings that affect the overall behavior of the datagrid.

Sort Options

Define the default sort order for the grid:

  1. Add Sort Fields: Add one or more fields to sort by
  2. Select Field: Choose the field to sort by
  3. Select Order: Choose ascending (ASC) or descending (DESC) order
  4. Multiple Sorts: Add multiple sort fields for complex sorting (sorts are applied in order)

Settings

Configure additional grid settings:

Hide Chat View

Toggle to hide or show the chat view in the datagrid interface.

Select Flow

Associate a workflow with the datagrid. This workflow can be triggered from various grid interactions.

Enable Custom Headers

Toggle to enable custom column headers. When enabled, you can customize header text and formatting.

## Best Practices ### Actions * **Limit Actions**: Keep the number of actions manageable to avoid cluttering the interface * **Clear Names**: Use descriptive action names that clearly indicate what the action does * **Logical Ordering**: Order actions by frequency of use or logical grouping * **Appropriate Icons**: Choose icons that match the action's purpose ### Drill-Down * **Relevant Fields**: Configure drill-down only on fields that logically lead to related data * **Filter Mapping**: Properly map fields to ensure drill-down views show relevant filtered data * **User Expectations**: Ensure drill-down targets match user expectations for navigation ### General Settings * **Default Sort**: Set a default sort that makes the most common use case efficient * **Flow Association**: Associate workflows that enhance the datagrid's functionality * **Custom Headers**: Use custom headers to improve readability for business users ## Related Introduction * [Creating Datagrids](/mbrix/datagrids/creating-datagrids) - Learn how to create datagrids * [Datagrids Introduction](/mbrix/datagrids) - Overview of datagrids * [Workflows Introduction](/mbrix/workflows) - Learn about workflows used in actions * [Objects Introduction](/mbrix/mobjects) - Understand Objects displayed in datagrids --- # Creating Datagrids URL: /mbrix/datagrids/creating-datagrids *** ## title: Creating Datagrids Datagrids are created using the Datagrid Designer interface. Each datagrid is linked to an Object and displays its records in a table format with filtering, sorting, and action capabilities. ## Required Information * **Name**: Unique identifier for the datagrid * **Description**: Optional description * **Object**: The Object whose data will be displayed ## Configuration Steps Datagrid Configuration Interface ### 1. Select Object Choose the Object that contains the data you want to display in the grid. All fields from this Object will be available for selection. ### 2. Select Fields Choose which fields to display in the grid. In the designer interface, you'll see a "Show Fields" drag-and-drop area where you can: * **Regular Fields**: Standard Object fields * **Formula Fields**: Calculated fields using expressions **How to add fields**: Drag fields from the field tree on the left side and drop them into the "Show Fields" section. #### Creating Formula Fields
Creating Formula Fields Formula Fields Configuration
To create a formula field: 1. Use the **Field Builder** component available in the designer interface 2. Click to create a new formula field 3. Enter an expression using other fields, constants, and operators 4. The formula field will be added to your available fields and can be dragged into "Show Fields" Formula fields allow you to create calculated columns based on expressions involving other fields in your Object. ### 3. Set Up Grouping (Optional) Below the "Show Fields" area, you'll find a "Group by" drag-and-drop section. **How to group**: Drag fields from the field tree into the "Group By" section. When you group by fields: * Records are organized hierarchically by the grouped fields * Non-grouped fields can use aggregation functions (SUM, COUNT, AVG, etc.) * The grid displays grouped rows with expand/collapse functionality **Note**: You can group by multiple fields for hierarchical grouping. ### 4. Configure Quick Filters Below the "Group by" section, you'll find a "Quick Filters" drag-and-drop area. **How to add quick filters**: Drag fields from the field tree into the "Quick Filters" section. These filters will: * Appear above the grid as filter inputs for easy access * Allow users to quickly filter records without opening advanced filter dialogs * Support common filter operations (contains, equals, greater than, etc.) **Configuring filter display**: Each quick filter field has a "Show as Quick Filter" option that controls whether it appears above the grid. ### 4.5. Configure Field Settings (Optional) Each field in the "Show Fields" section has configurable settings. Click the settings icon next to any field to configure: * **Display Name**: Custom column header text (overrides the default field label) * **Hide Column**: Toggle to hide the column from the grid (useful for fields used in calculations but not displayed) * **Column Width**: Resize columns directly in the preview pane - widths are saved automatically * **Data Orientation**: Set alignment for cell content (Left, Center, Right) * **Header Orientation**: Set alignment for header text (Left, Center, Right) * **Show as Tags**: For picklist fields, display values as tags instead of plain text **Column Resizing**: You can resize columns directly in the preview pane by dragging the column borders. The column widths are automatically saved when you save the datagrid. ### 5. Include Soft Deleted Records (Optional) Toggle the "Include Soft Deleted" switch to include or exclude soft-deleted records in the grid. When enabled, records that have been soft-deleted (marked as deleted but not permanently removed) will appear in the grid results. ### 6. Configure Actions (Optional) Add actions that can be triggered from the grid: * **Header Actions**: Actions available at the grid level * **Row Actions**: Actions available for each record row Actions can trigger forms, workflows, flow chains, or downloads. ### 7. Configure Drill-Down (Optional) Set up drill-down links to navigate to related pages or detailed views when clicking on specific columns. ### 8. General Settings Configure additional settings: * **Sort Options**: Define default sort order using order by fields * **Hide Chat View**: Toggle chat view visibility * **Custom Headers**: Enable custom column headers * **Flow**: Associate a workflow with the datagrid ### 9. Save Datagrid Provide a name and description, optionally select a folder for organization, and save the datagrid. ## UI Layout The datagrid designer has three main drag-and-drop areas stacked vertically: 1. **Show Fields** (top): Fields to display as columns in the grid 2. **Group by** (middle): Fields to group records by 3. **Quick Filters** (bottom): Fields to show as quick filter inputs above the grid All three areas use the same drag-and-drop mechanism - drag fields from the field tree on the left and drop them into the appropriate section. ## Field Types ### Regular Fields Standard fields from the selected Object. These display actual data values from records. ### Formula Fields Calculated fields that use expressions to compute values based on other fields or constants. ## Quick Filters Quick filters are fields that appear as filter inputs above the grid: * **Easy Access**: Users can filter records without opening dialogs * **Common Filters**: Best for frequently used filter fields * **Show/Hide**: Each field has a "Show as Quick Filter" option to control visibility * **Filter Operations**: Supports various operations like contains, equals, greater than, less than, etc. **How it works**: When you drag a field into the "Quick Filters" section, it becomes available as a filter input above the grid. Users can enter values directly in these inputs to filter the displayed records. ## Grouping Group records by fields to organize data hierarchically: * **Single Field Grouping**: Group by one field to organize records by that field's values * **Multiple Field Grouping**: Group by multiple fields for nested hierarchical organization * **Aggregations**: When grouping, non-grouped fields can use aggregation functions (SUM, COUNT, AVG, MIN, MAX) * **Expand/Collapse**: Grouped rows can be expanded or collapsed to show/hide detail records **How it works**: When you drag fields into the "Group by" section, the grid organizes records by those fields. The grid displays grouped rows that can be expanded to show individual records within each group. ## Field Settings Each field in your datagrid can be customized with various settings: ### Display Name Override the default field label with a custom column header. This is useful for: * Making technical field names more user-friendly * Providing context-specific labels * Localizing column headers ### Hide Column Hide columns from the grid while keeping them available for: * Calculations in formula fields * Filtering purposes * Grouping operations Hidden columns are still part of the datagrid configuration but are not visible to users. ### Column Width Columns can be resized directly in the preview pane: * Drag the column border to adjust width * Widths are automatically saved when you save the datagrid * Useful for optimizing the display of different data types ### Data and Header Orientation Control the alignment of content and headers: * **Left**: Default for text fields * **Center**: Useful for centered content * **Right**: Default for numbers and currency (data orientation) ### Show as Tags (Picklist Fields) For picklist fields, you can display values as tags instead of plain text: * Makes multi-select picklist values more visually distinct * Improves readability for fields with multiple values * Tags are color-coded for better visual organization ## Editing Existing Datagrids To edit an existing datagrid: 1. Navigate to the datagrid list 2. Click the **Edit** button for the datagrid you want to modify 3. Make your changes in the designer interface 4. Click **Save** to update the datagrid All changes are saved to the existing datagrid configuration. ## Related Introduction * [Datagrids Introduction](/mbrix/datagrids) - Overview of datagrids * [Configuring Actions](/mbrix/datagrids/configuring-actions) - Learn how to configure grid actions, drill-down, and settings * [Objects Introduction](/mbrix/mobjects) - Understand Objects and their fields * [Workflows Introduction](/mbrix/workflows) - Learn about workflows used in datagrid actions --- # Datagrids Introduction URL: /mbrix/datagrids *** ## title: Datagrids Introduction Datagrids are interactive table views that display Object data in a structured grid format. They provide filtering, sorting, grouping, and action capabilities for managing records efficiently. ## What are Datagrids? Datagrids are visual components that: * **Display Object Data**: Show records from an Object in a table format * **Enable Filtering**: Filter records using quick filters and advanced filters * **Support Grouping**: Group records by fields for better organization * **Provide Actions**: Execute actions on records (forms, flows, downloads) * **Enable Drill-Down**: Navigate to related data through drill-down links ## Key Features ### Field Selection Choose which fields from the Object to display in the grid. Fields can be: * Regular Object fields * Formula fields (calculated expressions) ### Filtering Filter records using: * **Quick Filters**: Common filters displayed above the grid * **Advanced Filters**: Complex filter conditions * **Soft Deleted Records**: Option to include or exclude deleted records ### Grouping Group records by one or more fields to organize data hierarchically. ### Actions Configure actions that can be triggered from the grid: * **Header Actions**: Actions available at the grid level (Type: HEADER) * **Row Actions**: Actions available for each row (Type: ROW) **Action Types:** * **FORM**: Open a form for creating or editing records * **FLOW**: Trigger a workflow with the selected record * **FLOW\_CHAIN**: Execute a flow chain * **DOWNLOAD**: Download data or files ### Drill-Down Configure drill-down links to navigate to related pages or detailed views when clicking on specific columns. ### Sorting Define default sort order for the grid using order by fields. ## Datagrid Configuration Each datagrid includes: * **Name**: Unique identifier for the datagrid * **Description**: Optional description * **Object**: The Object whose data is displayed * **Fields**: Selected fields to display * **Filters**: Filter configurations * **Actions**: Grid and row actions * **Directory**: Optional folder for organization ## Using Datagrids Datagrids can be: * **Embedded in Pages**: Added as widgets to dashboard pages * **Standalone Views**: Accessed directly for data management * **Action Targets**: Used as destinations for workflow actions ## Getting Started 1. **[Creating Datagrids](/mbrix/datagrids/creating-datagrids)**: Learn how to create datagrids with fields, filters, and grouping 2. **[Configuring Actions](/mbrix/datagrids/configuring-actions)**: Configure actions, drill-down, and general settings 3. **Use in Pages**: Embed datagrids in dashboard pages as widgets ## Related Introduction * [Creating Datagrids](/mbrix/datagrids/creating-datagrids) - Step-by-step guide to creating datagrids * [Objects Introduction](/mbrix/mobjects) - Understand the data models displayed in datagrids * [Workflows Introduction](/mbrix/workflows) - Learn about workflows triggered from datagrid actions --- # Exporting Entities URL: /mbrix/import-export/exporting-entities Learn how to export Objects, MFlows, MReports, MForms, and MData to JSON files *** title: Exporting Entities description: Learn how to export Objects, MFlows, MReports, MForms, and MData to JSON files ------------------------------------------------------------------------------------------- # Exporting Entities Export allows you to export entities (Objects, MFlows, MReports, MForms, MData) to JSON files for backup, migration, or sharing. ## Export Types You can export the following entity types: * **Object**: Export Object definitions (schema, fields, relationships) * **MFlow**: Export workflow definitions and configurations * **MReport**: Export report configurations and queries * **MForm**: Export form definitions * **MData**: Export Object data records ## Export Options When exporting, you can choose what to include: ### RELATED (Default) Export the entity and all related entities. This includes: * **Objects**: Related Objects through lookup fields * **MFlows**: Related MFlows referenced in the workflow * **MReports**: Related Objects used in reports * **MForms**: Related Objects used in forms **Use Case**: Export complete configurations with dependencies ### ALONE Export only the selected entity without related entities. **Use Case**: Export standalone entities without dependencies ### RELATIONSHIP Export only the relationships between entities, not the entities themselves. **Use Case**: Export relationship mappings only ## Exporting Objects ### Step-by-Step 1. **Select Entity Type**: Choose "Object" from the dropdown 2. **Select Objects**: Use the typeahead to search and select Objects 3. **Multiple Selection**: You can select multiple Objects to export together 4. **Choose Export Option**: Select RELATED, ALONE, or RELATIONSHIP 5. **Custom Filename** (Optional): Enter a custom filename for the export 6. **Export**: Click "Export" button 7. **Download**: JSON file downloads automatically ### Exporting Multiple Objects When exporting multiple Objects: * All selected Objects are exported in a single JSON file * Related entities are included based on export option * File contains array of export results ## Exporting MFlows ### Step-by-Step 1. **Select Entity Type**: Choose "MFlow" from the dropdown 2. **Select MFlow**: Use the typeahead to search and select a workflow 3. **Choose Export Option**: Select RELATED, ALONE, or RELATIONSHIP 4. **Custom Filename** (Optional): Enter a custom filename 5. **Export**: Click "Export" button 6. **Download**: JSON file downloads automatically ## Exporting MReports ### Step-by-Step 1. **Select Entity Type**: Choose "Report" from the dropdown 2. **Select Report**: Use the typeahead to search and select a report 3. **Choose Export Option**: Select RELATED, ALONE, or RELATIONSHIP 4. **Custom Filename** (Optional): Enter a custom filename 5. **Export**: Click "Export" button 6. **Download**: JSON file downloads automatically ## Exporting MForms ### Step-by-Step 1. **Select Entity Type**: Choose "MForms" from the dropdown 2. **Select MForm**: Use the typeahead to search and select a form 3. **Choose Export Option**: Select RELATED, ALONE, or RELATIONSHIP 4. **Custom Filename** (Optional): Enter a custom filename 5. **Export**: Click "Export" button 6. **Download**: JSON file downloads automatically ## Exporting MData ### Step-by-Step 1. **Select Entity Type**: Choose "MData" from the dropdown 2. **Select Object**: Choose the Object whose data you want to export 3. **Select Data Records**: Select specific data records from the table 4. **Choose Export Option**: Select RELATED, ALONE, or RELATIONSHIP 5. **Custom Filename** (Optional): Enter a custom filename 6. **Export**: Click "Export" button 7. **Download**: JSON file downloads automatically ### MData Export Notes * **Data Selection**: You can select specific records or export all data * **Related Data**: Related MData through lookup fields can be included * **Data Format**: Exported as JSON array of records ## Export File Format Exported files are JSON format: ```json [ { "mainEntity": { ... }, "relatedEntities": [ ... ], "exportType": "MOBJECT", "exportOption": "RELATED" } ] ``` ### File Structure * **Array Format**: Multiple entities exported as JSON array * **Single Entity**: Single entity exported as single object in array * **Metadata**: Export type and option included in file ## Export Best Practices ### Before Exporting * **Verify Selection**: Double-check selected entities * **Check Dependencies**: Understand what related entities will be included * **Choose Appropriate Option**: Select export option based on use case * **Use Descriptive Filenames**: Use meaningful filenames for easy identification ### Export Options Selection * **RELATED**: Use when exporting complete configurations * **ALONE**: Use when exporting standalone entities * **RELATIONSHIP**: Use when exporting relationship mappings only ### File Management * **Organize Exports**: Keep exports organized by purpose * **Version Control**: Include version or date in filenames * **Document Exports**: Document what was exported and why ## Related Introduction * [Importing Entities](/mbrix/import-export/importing-entities) - Learn how to import exported entities * [Objects Introduction](/mbrix/mobjects) - Understand Objects that can be exported * [Workflows Introduction](/mbrix/workflows) - Learn about workflows that can be exported --- # Importing Entities URL: /mbrix/import-export/importing-entities Learn how to import entities from JSON files with conflict detection and resolution *** title: Importing Entities description: Learn how to import entities from JSON files with conflict detection and resolution ------------------------------------------------------------------------------------------------ # Importing Entities Import allows you to import entities from JSON export files back into the system. The import process includes automatic conflict detection and resolution options. ## Import Process Overview The import process consists of: 1. **File Upload**: Upload JSON export file 2. **Conflict Check**: System analyzes file for conflicts 3. **Conflict Review**: Review detected conflicts (if any) 4. **Conflict Resolution**: Resolve conflicts using resolution options 5. **Import Execution**: Import entities based on resolutions ## Importing Entities ### Step-by-Step 1. **Upload File**: Click "Choose File" and select JSON export file 2. **Start Import**: Click "Import" button 3. **Conflict Check**: System checks for conflicts automatically 4. **Review Conflicts**: Review detected conflicts (if any) 5. **Resolve Conflicts**: Choose resolution for each conflict 6. **Complete Import**: Import executes based on resolutions ## Conflict Detection The system automatically detects conflicts when importing: ### Conflict Types * **Field Addition**: New fields being added to existing Objects * **Field Deletion**: Fields being removed from existing Objects * **Field Update**: Field properties being changed in existing Objects ### Conflict Analysis The conflict check analyzes: * **Schema Differences**: Differences between import and existing schemas * **Field Changes**: Additions, deletions, and updates to fields * **Non-Conflicting Objects**: Objects that can be imported without conflicts ## Conflict Resolution When conflicts are detected, you can resolve them: ### Resolution Options #### Approve Changes Approve import changes and use import fields: * **Field Additions**: Add new fields from import * **Field Updates**: Update fields with import values * **Field Deletions**: Remove fields as specified in import **Use Case**: Accept all changes from import file #### Revert Changes Keep existing fields and use existing values: * **Field Additions**: Skip adding new fields * **Field Updates**: Keep existing field properties * **Field Deletions**: Keep existing fields **Use Case**: Keep existing configuration and skip changes #### Skip Objects Skip importing conflicting objects entirely: * **No Import**: Object is not imported * **Other Objects**: Other non-conflicting objects still import **Use Case**: Skip problematic objects ### Batch Resolution Resolve all conflicts at once: * **Approve All**: Approve all changes from import * **Revert All**: Keep all existing fields * **Individual Resolution**: Resolve conflicts individually ## Conflict Window The conflict window displays: ### Conflict Information * **Entity Type**: Type of entity with conflict * **Entity Name**: Name of the conflicting entity * **Conflict Type**: Type of conflict (addition, update, removal) * **Conflict Details**: Detailed information about the conflict ### Conflict Details For each conflict, you can see: * **Field Name**: Name of the field with conflict * **Field Type**: Type of the field * **Change Type**: What will change (addition, update, removal) * **From/To Values**: Current and import values ## Import Sessions Import sessions track import progress: ### Session Features * **Session ID**: Unique identifier for import session * **Conflict Analysis**: Stored conflict analysis * **Non-Conflicting IDs**: List of non-conflicting object IDs * **Expiration**: Sessions expire after 24 hours ### Session Usage * **Conflict Resolution**: Resolve conflicts using session ID * **Import Execution**: Import using session ID * **Progress Tracking**: Track import progress ## Non-Conflicting Import Objects without conflicts are imported automatically: * **Automatic Import**: Non-conflicting objects import immediately * **No Resolution Needed**: No resolution required for non-conflicting objects * **Import Count**: Number of imported objects shown ## Import Warnings Warnings may appear during import: * **Schema Warnings**: Warnings about schema differences * **Data Warnings**: Warnings about data issues * **Validation Warnings**: Warnings about validation failures ### Handling Warnings * **Review Warnings**: Review warning messages * **Continue Import**: Import continues despite warnings * **Address Issues**: Address warnings if needed ## Import Best Practices ### Before Importing * **Backup Data**: Backup existing data before importing * **Review Export File**: Review export file contents * **Check Conflicts**: Understand potential conflicts * **Test Import**: Test import in non-production environment first ### Conflict Resolution * **Review Carefully**: Review conflicts carefully before resolving * **Understand Impact**: Understand impact of resolution choices * **Use Batch Carefully**: Use batch resolution only when appropriate * **Document Resolutions**: Document resolution choices ### After Importing * **Verify Import**: Verify imported entities * **Check Relationships**: Verify relationships are correct * **Test Functionality**: Test functionality of imported entities * **Update Documentation**: Update documentation if needed ## Import Limitations ### Supported Entity Types * **Object**: Object definitions * **MFlow**: Workflow definitions * **MReport**: Report configurations * **MForm**: Form definitions * **MData**: Object data records ### Import Constraints * **File Format**: Must be valid JSON export file * **Entity Existence**: Entities must exist in target system (for updates) * **Schema Compatibility**: Schemas must be compatible * **Session Expiration**: Import sessions expire after 24 hours ## Related Introduction * [Exporting Entities](/mbrix/import-export/exporting-entities) - Learn how to export entities * [Objects Introduction](/mbrix/mobjects) - Understand Objects that can be imported * [Workflows Introduction](/mbrix/workflows) - Learn about workflows that can be imported --- # Import Export Introduction URL: /mbrix/import-export Learn about Import Export - exporting and importing entities (Objects, MFlows, MReports, MForms, MData) with conflict resolution *** title: Import Export Introduction description: Learn about Import Export - exporting and importing entities (Objects, MFlows, MReports, MForms, MData) with conflict resolution --------------------------------------------------------------------------------------------------------------------------------------------- # Import Export Import Export enables you to export entities (Objects, MFlows, MReports, MForms, MData) to JSON files and import them back into the system. This facilitates data migration, backup, sharing configurations, and moving entities between environments. ## What is Import Export? Import Export enables you to: * **Export Entities**: Export Objects, MFlows, MReports, MForms, and MData to JSON files * **Import Entities**: Import entities from JSON files back into the system * **Conflict Detection**: Automatically detect conflicts when importing * **Conflict Resolution**: Resolve conflicts during import process * **Data Migration**: Move entities between environments or tenants * **Backup and Restore**: Create backups and restore entities ## Key Concepts ### Export Types You can export different types of entities: * **Object**: Export Object definitions (schema, fields, relationships) * **MFlow**: Export workflow definitions and configurations * **MReport**: Export report configurations and queries * **MForm**: Export form definitions * **MData**: Export Object data records ### Export Options When exporting, you can choose what to include: * **RELATED**: Export the entity and all related entities (default) * **ALONE**: Export only the selected entity without related entities * **RELATIONSHIP**: Export only the relationships between entities ### Import Process The import process includes: 1. **File Upload**: Upload JSON export file 2. **Conflict Check**: System checks for conflicts with existing entities 3. **Conflict Resolution**: Resolve conflicts (if any) 4. **Import Execution**: Import non-conflicting and resolved entities ### Conflict Types Conflicts can occur when importing: * **Field Addition**: New fields being added to existing Objects * **Field Deletion**: Fields being removed from existing Objects * **Field Update**: Field properties being changed in existing Objects ## How Import Export Works ### Export Process 1. **Select Entity Type**: Choose what type of entity to export 2. **Select Entities**: Choose specific entities to export 3. **Choose Export Option**: Select what to include (RELATED, ALONE, RELATIONSHIP) 4. **Export**: Generate JSON file with entity data 5. **Download**: Download the JSON file ### Import Process 1. **Upload File**: Upload JSON export file 2. **Conflict Check**: System analyzes file for conflicts 3. **Review Conflicts**: Review detected conflicts 4. **Resolve Conflicts**: Choose how to resolve each conflict 5. **Import**: Import entities based on resolutions ### Conflict Resolution When conflicts are detected: * **Review Conflicts**: See what will change (additions, updates, removals) * **Approve Changes**: Approve import changes (use import fields) * **Revert Changes**: Keep existing fields (use existing fields) * **Skip Objects**: Skip importing conflicting objects * **Batch Resolution**: Resolve all conflicts at once ## Import Export Features ### Export Features * **Multiple Entity Types**: Export different types of entities * **Related Entities**: Include related entities automatically * **Selective Export**: Export specific entities or all entities * **JSON Format**: Standard JSON format for portability ### Import Features * **Conflict Detection**: Automatic conflict detection * **Conflict Analysis**: Detailed analysis of conflicts * **Resolution Options**: Multiple ways to resolve conflicts * **Import Sessions**: Track import progress with sessions * **Non-Conflicting Import**: Import non-conflicting entities automatically ### Conflict Management * **Field-Level Conflicts**: Conflicts detected at field level * **Object-Level Resolution**: Resolve conflicts per object * **Batch Resolution**: Resolve multiple conflicts at once * **Preview Changes**: Preview what will change before importing ## Using Import Export Import Export can be used for: * **Data Migration**: Move entities between environments * **Backup**: Create backups of entities * **Restore**: Restore entities from backups * **Sharing**: Share entity configurations * **Version Control**: Track entity changes ## Getting Started 1. **[Exporting Entities](/mbrix/import-export/exporting-entities)**: Learn how to export entities to JSON files 2. **[Importing Entities](/mbrix/import-export/importing-entities)**: Learn how to import entities with conflict resolution ## Related Introduction * [Objects Introduction](/mbrix/mobjects) - Understand Objects that can be exported/imported * [Workflows Introduction](/mbrix/workflows) - Learn about workflows that can be exported/imported * [Reports Introduction](/mbrix/reports) - Understand reports that can be exported/imported --- # Introduction URL: /mbrix/introduction Introduction to MBrix platform modules and capabilities *** title: Introduction description: Introduction to MBrix platform modules and capabilities -------------------------------------------------------------------- # MBrix Platform Overview Welcome to MBrix, a comprehensive workflow automation and data management platform. This platform provides a suite of integrated modules that work together to help you build, manage, and automate your business processes.
Monetize360 visual workflow canvas
## Core Modules ### Objects Objects are custom data models that define the structure of your business data. Think of an Object as a table or database schema that stores related information with fields, relationships, and validation rules. When you create an Object, the system automatically generates standard workflows and datagrids to help you manage your data efficiently. ### Workflows Workflows are visual automation tools that enable you to build complex business processes using drag-and-drop functions. They connect pre-built functions together to automate tasks, process data, integrate with external systems, and trigger user interactions without writing code. ### Datagrids Datagrids are interactive table views that display Object data in a structured grid format. They provide powerful filtering, sorting, grouping, and action capabilities, allowing users to efficiently view, search, and manage records with drill-down navigation to related data. ## Visualization ### Layouts Layouts are custom views for displaying and managing Object records with organized sections and fields. They support multiple display types including View360 (comprehensive record views), Simple Layout (form-based), and Mixed Layout (combination views) to provide tailored interfaces for different use cases. ### Reports Reports are data visualization tools that enable you to create dynamic reports and charts from Object data using materialized views for performance optimization. They support multiple chart types, complex queries with joins and filters, and interactive data analysis with export capabilities. ### Dashboards Dashboards are customizable interfaces that combine multiple widgets (reports, datagrids, charts, KPIs) into a single unified view. They provide global filters that affect all widgets simultaneously, enabling comprehensive data visualization and analysis across multiple data sources. ## Application Building ### Builder Builder is the page builder interface that allows you to create and manage application pages with customizable widgets and components. You can build complete application experiences by combining workflows, reports, datagrids, dashboards, and other components into cohesive pages. ### Advance Builder The Advance Builder extends the core page building capabilities by offering granular control over application design and behavior. Often referred to as "Free Layout", it provides developers and power users with tools for custom code integration, free-form layout configurations, and complex state management to create highly tailored application experiences. ## AI & Intelligence ### Agents AI Agents are intelligent assistants that can interact with your data, answer questions, and perform tasks using natural language. They enhance the entire platform by querying Objects, accessing Workflows, generating insights from Reports, and providing conversational interfaces within your applications. The platform also offers the flexibility to connect and utilize your preferred external AI models and providers. ## Getting Started Each module includes detailed documentation to help you get started: * **[Objects](/en/mobjects)** - Learn how to create and manage your data models * **[Workflows](/en/workflows)** - Build automated business processes * **[Datagrids](/en/datagrids)** - Build interactive data grids * **[Layouts](/en/layouts)** - Design custom record views * **[Reports](/en/reports)** - Create data visualizations and reports * **[Dashboards](/en/dashboard)** - Build unified dashboard views * **[Builder](/en/builder)** - Create application pages * **[Advance Builder](/en/application-builder)** - Design application experiences with free layout * **[Agents](/en/agents)** - Create and configure AI agents --- # Creating Layouts URL: /mbrix/layouts/creating-layouts *** ## title: Creating Layouts Layouts are created using the Layout List interface. Each layout is associated with an Object and configured with a specific display type to organize how records are viewed and managed. ## Required Information * **Name**: Unique identifier for the layout * **Associated Object**: The Object whose records will be displayed in this layout * **Display Type**: The type of layout (View360, Simple Layout, Mixed Layout, Estimator, or Flows) ## Configuration Steps
Layout Configuration Steps Interface
### 1. Open Layout Creation Dialog Navigate to the Layouts page and click the **"Add Layout"** button to open the creation dialog. ### 2. Enter Layout Name Provide a unique name for the layout. This name will be used to identify the layout throughout the system. ### 3. Select Associated Object Choose the Object that this layout will be associated with. The layout will display records from this Object. **Note**: Once a layout is created, the associated object cannot be changed. Make sure to select the correct Object. ### 4. Select Display Type Choose the display type for the layout: * **View 360**: Comprehensive 360-degree view with multiple sections and tabs * **Simple Layout**: Form-based layout with organized field groups * **Mixed Layout**: Combination layout with multiple sections and different display types * **Estimator**: Specialized layout for price estimation and calculation * **Flows**: Layout that displays workflow interfaces **Note**: The display type cannot be changed after creation. Choose the appropriate type based on your use case. ### 5. Enter Description (Optional) Provide an optional description to explain the purpose or usage of the layout. ### 6. Select Folder (Optional) Choose a folder (directory) to organize the layout. Folders help organize layouts for better management and navigation. ### 7. Set as Default (Optional) Check the **"Is Default"** checkbox if this should be the default layout for the associated Object. When a layout is set as default: * It becomes the primary layout used when viewing or editing records * If another layout was previously set as default, it will be automatically unset * Only one default layout can exist per Object per display type ### 8. Create Layout Click **"Add"** to create the layout. After creation: * The layout is created with an empty configuration * You are redirected to the layout detail page * You can now configure sections and fields for the layout ## Configuring Layouts After creating a layout, you'll be taken to the layout detail page where you can configure sections:

What is Simple Layout?

Simple Layout Configuration Simple Layout Example

Left: Layout configuration in the designer | Right: How it appears to users in the application

Simple Layout is a form-based layout type designed for straightforward data entry and record viewing. It provides a clean, organized interface where fields are arranged in groups and positioned using a flexible grid system. Simple Layouts are ideal for:

  • Data entry forms
  • Record detail views
  • Quick data capture
  • Simple editing interfaces

Configuration Steps

1. Add Field Groups

Field groups help organize related fields together, making the layout more intuitive and easier to navigate.

  • Create Groups: Click "Add Field Group" to create a new group
  • Name Groups: Give each group a descriptive name (e.g., "Basic Information", "Contact Details", "Address")
  • Organize Logically: Group fields that belong together (e.g., all address fields in one group)
  • Multiple Groups: You can create as many groups as needed to organize your fields

2. Add Fields to Groups

Once you have field groups, add fields from your Object to each group.

  • Drag and Drop: Drag fields from the Object field tree and drop them into the desired group
  • Field Selection: Select any field from the associated Object or related Objects
  • Multiple Fields: Add multiple fields to each group
  • Reorder Fields: Drag fields within a group to reorder them

3. Configure Field Properties

Each field in a Simple Layout can be configured with various properties to control its behavior and appearance.

  • Visibility: Show or hide fields based on conditions or user permissions
  • Read-Only: Make fields read-only to prevent editing
  • Required: Mark fields as required to enforce data entry
  • Validation Rules: Set custom validation rules for field values
  • Display Options: Configure how fields are displayed (labels, placeholders, help text)
  • Default Values: Set default values for fields

4. Grid Layout System

Simple Layouts use a flexible grid system that allows you to position fields precisely and create responsive layouts.

  • Position Fields: Each field has x and y coordinates that determine its position in the grid
    • X Coordinate: Horizontal position (column)
    • Y Coordinate: Vertical position (row)
  • Field Dimensions: Control field size using width (w) and height (h) properties
    • Width (w): Number of grid columns the field spans (e.g., w=1 spans 1 column, w=2 spans 2 columns)
    • Height (h): Number of grid rows the field spans
  • Column Spanning: Fields can span multiple columns to accommodate longer content or create emphasis
  • Responsive Design: The grid automatically adjusts to different screen sizes
  • Side-by-Side Fields: Position fields next to each other by placing them in the same row with different x coordinates
  • Stacked Fields: Place fields vertically by incrementing the y coordinate

Best Practices

  • Logical Grouping: Group related fields together (e.g., personal information, contact details)
  • Consistent Spacing: Use consistent spacing between fields for a clean appearance
  • Important Fields First: Place the most important fields at the top of the layout
  • Appropriate Field Widths: Use wider fields for longer content (like descriptions) and narrower fields for short values (like phone numbers)
  • Visual Hierarchy: Use field grouping and spacing to create a clear visual hierarchy

What is View360 Layout?

View360 Layout Example 1 View360 Layout Example 2

Left: Layout configuration in the designer | Right: How it appears to users in the application

View360 Layout provides a comprehensive 360-degree view of a record with multiple tabs and sections. It's designed to display all related information about a record in an organized, tabbed interface. View360 Layouts are ideal for:

  • Comprehensive record overviews
  • Displaying related records from multiple Objects
  • Complex data relationships
  • Executive dashboards and detailed views
  • Multi-entity record management

Configuration Steps

1. Add Tabs

Tabs organize different aspects of the record into separate views, making it easier to navigate complex information.

  • Create Tabs: Click "Add Tab" to create a new tab
  • Name Tabs: Give each tab a descriptive name (e.g., "Overview", "Orders", "History", "Documents")
  • Organize Content: Group related sections within the same tab
  • Multiple Tabs: Create as many tabs as needed to organize all related information
  • Tab Order: Reorder tabs by dragging them to change the display order

2. Add Sections Within Tabs

Each tab can contain multiple sections, each displaying different types of content or related records.

  • Add Section: Click "Add Section" within a tab
  • Section Types: Choose from various entity types (see Entity Types below)
  • Multiple Sections: Add multiple sections to each tab
  • Section Order: Arrange sections vertically within a tab
  • Section Titles: Give each section a descriptive title

3. Configure Entity Types

Each section can display different types of content. Choose the entity type that best fits your needs:

MData Grid

Display datagrids showing related records in a tabular format.

  • Use Case: Show lists of related records (e.g., orders for a customer, tasks for a project)
  • Configuration: Select a datagrid to display
  • Filtering: Use lookup fields to filter records related to the current record
  • Interactions: Users can view, add, edit, and delete records directly from the grid
Simple Layout

Embed another simple layout to display related records in a form format.

  • Use Case: Show detailed information about related records (e.g., contact details for a customer)
  • Configuration: Select a Simple Layout to embed
  • Lookup Field: Set a lookup field to filter and show only related records
  • Filtering: The embedded layout automatically filters records based on the current record
Standard Layout

Add standard components like expressions, layout configurations, and price matrices.

  • Expression: Display calculated values or expressions
  • Layout Configuration: Configure layout-specific settings
  • Price Matrix: Display pricing information in a matrix format
Estimator

Add price estimation and calculation components.

  • Use Case: Display pricing calculations, quotes, or estimates
  • Configuration: Configure estimation rules and formulas
  • Dynamic Pricing: Calculate prices based on various factors
MFlow

Display workflow interfaces and process management.

  • Use Case: Show workflow steps, approvals, or process status
  • Configuration: Select a workflow (MFlow) to display
  • Interactions: Users can interact with workflow steps directly from the layout
Section

Create nested sections for additional grouping and organization.

  • Use Case: Group related sections together
  • Nesting: Create hierarchical organization of content
  • Organization: Improve visual organization of complex layouts

4. Set Lookup Fields

Lookup fields are crucial for filtering related records and ensuring sections display only relevant data.

  • When to Use: When adding a Simple Layout or MData Grid section
  • How it Works: The lookup field filters the embedded content to show only records related to the current record
  • Example: In a Customer View360, adding an Orders MData Grid with "customerId" lookup field shows only orders for that customer
  • Field Selection: Choose a lookup field that establishes the relationship between records
  • Automatic Filtering: Records are automatically filtered when the View360 is opened

5. Configure Permissions

Control what users can do with sections, including adding, editing, and deleting records.

  • Add Permission: Allow or restrict users from adding new records in sections
  • Edit Permission: Control whether users can edit existing records
  • Delete Permission: Control whether users can delete records
  • Role-Based: Permissions can be set based on user roles
  • Section-Specific: Each section can have different permission settings

Best Practices

  • Logical Tab Organization: Organize tabs by functional area (e.g., Overview, Financial, History)
  • Related Data Together: Group related sections in the same tab
  • Clear Tab Names: Use descriptive tab names that clearly indicate their content
  • Proper Lookup Fields: Always set appropriate lookup fields to ensure correct data filtering
  • Permission Management: Set appropriate permissions for each section based on user needs
  • Performance Considerations: Limit the number of sections per tab to maintain good performance

What is Mixed Layout?

Mixed Layout Configuration Mixed Layout Example

Left: Layout configuration in the designer | Right: How it appears to users in the application

Mixed Layout combines the form-based approach of Simple Layout with the ability to embed datagrids, creating a hybrid interface that displays both form fields and related record lists. Mixed Layouts are ideal for:

  • Record detail views with related record lists
  • Forms that need to show related data grids
  • Combining form fields and tabular data in one view
  • Complex record management interfaces
  • Dashboards with both form and grid components

Configuration Steps

1. Add Field Groups

Field groups work the same way as in Simple Layouts - they organize form fields into logical sections.

  • Create Groups: Click "Add Field Group" to create a new group
  • Name Groups: Give each group a descriptive name
  • Add Fields: Drag and drop fields from the Object into groups
  • Configure Fields: Set field properties like visibility, validation, and display options
  • Position Fields: Use the grid system to position fields within groups

2. Add Layout Containers

Layout containers allow you to embed datagrids within the layout, displaying related records in a tabular format.

  • Create Container: Click "Add Layout Container" to add a new container
  • Container Purpose: Containers hold datagrids that display related records
  • Multiple Containers: You can add multiple containers to display different datagrids
  • Position Containers: Use the grid system to position containers alongside field groups

3. Configure Layout Containers

Each layout container needs to be configured to display a specific datagrid and optionally filter records.

Select a Datagrid
  • Choose Datagrid: Select the datagrid you want to display in the container
  • Datagrid Source: The datagrid must be associated with a related Object
  • Display Format: The datagrid will display records in its configured format (columns, filters, etc.)
  • Interactions: Users can interact with the datagrid (view, add, edit, delete records)
Set Lookup Field (Optional)
  • Purpose: Filter the datagrid to show only records related to the current record
  • When to Use: When you want to show related records (e.g., orders for a customer)
  • How it Works: The lookup field establishes the relationship and filters records automatically
  • Example: In a Customer Mixed Layout, set "customerId" as the lookup field for an Orders datagrid container
  • Without Lookup: If no lookup field is set, the datagrid shows all records (use with caution)
Position Containers
  • Grid Coordinates: Use x, y coordinates to position containers
  • Size Containers: Set width (w) and height (h) to control container size
  • Placement Options:
    • Place containers next to field groups (side by side)
    • Place containers below field groups (stacked)
    • Create custom arrangements based on your needs

4. Grid Layout System

The grid layout system allows you to position both field groups and layout containers precisely, creating flexible and responsive layouts.

Positioning Elements
  • X Coordinate: Horizontal position (column) in the grid
    • Lower x values = left side
    • Higher x values = right side
  • Y Coordinate: Vertical position (row) in the grid
    • Lower y values = top
    • Higher y values = bottom
  • Coordinate System: Both field groups and containers use the same coordinate system
Element Dimensions
  • Width (w): Number of grid columns the element spans
    • w=1: Spans 1 column (narrow)
    • w=2: Spans 2 columns (medium)
    • w=3 or more: Spans multiple columns (wide)
  • Height (h): Number of grid rows the element spans
    • Controls vertical space
    • Larger h values = taller elements
Layout Arrangements
  • Side by Side: Place elements next to each other by using the same y coordinate and different x coordinates
    • Example: Field group at (x=0, y=0) and container at (x=2, y=0)
  • Stacked: Place elements vertically by using the same x coordinate and different y coordinates
    • Example: Field group at (x=0, y=0) and container at (x=0, y=5)
  • Custom Arrangements: Combine both approaches for complex layouts

Best Practices

  • Balance Form and Grid: Balance the amount of form fields and datagrid containers
  • Logical Positioning: Place related field groups and containers near each other
  • Use Lookup Fields: Always set lookup fields for containers to show relevant related records
  • Appropriate Sizing: Size containers appropriately - wider containers for more columns, taller for more rows
  • Visual Hierarchy: Use positioning and sizing to create a clear visual hierarchy
  • Responsive Design: Consider how the layout will look on different screen sizes
  • Performance: Limit the number of containers to maintain good performance
## Layout Settings ### Default Layout Behavior * **One Default Per Display Type**: Each Object can have one default layout per display type * **Automatic Selection**: Default layouts are automatically used when viewing records * **Changing Default**: Setting a new layout as default automatically unsets the previous default ### Folder Organization * **Optional Organization**: Folders are optional but recommended for better organization * **Hierarchical Structure**: Folders can be nested for complex organization * **Filtering**: You can filter layouts by folder in the layout list ### Workflow Integration After creating a layout, you can optionally associate it with a workflow using the **Flow ID** field. When a workflow is associated: * The workflow can be triggered when editing records through the layout * Custom business logic defined in the workflow is executed * The workflow can handle data validation, transformations, and side effects * This is configured in the layout detail/edit page ### Lookup Fields Lookup fields are used to filter related records in View360 layouts: * **When to Use**: When adding a Simple Layout section in View360, you can select a lookup field * **How it Works**: The lookup field filters the embedded layout's records to show only those related to the current record * **Example**: In a Customer View360 layout, adding an Orders Simple Layout with a "customerId" lookup field will show only orders for that customer ### Layout Containers (Mixed Layout) Layout containers in Mixed Layouts allow you to embed datagrids: * **Purpose**: Display related records in a grid format within the layout * **Configuration**: Select a datagrid and optionally set a lookup field * **Filtering**: The lookup field filters the datagrid to show only related records * **Positioning**: Containers are positioned using the grid layout system alongside field groups ## Best Practices ### Naming Conventions * Use descriptive names that clearly indicate the layout's purpose * Include the Object name in the layout name for clarity * Use consistent naming patterns across layouts ### Display Type Selection * **View360**: Use for comprehensive record views with multiple related data sections * **Simple Layout**: Use for straightforward forms and data entry * **Mixed Layout**: Use when you need to combine different view types * **Estimator**: Use specifically for pricing and estimation workflows * **Flows**: Use when displaying workflow interfaces ### Default Layouts * Set a default layout for each Object to ensure consistent user experience * Choose the most commonly used layout as the default * Consider user roles when selecting default layouts ### Folder Organization * Organize layouts by Object or by functional area * Use folders to group related layouts together * Keep folder structures simple and intuitive ## Related Introduction * [Layouts Introduction](/mbrix/layouts) - Overview of layouts * [Objects Introduction](/mbrix/mobjects) - Understand the data models used in layouts * [Workflows Introduction](/mbrix/workflows) - Learn about workflows used with layouts --- # Layouts Introduction URL: /mbrix/layouts *** ## title: Layouts Introduction Layouts are custom views for displaying and managing Object records. They provide structured interfaces for viewing, creating, and editing records with organized sections and fields. ## What are Layouts? Layouts are visual configurations that: * **Display Object Data**: Show records in organized, user-friendly views * **Organize Fields**: Group related fields into sections * **Support Multiple Views**: Provide different display types (View360, Simple Layout, Mixed Layout, Estimator, Flows) * **Enable Record Management**: Support creating, viewing, and editing records * **Associate with Objects**: Each layout is linked to a specific Object ## Layout Types | Type | Description | Best For | | ----------------- | ----------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------- | | **View360** | Comprehensive 360-degree view displaying all related information about a record, including related records from other Objects | Customer profiles, detailed record views, multi-entity dashboards | | **Simple Layout** | Straightforward form-based layout for creating and editing records with organized sections | Data entry forms, quick record editing, simple CRUD operations | | **Mixed Layout** | Combination layout with multiple sections and different display types (forms + datagrids) | Record details with related lists, complex record management | | **Estimator** | Specialized layout for price estimation and calculation | Pricing workflows, quotes, cost calculations | | **Flows** | Layout displaying workflow interfaces and execution forms | Workflow forms, guided processes, step-by-step data collection | ## Key Features ### Sections Layouts are organized into sections that group related fields together for better organization and user experience. ### Default Layouts Each Object can have a default layout that is automatically used when viewing or editing records. ### Directory Organization Layouts can be organized in folders (directories) for better management and navigation. ### Workflow Integration Layouts can be associated with workflows to enable custom edit functionality and business logic. ## Layout Configuration Each layout includes: * **Name**: Unique identifier for the layout * **Description**: Optional description * **Associated Object**: The Object whose records are displayed * **Display Type**: The type of layout (View360, Simple Layout, Mixed Layout, Estimator, Flows) * **Sections**: Organized groups of fields * **Directory**: Optional folder for organization * **Default Flag**: Whether this is the default layout for the Object ## Using Layouts Layouts are used: * **In Pages**: Embedded as components in dashboard pages * **For Record Management**: Viewing, creating, and editing Object records * **As Drill-Down Targets**: Navigated to from datagrids and reports * **In Workflows**: Referenced in workflow actions and forms ## Getting Started 1. **[Creating Layouts](/mbrix/layouts/creating-layouts)**: Learn how to create layouts with different display types 2. **Configure Sections**: Add and organize sections based on the layout type 3. **Set as Default**: Configure default layouts for Objects ## Related Introduction * [Creating Layouts](/mbrix/layouts/creating-layouts) - Step-by-step guide to creating layouts * [Objects Introduction](/mbrix/mobjects) - Understand the data models displayed in layouts * [Workflows Introduction](/mbrix/workflows) - Learn about workflows used with layouts * [Datagrids Introduction](/mbrix/datagrids) - Understand how layouts relate to datagrids --- # Creating Connections URL: /mbrix/connections/creating-connections Learn how to create connections for S3, Database, REST API, Stripe, and Airwallex *** title: Creating Connections description: Learn how to create connections for S3, Database, REST API, Stripe, and Airwallex ---------------------------------------------------------------------------------------------- # Creating Connections Connections are created through the Connections interface. Each connection type requires specific configuration details. All connections require a name and description. ## Common Fields All connection types require: * **Connection Name**: Unique identifier for the connection * **Description**: Optional description of the connection's purpose ## Connection Types ### S3 Connection Connect to AWS S3 buckets for file storage and data access. **Required Fields:** * **AWS Bucket**: Name of the S3 bucket * **AWS Region**: AWS region where the bucket is located **Authentication Options:** * **No Authentication**: For public buckets * **AWS Credentials**: Access Key ID and Secret Access Key * **IAM Role**: Assume an IAM role with Role ARN, Session Name, and External ID **Optional Fields:** * **AWS URL**: Custom S3 endpoint URL ### Database Connection Connect to external databases (PostgreSQL, MySQL, Oracle) for data access. **Required Fields:** * **Database Type**: PostgreSQL, MySQL, or Oracle * **Database User**: Username for database access * **Database Password**: Password for database access **Configuration Options:** **Simple Configuration:** * **Database Host**: Database server hostname or IP * **Database Port**: Database server port * **Default Database**: Default database name **Advanced Configuration:** * **Connection URL**: Full JDBC connection URL * **Driver Class Name**: JDBC driver class name * **Database Properties**: Additional connection properties ### REST API Connection Connect to external REST APIs with various authentication methods. **Required Fields:** * **API URL**: Base URL of the REST API endpoint * **HTTP Method**: GET, POST, PUT, or DELETE **Optional Fields:** * **Query Parameters**: URL query parameters * **Headers**: HTTP headers * **Request Body**: Request body content **Authentication Types:** * **None**: No authentication required * **Basic**: Username and password * **API Key**: API key with optional header name * **OAuth2**: Client ID, Client Secret, Token URL, Scope * **OAuth1**: Consumer Key, Consumer Secret, Token ID, Token Secret, Signature Method ### Stripe Connection Connect to Stripe payment processing service. **Required Fields:** * **API Key**: Stripe secret API key **Optional Fields:** * **Publishable Key**: Stripe publishable key * **Success URL**: Redirect URL for successful payments * **Failure URL**: Redirect URL for failed payments * **Currency**: Default currency code * **Webhook API Key**: API key for webhook verification ### Airwallex Connection Connect to Airwallex payment processing service. **Required Fields:** * **Base URL**: Airwallex API base URL * **OAuth2 Credentials**: Client ID and Client Secret **Optional Fields:** * **Publishable Key**: Airwallex publishable key * **Success URL**: Redirect URL for successful payments * **Failure URL**: Redirect URL for failed payments * **Currency**: Default currency code * **Webhook API Key**: API key for webhook verification ## Creating a Connection 1. Navigate to Connections 2. Click "Create Connection" 3. Enter connection name and description 4. Select connection type 5. Fill in required fields for the selected type 6. Configure authentication if required 7. Test the connection 8. Save the connection ## Testing Connections After creating a connection, test it to verify: * Credentials are correct * Network connectivity is available * Permissions are properly configured ## Schema Import After creating and testing a connection, you can import schema to understand available data structures: * **S3**: Import file structure and field mappings * **Database**: Import table schemas and column definitions * **REST API**: Import API response schemas ## Related Introduction * [Connections Introduction](/mbrix/connections) - Overview of connections * [S3DataLoad](/mbrix/workflows/functions/system-functions/s3-data-load) - Use S3 connections in workflows * [DbDataLoad](/mbrix/workflows/functions/system-functions/db-data-load) - Use database connections in workflows --- # Importing Schema from Connections URL: /mbrix/connections/importing-schema Learn how to import database schemas and automatically create Objects from connections *** title: Importing Schema from Connections description: Learn how to import database schemas and automatically create Objects from connections --------------------------------------------------------------------------------------------------- # Importing Schema from Connections Schema Import allows you to automatically create or update Objects based on external database schemas. This feature reads the database structure from a connection and generates corresponding Objects with matching fields. ## What is Schema Import? Schema Import analyzes the database structure connected through a Database connection and: * **Creates Objects**: New Objects are created for tables that don't have corresponding Objects * **Updates Objects**: Existing Objects are updated to match current database schema * **Tracks Changes**: Shows which Objects were created, updated, or deleted ## Supported Connection Types Schema Import is primarily used with **Database connections** (PostgreSQL, MySQL, Oracle). ## How It Works 1. **Create and Test Connection**: Ensure your database connection is working 2. **Import Schema**: Click "Import Schema" from the connection details 3. **Review Results**: View created, updated, and deleted Objects 4. **View Details**: Click on any Object to see its schema and data ## Import Results After importing, you'll see three categories: ### Created Objects New Objects created from database tables that didn't have corresponding Objects. Each table becomes an Object with fields matching the table columns. ### Updated Objects Existing Objects that were updated to match the current database schema. Fields are added or modified to reflect schema changes. ### Deleted Objects Objects that were removed because their corresponding database tables no longer exist. ## Viewing Imported Objects After import, you can: * **View Schema**: See the field structure of imported Objects * **View Data**: Browse sample data from the imported Objects * **Edit Objects**: Modify imported Objects as needed * **Use in Workflows**: Use imported Objects in workflows with DbDataLoad ## Best Practices 1. **Test Connection First**: Always test your connection before importing schema 2. **Review Changes**: Carefully review created/updated/deleted Objects 3. **Backup Data**: Consider backing up existing Objects before importing 4. **Incremental Updates**: Re-import schema periodically to keep Objects in sync with database changes ## Related Introduction * [Creating Connections](/mbrix/connections/creating-connections) - Learn how to create database connections * [Objects Introduction](/mbrix/mobjects) - Understand Objects and their structure * [DbDataLoad](/mbrix/workflows/functions/system-functions/db-data-load) - Use imported Objects to load data from databases --- # Connections Introduction URL: /mbrix/connections Learn about Connections - external system integrations for data ingestion and API access *** title: Connections Introduction description: Learn about Connections - external system integrations for data ingestion and API access ----------------------------------------------------------------------------------------------------- # Connections Connections are configurations that enable integration with external systems and data sources. They store authentication credentials and connection details needed to access external APIs, databases, cloud storage, and other services. ## What are Connections? Connections provide secure, reusable configurations for: * **Data Sources**: S3, FTP, Databases (PostgreSQL, MySQL, Oracle), Salesforce, Athena, QuickSight * **Payment Providers**: Stripe, Airwallex * **Email Providers**: SendGrid, SMTP, SES * **Tax Engines**: Vertex, Avalara, M360 Tax * **General Ledger**: Xero, QuickBooks * **External APIs**: REST API connections with various authentication methods ## Connection Types ### Data Source Connections * **S3**: AWS S3 bucket access with credentials or IAM roles * **DB**: Database connections (PostgreSQL, MySQL, Oracle) with host, port, credentials * **REST\_API**: External API connections with authentication (Basic, API Key, OAuth2, OAuth1) * **FTP**: File Transfer Protocol connections * **Salesforce**: Salesforce API integration * **Athena**: AWS Athena query access * **QuickSight**: AWS QuickSight integration ### Payment Provider Connections * **Stripe**: Stripe payment processing with API keys * **Airwallex**: Airwallex payment processing with OAuth2 ### Email Provider Connections * **SendGrid**: SendGrid email service * **SMTP**: Standard SMTP email server * **SES**: AWS Simple Email Service ## Key Features ### Connection Configuration Each connection type has specific configuration requirements: * **S3**: Bucket name, region, AWS credentials or IAM role * **DB**: Database type, host, port, credentials, connection URL * **REST\_API**: API endpoint, HTTP method, headers, authentication details * **Stripe/Airwallex**: API keys, OAuth credentials, webhook URLs ### Connection Testing Test connections before use to verify credentials and connectivity. ### Schema Import Import schema from connections to understand available data structures and fields. ### Security Connections securely store credentials and support various authentication methods including OAuth2, API keys, and basic authentication. ## Using Connections in Workflows Connections are used by workflow functions to access external data: * **[S3DataLoad](/mbrix/workflows/functions/system-functions/s3-data-load)**: Load data from S3 buckets * **[DbDataLoad](/mbrix/workflows/functions/system-functions/db-data-load)**: Load data from external databases * **CallExternalApi**: Make API calls to external REST APIs ## Getting Started 1. **[Creating Connections](/mbrix/connections/creating-connections)**: Learn how to create S3, Database, REST API, Stripe, and Airwallex connections 2. **Test Connections**: Verify credentials and connectivity 3. **[Importing Schema](/mbrix/connections/importing-schema)**: Import database schemas and create Objects automatically 4. **Use in Workflows**: Reference connections in workflow functions ## Related Introduction * [Creating Connections](/mbrix/connections/creating-connections) - Step-by-step guide to creating connections * [S3DataLoad](/mbrix/workflows/functions/system-functions/s3-data-load) - Load data from S3 connections * [DbDataLoad](/mbrix/workflows/functions/system-functions/db-data-load) - Load data from database connections * [Workflows](/mbrix/workflows) - Learn about workflow creation and management --- # Creating Objects URL: /mbrix/mobjects/creating-mobjects *** ## title: Creating Objects When creating an Object, you'll configure various fields that control its behavior, organization, and data management. This guide explains how to create Objects and configure each setting in detail. Creating Objects Interface ## Required Fields ### Object Name The unique identifier for your Object. Must be unique across all Objects and cannot be changed after creation. **Requirements:** * Use descriptive, PascalCase names (e.g., "Customer", "Order", "Product") * Use singular nouns (Customer, not Customers) * Avoid special characters and spaces ### Description A human-readable description that explains what the Object represents and its purpose. Can be updated after creation. Keep it clear and concise (1-2 sentences). **Example:** "Customer information and contact details for managing customer relationships and transactions" ## Optional Fields ### Business Key A field name that serves as a unique identifier for display purposes. Used when displaying records in lookups, dropdowns, and related record views. Must reference a field that exists in your Object schema. **When to Use:** * When you have a natural unique identifier (email, product code, SKU) * For better UX in lookup fields and related record displays **Example:** `email` or `customerNumber` (Customer), `sku` or `productCode` (Product), `orderNumber` (Order) **Note:** The business key field should ideally be unique or have a unique constraint in your schema. ### Object Type Defines the category and behavior of the Object. Each type has different characteristics and use cases. | Type | Description | Use Case | Editable | | -------------- | ----------------------------------------- | ------------------------------------------------------------- | -------- | | **PERSISTENT** | Data persists permanently in the database | Customer records, orders, invoices, products | Yes | | **TRANSIENT** | Temporary data, may be cleaned up | Workflow execution data, temporary calculations, session data | Yes | | **SYSTEM** | System-managed objects, read-only | Internal system objects, core platform entities | No | | **STANDARD** | Standard business objects | Predefined business entities | Yes | | **CUSTOM** | User-defined custom objects | Custom business logic objects | Yes | | **EXTERNAL** | External data sources | Objects synced from external databases or systems | Limited | **Default:** `PERSISTENT` Use PERSISTENT for most business data, TRANSIENT for temporary or workflow-specific data. SYSTEM objects are managed by the platform, and EXTERNAL objects are synced from external connections. ### Tags Labels for organizing and categorizing Objects. Multiple tags can be assigned to an Object. Tags are case-sensitive and help you filter, search, and group related objects. **Best Practices:** * Use consistent naming conventions (lowercase, kebab-case, or camelCase) * Create meaningful categories (e.g., "customer", "sales", "inventory", "finance", "core", "integration") * Keep tag names short and descriptive ### Enable Audit Enables audit trail tracking for all changes made to Data records. When enabled, all create, update, and delete operations are logged with who made the change, when, and what changed. **When to Enable:** * Important business data (customers, orders, financial records) * When compliance or audit requirements exist **When to Disable:** * Temporary or transient data * High-volume, low-value data * When storage optimization is critical **Note:** Audit trails consume additional storage. Enable only for objects where change tracking is necessary. ### Org Enabled Controls whether Data records are scoped to the organization (multi-tenant isolation). **Default:** `true` (enabled) **When enabled (default):** Records are filtered by organization ID. Each organization only sees its own data. Use for customer-specific data, organization-specific configurations, and most business data. **When disabled:** Records are shared across organizations. Use for shared reference data (countries, currencies, product catalogs), system-wide configurations, and global lookup tables. **Important:** Changing this setting after creation may affect data access. Plan your multi-tenant strategy before creating Objects. ## Import Schema Import field definitions from an Excel (.xlsx, .xls) or CSV file instead of manually adding fields. **Supported Formats:** Excel (`.xlsx`, `.xls`) and CSV (`.csv`) **File Format:** The import file should contain columns: Name (required), Title, Description, Type, and Enum (for picklist fields, comma-separated). **Import Process:** 1. Click "Select File to Import Schema" 2. Choose an Excel or CSV file 3. Review the imported fields 4. Click "Import Schema" to apply Use the download icon to get a template file with the correct format. Useful for migrating schemas from other systems, bulk field creation, and standardizing field definitions across Objects. ## Fields Summary | Setting | Required | Default | Can Change After Creation | | ------------ | -------- | ---------- | ------------------------- | | Object Name | Yes | - | No | | Description | Yes | - | Yes | | Business Key | No | - | Yes | | Object Type | Yes | PERSISTENT | Limited | | Tags | No | - | Yes | | Enable Audit | No | false | Yes | | Org Enabled | No | true | Yes (with caution) | ## Best Practices * Use clear, descriptive PascalCase names (singular nouns) * Provide meaningful descriptions for maintainability * Set business keys for better UX in lookups and displays * Use consistent tagging strategy for organization * Enable audit for important business data only * Plan multi-tenant strategy before creation * Choose the right Object Type based on data lifecycle ## Related Introduction * [Field Types](/mbrix/mobjects/field-types) - Complete reference for all field types --- # Field Types URL: /mbrix/mobjects/field-types *** ## title: Field Types Objects support various field types to represent different kinds of data. Choose the appropriate field type based on the data you need to store and how users will interact with it.
General Fields General Fields 2 Special Fields
## Common Properties All field types support the following common properties: * **`label`**: Display name for the field shown in forms and UI (required) * **`description`**: Additional help text or instructions about the field (optional) * **`required`**: Whether the field must have a value before form submission (default: false) These properties are available for every field type and can be configured in the Schema Builder. ## General Fields | Name | Type | Description | Properties | | ---------------- | ------------------------------ | --------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------- | | Single Line Text | `string` | Single-line text input for short values like names, titles, or codes | `unique`: Ensures no duplicate values across records | | Number | `number` or `integer` | Numeric field for whole numbers or decimals | `unique`: Ensures no duplicate values; `minimum`: Minimum allowed value; `maximum`: Maximum allowed value | | Currency | `currency` | Specialized number field for monetary values with currency formatting | `currencyCode`: ISO currency code (e.g., USD, EUR) | | Slider | `number` | Numeric input displayed as a slider control | `minimum`: Minimum slider value; `maximum`: Maximum slider value; `step`: Increment step value | | Long Text | `text` | Multi-line text input for longer content like descriptions or notes | `pattern`: Regular expression pattern for text validation | | Static Text | `string` (read-only) | Read-only text field displaying static information or labels | `value`: The static text content to display | | Picklist | `picklist` | Dropdown field allowing selection of a single value from a predefined picklist category | `picklistCategoryId`: ID of the picklist category to use | | Select | `string` | Dropdown field allowing selection of a single value from predefined options | `options`: Array of option objects with value and label | | MultiSelect | `array` | Dropdown field allowing selection of multiple values from predefined options | `options`: Array of option objects with value and label | | Lookup | `reference` | Reference field linking to another Object record, creates relationships and foreign keys | `targetMObjectId`: ID of the target Object to reference; `displayField`: Field name to display in lookup results | | Checkbox | `boolean` | Boolean field storing true/false values, displayed as checkbox | | | URL | `string` (format: "url") | Text field for web URLs with URL format validation | | | Date | `string` (format: "date") | Date picker for selecting calendar dates without time | | | Date Time | `string` (format: "date-time") | Date and time picker for selecting both date and time values | | | Time | `string` (format: "time") | Time picker for selecting time values without date | | | Email | `string` (format: "email") | Text field for email addresses with email format validation | | | Password | `string` (format: "password") | Secure text input that masks characters, designed for sensitive information | | | UUID | `uuid` | Field for storing universally unique identifiers (UUIDs) | | | Switch | `boolean` | Boolean field displayed as a toggle switch control, similar to Checkbox but with different UI | | ## Lookup Fields Lookup fields create relationships between Objects, similar to foreign keys in databases. When you add a Lookup field, you select a target Object to reference. This allows you to link records together — for example, linking an Order to a Customer, or a Product to a Category. Lookup Fields Configuration ### Configuration * **Lookup Object**: The Object you want to reference (e.g., Customer, Product, Category) * **Lookup Field**: The field used to match and store the reference (e.g., id, code) * **Lookup Display Label**: The field value shown in the dropdown (e.g., `{{name}}` to display the name field) * **Enable Multi-Select**: When enabled, allows selecting multiple records from the target Object instead of just one ### Use Cases * Link Orders to Customers * Link Products to Categories * Link Invoices with Payments ## Special Fields | Name | Type | Description | Properties | | ---------------- | ------------------------ | -------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------- | | Attachment | `file` | File upload field for storing a single file attachment | `allowedFileTypes`: Comma-separated list of allowed file extensions; `maxFileSize`: Maximum file size in bytes | | File Array | `file-array` | Field for storing multiple file attachments | `allowedFileTypes`: Comma-separated list of allowed file extensions; `maxFileSize`: Maximum file size per file; `maxFiles`: Maximum number of files allowed | | Array | `array` | Field for storing arrays or lists of values of any data type | `items`: Schema definition for the array item type | | JSON | `object` or `json` | Field for storing arbitrary JSON data structures | `properties`: Nested schema definition for JSON object structure | | Service Widget | Custom widget type | Specialized widget field integrating with external services or APIs | `serviceType`: Type of external service; `serviceConfig`: Configuration object for the service | | Input Form | `object` (nested schema) | Field embedding a form within another form for nested structures | `schema`: Nested form schema definition | | Stripe Widget | Custom widget type | Specialized payment widget integrating with Stripe payment processing | `stripeConfig`: Stripe API configuration and settings | | Airwallex Widget | Custom widget type | Specialized payment widget integrating with Airwallex payment processing | `airwallexConfig`: Airwallex API configuration and settings | | File Preview | `file` (preview enabled) | Field displaying preview of uploaded files, especially images or documents | `previewEnabled`: Enable file preview display; `allowedFileTypes`: Comma-separated list of allowed file extensions | **Note**: All fields support common properties: `label`, `description`, and `required`. ## System Properties Every Object automatically includes system properties that are managed by the platform. These properties provide essential metadata about your records, including unique identifiers, timestamps, user tracking, and soft deletion support. System properties are automatically added to every Object schema when it's created and cannot be modified manually. | Property | Type | Description | When Set | | ------------ | ---------------- | -------------------------------------------------------------------- | ----------------------------------------------------------- | | `id` | UUID | Unique identifier for the record, automatically generated | On creation | | `created_at` | DateTime | Timestamp when record was created (UTC, ISO 8601 format) | On creation | | `created_by` | UUID (Reference) | User who created the record, references User Object | On creation | | `updated_at` | DateTime | Timestamp when record was last updated (UTC, ISO 8601 format) | On every update | | `updated_by` | UUID (Reference) | User who last updated the record, references User Object | On every update | | `deleted` | Boolean | Soft delete flag (false = active, true = deleted), defaults to false | On creation (defaults to false), set to true on soft delete | **Key Characteristics:** * Automatically added to all Objects * Managed by the system (cannot be modified manually, except `deleted` for soft deletion) * Always available in your data records * Provide essential metadata and tracking **Note:** By default, queries exclude records where `deleted: true`. To include deleted records, you need to explicitly filter for them. ## Field Type Selection Guide | Data Type | Recommended Field Type | | ------------------------- | -------------------------------- | | Short text (names, codes) | Single Line Text | | Long text (descriptions) | Long Text | | Numbers | Number | | Money values | Currency | | True/False | Checkbox | | Dates only | Date | | Date and time | Date Time | | Email addresses | Email | | Web links | URL | | Passwords | Password | | File uploads | Attachment or File Array | | Related records | Lookup | | Multiple choice | Picklist, Select, or MultiSelect | | Toggle on/off | Checkbox or Switch | | Complex data | JSON or Object | | Unique IDs | UUID | --- # Objects Introduction URL: /mbrix/mobjects *** ## title: Objects Introduction Objects are custom data models that define the structure of your business data in Monetize360. Create Objects to store and manage your data with fields, relationships, and validation rules. Objects Interface ## What are Objects? Objects define your data structure. Think of an Object as a table or database schema that defines the structure for storing related data. Each Object contains: * Fields with specific data types (text, number, date, etc.) * Lookup fields (foreign keys) for relationships between objects * Picklist fields for dropdown values * Validation rules * Audit trails (optional) ### Auto-Created Resources When you create an Object, the system automatically creates: * **[Workflows](/mbrix/workflows)**: Standard CRUD workflows are automatically generated: * **Save Flow**: Create new records * **Edit Flow**: Update existing records * **Delete Flow**: Delete records * **Import Flow**: Import data from files * **Export Flow**: Export data to files * **Excel Import Flow**: Import data from Excel/CSV files * **[DataGrid](/mbrix/datagrids)**: A default datagrid is automatically created with: * All Object fields displayed as columns * Pre-configured actions (Save, Edit, Delete, Import, Export, Excel Import) * Ready-to-use interface for viewing and managing Data records These auto-created resources are organized in directories matching your Object name, making it easy to find and customize them as needed. ## Key Concepts ### Fields Define fields to store your data: * **Text**: Names, descriptions, notes * **Number**: Quantities, prices, amounts * **Date**: Dates and timestamps * **Boolean**: True/false values * **Lookup**: Links to other Objects (creates relationships) * **Picklist**: Predefined dropdown options ### Relationships Create relationships between Objects using Lookup fields: * Link customers to orders * Link products to categories * Link invoices with payments ### Data
Data Interface Data Records
**Data** represents the actual data records stored within your Objects. While Objects define the structure (schema), Data contains the actual instances of that data. * **Object**: The blueprint or template (e.g., "Customer" schema with fields like name, email, address) * **Data**: The actual records conforming to that blueprint (e.g., individual customer records with real values) Each Data record is a JSON document that follows the schema defined by its parent Object. Data records include: * Business data fields (as defined in the Object schema) * System properties (id, created\_at, created\_by, updated\_at, updated\_by, deleted) ### Data Management Once you've created Objects, use CRUD operations to manage your data: * [Create or Update Records](/mbrix/workflows/functions/crud-operations/insert-mdata) * [Fetch Records](/mbrix/workflows/functions/crud-operations/fetch-mdata) * [Delete Records](/mbrix/workflows/functions/crud-operations/delete-mdata) ## Getting Started 1. **[Create an Object](/mbrix/mobjects/creating-mobjects)**: Learn how to create Objects and configure their settings 2. **[Add Fields](/mbrix/mobjects/field-types)**: Learn about all available field types and their use cases 3. **[Add Data](/mbrix/workflows/functions/crud-operations/insert-mdata)**: Create or update records in your Objects ## Related Introduction * [Schema Builder](/mbrix/mobjects/schema-builder) - Understanding the Schema Builder interface for defining fields * [Creating Objects](/mbrix/mobjects/creating-mobjects) - Learn how to create Objects and configure their settings * [Field Types](/mbrix/mobjects/field-types) - Complete reference for all field types * [CRUD Operations](/mbrix/workflows/functions/crud-operations) - Work with Object data * [Getting Started](/mbrix/workflows/getting-started) - Build your first workflow --- # Object Fields Configuration URL: /mbrix/mobjects/schema-builder *** ## title: Object Fields Configuration The **Object Field Definition** is the visual interface used to define fields and properties for Objects. ## Overview When working with Objects, the Object Field Definition provides a drag-and-drop interface to: * Add fields to your Object schema * Configure field properties (type, validation, UI options) * Set up relationships and lookups * Define field visibility and conditional logic ## How It Works ### Visual Interface Object Field Definition The Object Field Definition consists of: 1. **Field Palette** (Left Side): A tree of available field types you can drag and drop * General Fields (Text, Number, Date, etc.) * Special Fields (Attachment, File Array, Service Widget etc.) * System Fields (automatically added) 2. **Form Canvas** (Center): Where you build your Object schema * Drag fields from the palette * Arrange and organize fields * Configure field properties 3. **Property Panel** (Right Side): Configure selected field properties * Field name and label * Data type and format * Validation rules * UI options * External data sources (for Lookup fields) ### Field Definition Process When defining Object fields using the Object Field Definition: 1. **Select Field Type**: Choose from the field palette (e.g., Single Line Text, Number, Lookup) 2. **Drag to Canvas**: Drop the field onto the form canvas 3. **Configure Properties**: Set field name, label, validation rules, and UI options 4. **Set Relationships**: Configure Lookup fields to reference other Objects 5. **Save Schema**: The Object Field Definition converts your visual configuration into a JSON Schema ## Field Properties Each field in the Object Field Definition has configurable properties: ### Common Properties * **Name**: Technical field name (used in API and database) * **Label/Title**: Display name shown in forms * **Description**: Help text for users * **Required**: Whether the field is mandatory * **Default Value**: Initial value for new records ### Type-Specific Properties Different field types have additional properties: * **Text Fields**: Min/max length, pattern validation * **Number Fields**: Min/max values, decimal places * **Date Fields**: Date format, date range constraints * **Lookup Fields**: Target Object, display field * **Picklist Fields**: Enum values, multi-select option ## Best Practices ### Field Naming * Use clear, descriptive names: `customerName` instead of `name1` * Follow consistent naming conventions (camelCase) * Avoid reserved words and special characters ### Field Organization * Group related fields together * Use logical ordering (e.g., personal info before contact info) * Consider user workflow when arranging fields ### Relationships * Plan Lookup fields early in your design * Choose meaningful display fields for Lookup fields * Consider cascade behavior for related data ## Example: Creating a Customer Object 1. **Start**: Open Object creation dialog 2. **Basic Info**: Enter name "Customer" and description 3. **Field Definition Tab**: Use Object Field Definition to add fields: * Drag "Single Line Text" → Name: `name`, Label: "Customer Name" * Drag "Email" → Name: `email`, Label: "Email Address" * Drag "Lookup" → Name: `accountManager`, Label: "Account Manager", Target: "User" Object 4. **Configure**: Set validation rules (required fields, email format) 5. **Save**: Object Field Defnition generates the JSON Schema and creates the Object ## Related Introduction * [Field Types](/mbrix/mobjects/field-types) - Complete reference for all field types * [Creating Objects](/mbrix/mobjects/creating-mobjects) - Configure Object-level settings --- # Organization Introduction URL: /mbrix/organization Learn about Organization management - hierarchical organizations, users, groups, roles, and permissions *** title: Organization Introduction description: Learn about Organization management - hierarchical organizations, users, groups, roles, and permissions -------------------------------------------------------------------------------------------------------------------- # Organization Organization management enables you to structure your system with hierarchical organizations, manage users, groups, roles, and permissions. This provides a comprehensive access control and multi-tenancy system. ## What is Organization Management? Organization management enables you to: * **Create Hierarchical Organizations**: Build parent-child organization structures * **Manage Users**: Create and manage users across multiple organizations * **Organize with Groups**: Create groups to organize users * **Define Roles**: Create roles with specific permissions * **Control Access**: Manage permissions through roles and groups * **Multi-Tenancy**: Support multiple organizations in a single system ## Key Concepts ### Organizations Organizations are hierarchical entities that represent companies, departments, or business units: * **Hierarchical Structure**: Organizations can have parent-child relationships * **Root Organizations**: Top-level organizations without parents * **Child Organizations**: Sub-organizations that belong to parent organizations * **Organization Tree**: Visual representation of organization hierarchy ### Users Users are individuals who access the system: * **Multiple Organizations**: Users can belong to multiple organizations * **Primary Organization**: One organization is designated as primary * **User Roles**: Users can have direct role assignments * **Group Membership**: Users can belong to groups ### Groups Groups are collections of users within an organization: * **Hierarchical Structure**: Groups can have parent-child relationships * **Organization Scoped**: Groups belong to specific organizations * **Role Assignment**: Groups can have roles assigned * **Inheritance**: Groups can inherit permissions from parent groups ### Roles Roles define sets of permissions: * **Organization Scoped**: Roles belong to specific organizations * **Permission Assignment**: Roles have permissions assigned * **Permission Groups**: Roles can include permission groups * **User Assignment**: Roles can be assigned to users or groups ### Permissions Permissions define what actions can be performed: * **Resource Types**: Permissions apply to resources (tables, rows, columns, JSON keys) * **Actions**: Permissions define actions (read, write, delete, etc.) * **Conditions**: Permissions can have conditions (ABAC - Attribute-Based Access Control) * **Permission Groups**: Permissions can be organized into groups ## How Organization Management Works ### Hierarchical Structure Organizations form a tree structure: * **Root Level**: Top-level organizations * **Child Levels**: Sub-organizations nested under parents * **Visualization**: Organization tree displayed as a graph/flow diagram * **Navigation**: Navigate through organization hierarchy ### User Management Users are managed across organizations: * **User Creation**: Create users and assign to organizations * **Multiple Organizations**: Assign users to multiple organizations * **Role Assignment**: Assign roles directly to users * **Group Membership**: Add users to groups ### Group Management Groups organize users within organizations: * **Group Creation**: Create groups within organizations * **Hierarchical Groups**: Create parent-child group structures * **User Assignment**: Add users to groups * **Role Assignment**: Assign roles to groups ### Role Management Roles define permission sets: * **Role Creation**: Create roles within organizations * **Permission Assignment**: Assign permissions to roles * **Permission Groups**: Include permission groups in roles * **User/Group Assignment**: Assign roles to users or groups ### Permission System Permissions control access: * **Resource-Based**: Permissions apply to specific resources * **Action-Based**: Permissions define allowed actions * **Conditional**: Permissions can have conditions * **Inheritance**: Permissions can be inherited through groups ## Organization Features ### Organization Tree Visual representation of organization hierarchy: * **Graph View**: Interactive graph showing organization relationships * **Node Representation**: Each organization shown as a node * **Parent-Child Links**: Visual connections between parent and child organizations * **Navigation**: Click nodes to view details or add children ### Multi-Organization Support Users can belong to multiple organizations: * **Organization Selection**: Users can switch between organizations * **Primary Organization**: One organization designated as primary * **Cross-Organization Access**: Users can access resources from multiple organizations * **Organization Context**: System context switches based on selected organization ### Access Control Comprehensive access control system: * **Role-Based Access Control (RBAC)**: Permissions assigned through roles * **Group-Based Access**: Permissions inherited through group membership * **User-Level Permissions**: Direct permission assignments to users * **Resource-Level Control**: Permissions apply to specific resources ## Using Organization Management Organization management features can be: * **Created**: Create organizations, users, groups, and roles * **Edited**: Modify organization structure, user assignments, group membership, and role permissions * **Deleted**: Remove organizations, users, groups, and roles (with proper validation) * **Visualized**: View organization hierarchy as a tree/graph * **Managed**: Manage permissions and access control ## Getting Started 1. **[Managing Organizations](/mbrix/organization/managing-organizations)**: Learn how to create and manage organizations 2. **[Managing Users](/mbrix/organization/managing-users)**: Learn how to create and manage users 3. **[Managing Groups](/mbrix/organization/managing-groups)**: Learn how to create and manage groups 4. **[Managing Roles](/mbrix/organization/managing-roles)**: Learn how to create and manage roles ## Related Introduction * [Objects Introduction](/mbrix/mobjects) - Understand how organizations relate to Object data * [Workflows Introduction](/mbrix/workflows) - Learn about workflows that can be organization-scoped --- # Managing Groups URL: /mbrix/organization/managing-groups Learn how to create, edit, and manage groups within organizations *** title: Managing Groups description: Learn how to create, edit, and manage groups within organizations ------------------------------------------------------------------------------ # Managing Groups Groups are collections of users within an organization. Groups can have hierarchical structures and roles assigned, allowing you to organize users and manage permissions efficiently. ## Group Overview Groups have the following properties: * **Name**: Unique name for the group within an organization * **Description**: Optional description explaining the group's purpose * **Organization**: The organization the group belongs to * **Parent Group**: Optional parent group for hierarchical structure * **Roles**: Roles assigned to the group * **Users**: Users who belong to the group ## Creating Groups ### Required Information * **Name**: Unique name for the group (required) * **Description**: Optional description * **Organization**: Organization the group belongs to (required, set automatically) * **Roles**: Optional roles to assign ### Configuration Steps 1. Navigate to the Groups page 2. Click the **"Add Group"** button (or similar action) 3. Fill in the group form: #### Enter Group Name Provide a unique name for the group within the organization. **Required**: Yes **Field**: Name **Validation**: Must be unique within the organization **Example**: "Engineering Team", "Sales Department", "Administrators" #### Enter Description Provide an optional description explaining the group's purpose. **Required**: No **Field**: Description **Example**: "Group for engineering team members" #### Select Roles (Optional) Choose roles to assign to the group. **Required**: No **Field**: Roles **How to select**: * Use the multi-select dropdown * Search for roles by name * Select multiple roles * Roles are scoped to the group's organization **Note**: Users in the group inherit roles assigned to the group. 4. Click **"Save"** to create the group ## Editing Groups To edit an existing group: 1. Navigate to the Groups page 2. Find the group in the groups list 3. Click the **"Edit"** icon next to the group 4. The group form opens with existing data 5. Modify: * **Name**: Can be changed (must remain unique) * **Description**: Can be changed * **Roles**: Add or remove roles 6. Click **"Save"** to apply changes **Note**: Organization and parent group typically cannot be changed after creation. ## Group Hierarchy Groups can have hierarchical structures: * **Parent Groups**: Groups that contain other groups * **Child Groups**: Groups that belong to parent groups * **Inheritance**: Child groups can inherit permissions from parent groups * **Nested Levels**: Groups can have multiple levels of nesting ### Creating Child Groups To create a child group: 1. Navigate to the Groups page 2. Find the parent group 3. Use group management options to create a child group 4. Configure the child group similar to creating a regular group **Note**: Child groups inherit the parent group's organization. ## Managing Group Roles ### Assigning Roles to Groups To assign roles to a group: 1. Edit the group 2. In the Roles field, select roles 3. Save changes **How it works**: Users in the group automatically inherit roles assigned to the group. ### Removing Roles from Groups To remove roles from a group: 1. Edit the group 2. In the Roles field, deselect roles 3. Save changes **Note**: Removing roles from a group affects all users in that group. ## Managing Group Users ### Adding Users to Groups Users can be added to groups through: * **User Management**: Edit user and add to groups * **Group Management**: Edit group and add users (if supported) **How it works**: Users inherit roles from groups they belong to. ### Removing Users from Groups Users can be removed from groups through: * **User Management**: Edit user and remove from groups * **Group Management**: Edit group and remove users (if supported) **Note**: Removing a user from a group removes inherited roles from that group. ## Group List Features ### Search Groups Use the search bar to find groups: * **Search By**: Group name * **Real-time**: Results update as you type * **Case Insensitive**: Search is case-insensitive ### View Group Details Click on a group to view details: * **Group Information**: Name, description, organization, parent group * **Roles**: Roles assigned to the group * **Users**: Users who belong to the group * **Created/Updated**: Timestamps and user information ### Delete Groups To delete a group: 1. Navigate to the Groups page 2. Find the group in the list 3. Click the **"Delete"** icon 4. Confirm deletion in the confirmation dialog **Warning**: Deleting a group removes role assignments for all users in that group. Ensure the group is no longer needed before deletion. ## Group Permissions Groups can have permissions configured: * **Resource Permissions**: Permissions for specific resources (Objects, workflows, etc.) * **Widget Permissions**: Permissions for dashboard widgets * **Nested 360 Permissions**: Permissions for nested 360 views **Note**: Permission configuration is typically done through the group detail/edit page. ## Best Practices ### Group Creation * **Meaningful Names**: Use clear, descriptive names for groups * **Descriptions**: Add descriptions to explain group purpose * **Logical Organization**: Organize groups logically within organizations * **Appropriate Roles**: Assign roles that match group responsibilities ### Hierarchy Management * **Logical Structure**: Create hierarchical structures that make sense * **Appropriate Depth**: Avoid too many nesting levels * **Clear Relationships**: Ensure parent-child relationships are clear ### Role Assignment * **Group-Level Roles**: Assign common roles at the group level * **User-Level Roles**: Assign specific roles at the user level when needed * **Minimal Permissions**: Follow principle of least privilege ## Related Introduction * [Organization Introduction](/mbrix/organization) - Overview of organization management * [Managing Organizations](/mbrix/organization/managing-organizations) - Learn about organizations groups belong to * [Managing Users](/mbrix/organization/managing-users) - Learn how to add users to groups * [Managing Roles](/mbrix/organization/managing-roles) - Understand roles assigned to groups --- # Managing Organizations URL: /mbrix/organization/managing-organizations Learn how to create, edit, and manage hierarchical organizations *** title: Managing Organizations description: Learn how to create, edit, and manage hierarchical organizations ----------------------------------------------------------------------------- # Managing Organizations Organizations are hierarchical entities that represent companies, departments, or business units. They form a tree structure where organizations can have parent-child relationships. ## Organization Structure Organizations are displayed as a visual tree/graph: * **Graph View**: Interactive graph showing organization relationships * **Node Representation**: Each organization shown as a node * **Parent-Child Links**: Visual connections between parent and child organizations * **Hierarchical Layout**: Automatic layout positioning based on relationships ## Creating Organizations ### Create Root Organization To create a root (top-level) organization: 1. Navigate to the Organizations page 2. Click the **"Add Organization"** button (or similar action) 3. Enter the organization name 4. Leave parent organization empty (or select "None") 5. Click **"Create"** to save **Required**: Organization name ### Create Child Organization To create a child organization under a parent: 1. Navigate to the Organizations page 2. Find the parent organization in the graph 3. Click the **"Create Child"** option from the organization node menu 4. Enter the child organization name 5. Click **"Create"** to save **Required**: Organization name, Parent organization (automatically set) **How it works**: The child organization is created with the selected parent organization as its parent. The graph automatically updates to show the new relationship. ## Editing Organizations To edit an organization: 1. Navigate to the Organizations page 2. Find the organization in the graph 3. Click the **"Edit"** option from the organization node menu 4. The organization name becomes editable 5. Modify the name 6. Click the **"Save"** icon (checkmark) to save changes 7. Click the **"Cancel"** icon (X) to discard changes **Note**: You can only edit the organization name. Parent-child relationships are managed through creating child organizations. ## Viewing Organization Details To view organization details: 1. Navigate to the Organizations page 2. Find the organization in the graph 3. Click the **"Display Details"** option from the organization node menu 4. A dialog opens showing: * **Organization Name**: The name of the organization * **Parent Organization**: The parent organization (if any) * **Is Root**: Whether this is a root organization * **Created At**: When the organization was created * **Updated At**: When the organization was last updated * **Created By**: User who created the organization * **Updated By**: User who last updated the organization ## Organization Hierarchy ### Understanding Hierarchy Organizations form a tree structure: * **Root Organizations**: Top-level organizations without parents * **Child Organizations**: Sub-organizations that belong to parent organizations * **Nested Levels**: Organizations can have multiple levels of nesting * **Visual Representation**: Hierarchy displayed as a graph with nodes and edges ### Navigating the Graph * **Zoom**: Use zoom controls to zoom in/out * **Pan**: Click and drag to pan the graph * **Fit View**: Click refresh icon to fit all organizations in view * **Node Interaction**: Click nodes to access menu options ## Best Practices ### Organization Naming * **Clear Names**: Use clear, descriptive names for organizations * **Consistent Naming**: Use consistent naming conventions across organizations * **Hierarchical Names**: Consider including parent context in child names (optional) ### Hierarchy Design * **Logical Structure**: Organize organizations in a logical hierarchy * **Appropriate Depth**: Avoid too many nesting levels (typically 2-4 levels) * **Balanced Structure**: Balance the hierarchy to avoid overly deep or wide trees ### Organization Management * **Regular Review**: Review organization structure periodically * **Cleanup**: Remove unused organizations * **Documentation**: Document organization structure and purpose ## Related Introduction * [Organization Introduction](/mbrix/organization) - Overview of organization management * [Managing Users](/mbrix/organization/managing-users) - Learn how to assign users to organizations * [Managing Groups](/mbrix/organization/managing-groups) - Understand groups within organizations * [Managing Roles](/mbrix/organization/managing-roles) - Learn about roles scoped to organizations --- # Managing Roles URL: /mbrix/organization/managing-roles Learn how to create, edit, and manage roles with permissions *** title: Managing Roles description: Learn how to create, edit, and manage roles with permissions ------------------------------------------------------------------------- # Managing Roles Roles define sets of permissions that can be assigned to users or groups. Roles are scoped to organizations and control what actions users can perform on resources. ## Role Overview Roles have the following properties: * **Name**: Unique name for the role within an organization * **Description**: Description explaining the role's purpose * **Organization**: The organization the role belongs to * **Permissions**: Individual permissions assigned to the role * **Permission Groups**: Permission groups assigned to the role ## Creating Roles ### Required Information * **Name**: Unique name for the role (required) * **Description**: Description of the role (required) ### Configuration Steps 1. Navigate to the Roles page 2. Click the **"Add Role"** button (or similar action) 3. Fill in the role form: #### Enter Role Name Provide a unique name for the role. **Required**: Yes **Field**: Name **Validation**: Must be unique within the organization **Example**: "Admin Role", "Viewer Role", "Editor Role" #### Enter Description Provide a description explaining the role's purpose and responsibilities. **Required**: Yes **Field**: Description **Example**: "Full access to all resources", "Read-only access to reports" #### Select Permissions (Optional) Choose individual permissions to assign to the role. **Required**: No **Field**: Permissions **How to select**: * Use the multi-select dropdown with search * Search for permissions by name * Select multiple permissions * Permissions define what actions can be performed on resources **Permission Types**: * **Resource Permissions**: Permissions for specific resources (tables, rows, columns, JSON keys) * **Action Permissions**: Permissions for specific actions (read, write, delete, etc.) * **Conditional Permissions**: Permissions with conditions (ABAC) #### Select Permission Groups (Optional) Choose permission groups to assign to the role. **Required**: No **Field**: Permission Groups **How to select**: * Use the multi-select dropdown with search * Search for permission groups by name * Select multiple permission groups * Permission groups contain collections of related permissions **How it works**: Assigning a permission group assigns all permissions in that group to the role. 4. Click **"Save"** to create the role ## Editing Roles To edit an existing role: 1. Navigate to the Roles page 2. Find the role in the roles list 3. Click the **"Edit"** icon next to the role 4. The role form opens with existing data 5. Modify: * **Name**: Can be changed (must remain unique) * **Description**: Can be changed * **Permissions**: Add or remove individual permissions * **Permission Groups**: Add or remove permission groups 6. Click **"Save"** to apply changes **Note**: Changes to role permissions affect all users and groups with that role assigned. ## Understanding Permissions ### Permission Structure Permissions define access control: * **Resource Type**: What resource the permission applies to (TABLE, ROW, COLUMN, JSON\_KEY) * **Resource Name**: The specific resource (table name, column name, etc.) * **Resource Identifier**: For row-level permissions, the primary key or condition * **Actions**: What actions are allowed (read, write, delete, etc.) - represented as bitmask * **Conditions**: Optional conditions for attribute-based access control (ABAC) ### Permission Groups Permission groups organize related permissions: * **Grouped Permissions**: Collections of permissions grouped together * **Easier Management**: Assign multiple permissions at once * **Logical Organization**: Organize permissions by function or resource type ### Permission Assignment Permissions can be assigned: * **Directly**: Assign individual permissions to roles * **Through Groups**: Assign permission groups to roles (includes all permissions in group) * **Combined**: Use both individual permissions and permission groups ## Role Assignment Roles can be assigned to: * **Users**: Direct role assignment to individual users * **Groups**: Role assignment to groups (users inherit group roles) ### Assigning Roles to Users To assign a role to a user: 1. Edit the user 2. In the Roles field, select the role 3. Save changes **How it works**: User gains all permissions defined in the assigned role. ### Assigning Roles to Groups To assign a role to a group: 1. Edit the group 2. In the Roles field, select the role 3. Save changes **How it works**: All users in the group inherit the role and its permissions. ## Role List Features ### Search Roles Use the search bar to find roles: * **Search By**: Role name * **Real-time**: Results update as you type * **Case Insensitive**: Search is case-insensitive ### View Role Details Click on a role to view details: * **Role Information**: Name, description, organization * **Permissions**: Individual permissions assigned * **Permission Groups**: Permission groups assigned * **Assigned To**: Users and groups with this role * **Created/Updated**: Timestamps and user information ### Delete Roles To delete a role: 1. Navigate to the Roles page 2. Find the role in the list 3. Click the **"Delete"** icon 4. Confirm deletion in the confirmation dialog **Warning**: Deleting a role removes permissions from all users and groups with that role assigned. Ensure the role is no longer needed before deletion. ## Best Practices ### Role Design * **Clear Names**: Use clear, descriptive names for roles * **Descriptive Descriptions**: Explain role purpose and scope * **Logical Permissions**: Assign permissions that make sense together * **Minimal Permissions**: Follow principle of least privilege ### Permission Management * **Permission Groups**: Use permission groups for common permission sets * **Individual Permissions**: Use individual permissions for specific needs * **Regular Review**: Review role permissions periodically * **Documentation**: Document role purposes and permission rationale ### Role Assignment * **Group-Level**: Assign common roles at the group level * **User-Level**: Assign specific roles at the user level when needed * **Avoid Over-Assignment**: Don't assign more roles than necessary * **Regular Review**: Review role assignments regularly ## Related Introduction * [Organization Introduction](/mbrix/organization) - Overview of organization management * [Managing Organizations](/mbrix/organization/managing-organizations) - Learn about organizations roles belong to * [Managing Users](/mbrix/organization/managing-users) - Learn how to assign roles to users * [Managing Groups](/mbrix/organization/managing-groups) - Learn how to assign roles to groups --- # Managing Users URL: /mbrix/organization/managing-users Learn how to create, edit, and manage users across multiple organizations *** title: Managing Users description: Learn how to create, edit, and manage users across multiple organizations -------------------------------------------------------------------------------------- # Managing Users Users are individuals who access the system. Users can belong to multiple organizations and have roles assigned to control their access and permissions. ## User Overview Users have the following properties: * **Username**: Unique identifier for the user * **Email**: User's email address (unique, required) * **Organizations**: One or more organizations the user belongs to * **Roles**: Roles assigned to the user (optional) * **Primary Organization**: One organization designated as primary ## Creating Users ### Required Information * **Username**: Unique username for the user (required) * **Email**: User's email address (required, must be unique) * **Organizations**: At least one organization (required) ### Configuration Steps 1. Navigate to the Users page 2. Click the **"Add User"** button (or similar action) 3. Fill in the user form: #### Enter Username Provide a unique username for the user. **Required**: Yes **Field**: Username **Validation**: Must be unique #### Enter Email Provide the user's email address. **Required**: Yes **Field**: Email **Validation**: * Must be a valid email format * Must be unique across all users * Cannot be changed after user creation #### Select Organizations Choose one or more organizations for the user. **Required**: Yes (at least one organization) **Field**: Organizations **How to select**: * Use the multi-select dropdown * Search for organizations by name * Select multiple organizations * The first selected organization becomes the primary organization **Note**: Users can belong to multiple organizations, allowing them to switch between organization contexts. #### Select Roles (Optional) Choose roles to assign to the user. **Required**: No **Field**: Roles **How to select**: * Use the multi-select dropdown * Search for roles by name * Select multiple roles * Roles are scoped to the user's organizations **Note**: Roles can also be assigned through group membership. 4. Click **"Save"** to create the user ## Editing Users To edit an existing user: 1. Navigate to the Users page 2. Find the user in the users list 3. Click the **"Edit"** icon next to the user 4. The user form opens with existing data 5. Modify: * **Username**: Can be changed * **Email**: Cannot be changed (disabled field) * **Organizations**: Add or remove organizations * **Roles**: Add or remove roles 6. Click **"Save"** to apply changes **Note**: Email cannot be changed after user creation. To change email, you may need to create a new user. ## User Organization Management ### Adding Organizations to Users To add an organization to an existing user: 1. Edit the user 2. In the Organizations field, select additional organizations 3. Save the changes **Note**: Users must belong to at least one organization. You cannot remove all organizations from a user. ### Removing Organizations from Users To remove an organization from a user: 1. Edit the user 2. In the Organizations field, deselect the organization 3. Save the changes **Validation**: Users must have at least one organization. If removing an organization would leave the user with no organizations, the operation will fail. ### Primary Organization The primary organization is automatically set: * **First Organization**: The first organization selected becomes primary * **Organization Order**: Primary organization is typically the first in the list * **Context Switching**: Users can switch between organizations, but primary is used as default ## User Role Management ### Assigning Roles Roles can be assigned to users in two ways: **Direct Assignment**: 1. Edit the user 2. Select roles in the Roles field 3. Save changes **Through Groups**: 1. Add user to a group 2. Assign roles to the group 3. User inherits group roles ### Removing Roles To remove roles from a user: 1. Edit the user 2. Deselect roles in the Roles field 3. Save changes **Note**: Roles assigned through groups cannot be removed directly from the user. Remove the user from the group or remove roles from the group. ## User List Features ### Search Users Use the search bar to find users: * **Search By**: Username and email * **Real-time**: Results update as you type * **Case Insensitive**: Search is case-insensitive ### View User Details Click on a user to view details: * **User Information**: Username, email, organizations, roles * **Created/Updated**: Timestamps and user information ### Delete Users To delete a user: 1. Navigate to the Users page 2. Find the user in the list 3. Click the **"Delete"** icon 4. Confirm deletion in the confirmation dialog **Warning**: Deleting a user is permanent and cannot be undone. Ensure the user is no longer needed before deletion. ## Best Practices ### User Creation * **Unique Usernames**: Use unique, meaningful usernames * **Valid Emails**: Ensure email addresses are valid and accessible * **Organization Assignment**: Assign users to appropriate organizations * **Role Assignment**: Assign roles based on user responsibilities ### Organization Management * **Multiple Organizations**: Assign users to multiple organizations when they need cross-organization access * **Primary Organization**: Choose appropriate primary organization * **Regular Review**: Review user organization assignments periodically ### Role Management * **Appropriate Roles**: Assign roles that match user responsibilities * **Minimal Permissions**: Follow principle of least privilege * **Group-Based Roles**: Use groups for common role assignments ## Related Introduction * [Organization Introduction](/mbrix/organization) - Overview of organization management * [Managing Organizations](/mbrix/organization/managing-organizations) - Learn about organizations users belong to * [Managing Groups](/mbrix/organization/managing-groups) - Learn about groups users can belong to * [Managing Roles](/mbrix/organization/managing-roles) - Understand roles assigned to users --- # Creating Picklists URL: /mbrix/picklists/creating-picklists *** ## title: Creating Picklists Picklists are created in a single modal where you configure the **Picklist Category** and add **Picklist Items** all at once. Both the category and its items are created together when you save. Creating Picklists Interface ## Overview A picklist consists of: 1. **Picklist Category**: A container that groups related options (e.g., "Status", "Priority") 2. **Picklist Items**: Individual options within the category (e.g., "Active", "Inactive", "Pending") ## Creating a Picklist Category A Picklist Category is the container for your picklist items. Configure the following fields: ### Category Fields | Field | Type | Description | | ------------- | ------ | -------------------------------------------------------------------------------------------- | | `name` | string | Unique name for the category (e.g., "Status", "Priority", "Country") - **Required** | | `description` | string | Optional description explaining the category's purpose | | `variant` | enum | Category variant: `SINGLE_SELECT` (single selection) or `MULTI_SELECT` (multiple selections) | **Note**: The `variant` field determines whether users can select one option or multiple options from the picklist when used in Object fields. ### Example: Creating a Status Category When creating a Status category, configure: * **Name**: "Record Status" * **Variant**: SINGLE\_SELECT (users can select one status at a time) * **Description**: "Standard status options for records" ## Adding Picklist Items In the same modal, below the category fields, add items to the picklist. Each item represents an option users can select. Click the "Add Item" button to add new items to the table. ### Item Fields | Field | Type | Description | | -------------- | ------- | ---------------------------------------------------------------------------------------- | | `name` | string | Display name shown to users (e.g., "Active", "Inactive") - **Required** | | `status` | enum | Item status: `ACTIVE` (visible and selectable) or `INACTIVE` (hidden from selection) | | `color` | string | Optional color code for visual distinction (e.g., "#00FF00" for green) | | `displayOrder` | integer | Order in which the item appears in the dropdown - **Automatically set by drag and drop** | **Note**: The display order is automatically determined by the position of items in the table. You can reorder items by dragging them up or down in the items table. ### Example: Adding Status Items When adding status items to a Status category, configure: **Item 1: Active** * **Name**: "Active" * **Status**: ACTIVE * **Color**: "#00FF00" (green) **Item 2: Inactive** * **Name**: "Inactive" * **Status**: ACTIVE * **Color**: "#FF0000" (red) **Item 3: Pending** * **Name**: "Pending" * **Status**: ACTIVE * **Color**: "#FFA500" (orange) ## Complete Example: Creating a Priority Picklist ### Step 1: Create the Category Create a Priority category with: * **Name**: "Priority" * **Variant**: SINGLE\_SELECT * **Description**: "Priority levels for tasks and records" ### Step 2: Add Items to the Category Add the following items to the Priority category (drag to reorder as needed): **Item 1: Low** * **Name**: "Low" * **Status**: ACTIVE * **Color**: "#90EE90" (light green) **Item 2: Medium** * **Name**: "Medium" * **Status**: ACTIVE * **Color**: "#FFD700" (amber) **Item 3: High** * **Name**: "High" * **Status**: ACTIVE * **Color**: "#FF6347" (red) **Item 4: Critical** * **Name**: "Critical" * **Status**: ACTIVE * **Color**: "#DC143C" (crimson) ## Best Practices ### Naming Conventions * **Category Names**: Use clear, descriptive names (e.g., "Record Status", "Task Priority") * **Item Names**: Keep item names concise and consistent (e.g., "Active", "Inactive", not "Active Status", "Inactive Status") ### Display Order * Items are ordered by their position in the items table * Drag and drop items to reorder them * Most commonly used items should appear first * Consider alphabetical ordering for long lists ### Colors * Use colors consistently across related picklists * Choose colors that are accessible and distinguishable * Use standard color codes (hex format: `#RRGGBB`) * Colors help users quickly identify picklist values in forms and reports ### Status Management * Set `status: "ACTIVE"` for items currently in use and visible in dropdowns * Set `status: "INACTIVE"` to hide items without deleting them (useful for historical data or deprecated options) * Inactive items won't appear in dropdown selections but existing records using them remain valid ## Using Picklists in Objects
Using Picklists in Objects
After creating a picklist, you can use it in Object fields: 1. When defining a field in an Object, select the field type as **Picklist** 2. Configure the field to reference your picklist category by selecting the category from the dropdown 3. The picklist items will appear as dropdown options in forms 4. The variant you selected when creating the picklist (SINGLE\_SELECT or MULTI\_SELECT) determines whether users can select one or multiple values ## Next Steps * **[Field Types](/mbrix/mobjects/field-types)**: See how picklist fields work in Objects --- # Picklists Introduction URL: /mbrix/picklists *** title: Picklists Introduction *** Picklists are predefined sets of options that can be used in Object fields to provide dropdown selections. They help ensure data consistency and improve user experience by offering standardized choices. ## What are Picklists? Picklists consist of: * **Picklist Categories**: Groups that organize related picklist items (e.g., "Status", "Priority", "Country") * **Picklist Items**: Individual options within a category (e.g., "Active", "Inactive", "Pending" within a Status category) ## Key Concepts ### Picklist Categories A **Picklist Category** is a container that groups related options together. Each category has: * **Name**: Unique identifier for the category (required) * **Variant**: Category variant - `SINGLE_SELECT` (single selection) or `MULTI_SELECT` (multiple selections) * **Description**: Optional explanation of the category's purpose **Note**: The variant determines whether users can select one option or multiple options when the picklist is used in Object fields. ### Picklist Items A **Picklist Item** is an individual option within a category. Each item has: * **Name**: Display name shown to users (required) * **Status**: Active/Inactive state - determines if the item is visible and selectable * **Color**: Optional color code for visual distinction (hex format: `#RRGGBB`) * **Display Order**: Order in which items appear - automatically set by drag and drop positioning in the items table ## Use Cases Picklists are commonly used for: * **Status Fields**: Active, Inactive, Pending, Completed * **Priority Levels**: Low, Medium, High, Critical * **Country/Region Selection**: List of countries or regions * **Category Classification**: Product categories, document types * **Standardized Options**: Any field requiring predefined choices ## Benefits * **Data Consistency**: Ensures users select from valid options only * **Better UX**: Provides clear, searchable dropdown options * **Easier Reporting**: Standardized values make reporting and analysis easier * **Reusability**: Same picklist can be used across multiple Objects ## Getting Started 1. **[Creating Picklists](/mbrix/picklists/creating-picklists)**: Learn how to create picklist categories and items ## Related Introduction * [Objects](/mbrix/mobjects) - Learn about custom data models * [Field Types](/mbrix/mobjects/field-types) - See how picklists are used in Object fields * [Resolve Picklist Field](/mbrix/workflows/functions/system-functions/resolve-picklist-field) - Function to resolve picklist values in workflows --- # Configuring Report Settings URL: /mbrix/reports/configuring-report-settings *** ## title: Configuring Report Settings The Report Settings dialog allows you to configure various aspects of your report through six main tabs: General Settings, Drill-Down Settings, KPI Settings, Chart Settings, Kanban Settings, and Card View Settings. Each tab contains specific configuration options for different report types and visualizations. ## Accessing Settings To access report settings: 1. Open a report in the Report Designer 2. Click the **Settings icon** (gear icon) in the top toolbar 3. The Settings modal opens with tabs for different setting categories ## General Settings Configure general report-wide settings that apply to all report types. General Settings Tab Interface ### Sort Options Define the default sort order for the report: 1. **Add Sort Fields**: Click to add one or more fields to sort by 2. **Select Field**: Choose the field to sort by from the dropdown 3. **Select Order**: Choose ascending (ASC) or descending (DESC) order 4. **Multiple Sorts**: Add multiple sort fields for complex sorting (sorts are applied in order) 5. **Remove Sorts**: Delete sort fields that are no longer needed **How it works**: The report displays data sorted by the configured fields in the specified order. Multiple sort fields create a hierarchical sort. ### Report Settings Configure various display and behavior settings: #### Freeze Column Count Set the number of columns to freeze (keep visible) when scrolling horizontally in table views. **Default**: 0 **Use Case**: Useful for keeping important columns (like names or IDs) visible while scrolling through wide tables. #### Row Height Configure the height of rows in table views. **Default**: System default **Range**: Minimum 10 pixels **Use Case**: Adjust row height for better readability or to fit more data on screen. #### Enable Picklist Colors Toggle to display picklist values with their associated colors in the report. **Default**: Disabled **Use Case**: Visual distinction for picklist values makes reports easier to scan and understand. #### Report Max Read Limit Set the maximum number of records to retrieve and display in the report. **Default**: System default (typically 10,000) **Range**: 0 to maximum allowed limit **Use Case**: Limit data retrieval for performance optimization, especially for large datasets. #### Associated Flow Associate a workflow (MFlow) with the report. When a flow is associated: * The workflow can be triggered from report interactions * Custom business logic defined in the workflow is executed * The workflow can handle data validation, transformations, and side effects **How to select**: Use the flow selector dropdown to search and select a workflow by name. #### Enable Custom Header Toggle to enable custom column headers. When enabled: * You can customize header text and formatting * Headers can differ from field display names * Useful when data comes from workflows to provide user-friendly labels **Default**: Disabled ## Drill-Down Settings Configure drill-down navigation that allows users to navigate to related pages or detailed views when clicking on specific fields or data points. Drill-Down Settings Tab Interface ### Enable Drill-Down Toggle to enable or disable drill-down functionality for the report. ### Drill-Down Configuration Configure drill-down definitions with the following options: #### Drill-Down Field Select the field that will trigger the drill-down when clicked. Available fields are from the report's "Show" fields. **Required**: Yes (when drill-down is enabled) #### Drill-Down Type Choose the type of target for drill-down navigation: * **Self**: Navigate to the same report with filtered data * **Report**: Navigate to another report * **Workflow**: Navigate to a workflow * **My Tasks**: Navigate to user tasks **Required**: Yes #### Target Selection Based on the selected drill-down type, choose the specific target: * **For Report**: Select a report from the dropdown * **For Workflow**: Select a workflow from the dropdown * **For My Tasks**: No additional selection needed #### Filter Mapping Configure how fields from the current report map to filter the drill-down target: * **Source Field**: Field from the current report * **Target Field**: Field in the drill-down target to filter by * **Filter Logic**: How the filter is applied (equals, contains, etc.) ### Multiple Drill-Down Definitions You can configure multiple drill-down definitions for different fields, allowing different columns or data points to navigate to different targets. ## KPI Settings Configure settings specific to KPI (Key Performance Indicator) visualizations. KPI Settings Tab Interface ### Icon Select an icon to display alongside the KPI value. Icons help visually identify the KPI type. **How to select**: Use the icon picker to browse and select from available icons. ### KPI Value Configuration Configure how the KPI value is displayed: #### Font Color Set the color for the KPI value text. You can use: * Color picker to select a color * Hex color code (e.g., `#000000`) * CSS variable (e.g., `var(--primary)`) #### Font Size Choose the font size for the KPI value: **Options**: 12, 14, 16, 24, 28, 32 **Default**: System default #### Background Select the background theme for the KPI: * **Primary Background**: Uses the primary theme color * **Secondary Background**: Uses the secondary/accent theme color #### Disable Background Animation Toggle to disable animated background effects for the KPI. **Default**: Disabled (animation enabled) #### KPI Prefix Enter text to display before the KPI value (e.g., "$", "Total: "). #### KPI Suffix Enter text to display after the KPI value (e.g., "%", " units"). ### Variance Configuration Configure variance display to compare KPI values against goals: #### Show Variance Toggle to enable variance display, which shows the difference between the current KPI value and a goal value. **Default**: Disabled #### Goal Period When variance is enabled, select the time period for goal comparison: * **Last Month**: Compare against previous month * **Quarterly**: Compare against last 3 months * **Half Year**: Compare against last 6 months * **Year**: Compare against last 12 months #### Goal Reference Date Field Select a date field from the report's Object to use as the reference for goal period calculations. **Required**: Yes (when goal period is selected) #### Custom Goal Value If no goal period is selected, enter a custom numeric goal value to compare against. #### Custom Variance Prefix Enter text to display before the variance value (e.g., "+", "Change: "). #### Custom Variance Suffix Enter text to display after the variance value (e.g., "%", " points"). #### Is the KPI Result Positive Toggle to indicate whether higher KPI values are considered positive (good) or negative (bad). This affects variance color coding. **Default**: Enabled (higher is positive) ## Chart Settings Configure visualization-specific settings for chart reports (Bar, Line, Pie, etc.). Chart Settings Tab Interface Chart Settings Tab Interface ### X-Axis Settings Configure the horizontal axis appearance and behavior: * **Interval**: Set the interval between axis labels * **Rotation**: Rotate axis labels by degrees (0-90) * **Font Size**: Set the font size for axis labels * **Font Color**: Set the color for axis labels * **Enable Plot Bands**: Toggle to show plot bands (shaded areas) on the axis * **Enable Axis Title**: Toggle to show the axis title ### Y-Axis Settings Configure the vertical axis appearance and behavior: * **Interval**: Set the interval between axis labels * **Rotation**: Rotate axis labels by degrees (0-90) * **Font Size**: Set the font size for axis labels * **Font Color**: Set the color for axis labels * **Minimum Value**: Set the minimum value displayed on the axis * **Maximum Value**: Set the maximum value displayed on the axis * **Enable Axis Title**: Toggle to show the axis title ### Legend Settings Configure the chart legend: * **Enabled**: Toggle to show or hide the legend * **Max Height**: Set the maximum height for the legend * **Font Size**: Set the font size for legend text * **Font Color**: Set the color for legend text * **Align**: Set horizontal alignment (Left, Right, Center) * **Vertical Align**: Set vertical alignment (Top, Bottom, Middle) * **Layout**: Set legend layout (Horizontal, Vertical, Proximate) ### Data Label Settings Configure labels displayed on chart elements: * **Enabled**: Toggle to show or hide data labels * **Inside**: Toggle to display labels inside chart elements * **Font Size**: Set the font size for data labels * **Font Color**: Set the color for data labels * **Allow Overlap**: Toggle to allow overlapping labels * **Rotation**: Rotate labels by degrees (0-90) ### Visual Map Settings Configure visual map (color scale) for heat maps and similar visualizations: * **Min Value**: Set the minimum value for the color scale * **Max Value**: Set the maximum value for the color scale * **Calculable**: Toggle to enable interactive value calculation * **Orientation**: Set orientation (Horizontal, Vertical) * **Position**: Set position (Left, Center, Right) * **Enable Zoom**: Toggle to enable zoom functionality * **Zoom Type**: Select zoom type (Inside, Slider) ## Kanban Settings Configure settings specific to Kanban visualizations. Kanban Settings Tab Interface ### Card & Display Settings Configure how cards are displayed in the Kanban board: #### Summarize By Select the field to use as the card title/summary. Options include: * **Record Number**: Use the record's system ID * **Field Selection**: Choose any field from the report's selected fields **Required**: Yes #### Show Field Labels Toggle to display field labels alongside values on cards. **Default**: Enabled #### Default Color Set the default color for cards. Cards can be colored based on grouping fields or use this default. #### Hide Fields Select fields to hide from card display. Useful for hiding system fields or less important data. **Multi-select**: Yes ### Column Settings Configure Kanban column appearance: * **Column Width**: Set the width of each column * **Min Column Width**: Set the minimum column width * **Max Column Width**: Set the maximum column width * **Max Columns**: Set the maximum number of columns to display **Note**: Column grouping is configured in the main report configuration (Group By fields), not in settings. ## Card View Settings Configure settings specific to Card View visualizations. Card View Settings Tab Interface ### Background Theme Select the background theme for cards: * **Primary Background**: Uses the primary theme color * **Secondary Background**: Uses the secondary/accent theme color **Default**: Secondary ### Card Layout Settings Configure the appearance of individual cards: * **Card Height**: Set the height of each card * **Show Card Borders**: Toggle to show borders around cards * **Card Border Radius**: Set the border radius for rounded corners * **Card Shadow**: Toggle to add shadow effects to cards ### Field Configuration Configure which fields are displayed on cards: #### Title Field Select the field to display as the card title (main heading). **Required**: Yes #### Title Percentage Field Select a numeric field to display as a percentage alongside the title. **Optional**: Yes #### Tag Fields Select up to 3 fields to display as tags on the card. **Multi-select**: Yes (up to 3 fields) #### Bar Field Select a numeric field to display as a progress bar on the card. **Optional**: Yes #### Right Value Field Select a field to display on the right side of the card (typically a value or metric). **Optional**: Yes ## Report Filters Configure filters to narrow down the data displayed in the report. Filters allow you to apply conditions that determine which records are included in the report results. **How to configure filters**: 1. Click the **Filter icon** in the top toolbar of the Report Designer 2. The filter modal opens with two tabs: * **Fields Tab**: Configure WHERE conditions for regular fields * **Measures Tab**: Configure HAVING conditions for aggregated fields ### Fields (WHERE Conditions) Fields Filter Tab Interface Filter data before aggregation using the Fields tab. This applies conditions directly to the source data. **Filter Options**: * **Field Selection**: Choose any field from the report's Object or related Objects * **Operators**: Use comparison operators such as: * Equals, Not Equals * Greater Than, Less Than, Greater Than or Equal, Less Than or Equal * Contains, Starts With, Ends With (for text fields) * In, Not In (for multiple values) * Is Null, Is Not Null * Between (for ranges) * **Value Input**: Enter filter values based on field type: * Text values for text fields * Numeric values for number fields * Date picker for date fields * Picklist selection for picklist fields * **Logic Operators**: Combine multiple conditions with: * **AND**: All conditions must be true * **OR**: At least one condition must be true * **Nested Conditions**: Create complex filter logic by grouping conditions with parentheses **Use Cases**: * Filter records by status, date range, or specific field values * Exclude certain records from the report * Show only records matching multiple criteria ### Measures (HAVING Conditions) Measures Filter Tab Interface Filter aggregated data after grouping using the Measures tab. This applies conditions to calculated values and aggregated fields. **Filter Options**: * **Aggregated Fields**: Filter by fields that use aggregation functions (SUM, AVG, COUNT, MIN, MAX, etc.) * **Operators**: Use comparison operators similar to Fields tab * **Value Comparison**: Compare aggregated values against thresholds (e.g., SUM > 1000, AVG \< 50) * **Logic Operators**: Combine multiple measure conditions with AND/OR logic **Use Cases**: * Show only groups where total sales exceed a certain amount * Filter out groups with low record counts * Display only categories meeting specific performance criteria ### Filter Management **Save Filters**: Click "Save" to apply filters to the report. Filters are saved with the report configuration. **Clear Filters**: Click "Clear Filter" to remove all filter conditions and reset the report to show all data. **Filter Persistence**: Filters are saved as part of the report configuration and will be applied whenever the report is executed. **Dynamic Filters**: Filters can be modified at any time by reopening the filter modal and adjusting conditions. **Best Practices**: * Use Fields tab filters for basic data filtering before aggregation * Use Measures tab filters to refine results after grouping and aggregation * Combine multiple conditions logically to create precise data subsets * Test filters to ensure they return expected results * Consider performance impact when filtering large datasets ## Best Practices ### General Settings * **Sort Options**: Set default sorts that match the most common use case * **Max Read Limit**: Set appropriate limits to balance performance and data completeness * **Custom Headers**: Use custom headers when reports are used in dashboards for better user experience * **Report Filters**: Use Fields tab for pre-aggregation filtering and Measures tab for post-aggregation filtering. Test filters to ensure they return expected results and consider performance impact on large datasets ### Drill-Down Settings * **Relevant Fields**: Configure drill-down only on fields that logically lead to related data * **Filter Mapping**: Properly map fields to ensure drill-down views show relevant filtered data * **User Expectations**: Ensure drill-down targets match user expectations for navigation ### KPI Settings * **Font Size**: Choose font sizes that are readable but not overwhelming * **Variance**: Enable variance for KPIs where goal comparison is meaningful * **Goal Period**: Select goal periods that match your business reporting cycles ### Chart Settings * **Axis Labels**: Configure axis labels for clarity and readability * **Data Labels**: Use data labels sparingly to avoid cluttering charts * **Legends**: Position legends where they don't obstruct chart data ### Kanban Settings * **Card Summarization**: Choose fields that clearly identify each card * **Column Width**: Set column widths that accommodate card content without excessive scrolling * **Field Visibility**: Hide fields that aren't essential for quick card scanning ### Card View Settings * **Title Field**: Choose a field that clearly identifies each card * **Tag Fields**: Limit tags to the most important categorization fields * **Bar Fields**: Use bar fields to show progress or relative values visually ## Related Introduction * [Creating Reports](/mbrix/reports/creating-reports) - Learn how to create reports * [Reports Introduction](/mbrix/reports) - Overview of reports * [Objects Introduction](/mbrix/mobjects) - Understand the data models used in reports * [Workflows Introduction](/mbrix/workflows) - Learn about workflows associated with reports --- # Creating Reports URL: /mbrix/reports/creating-reports *** ## title: Creating Reports Reports are created using the Report Designer interface. Each report queries data from Objects and displays it using various visualization types. ## Required Information * **Name**: Unique identifier for the report (required) * **Object**: The data source for the report (required) * **Show Fields**: At least one field to display (required) * **Visualization Type**: The type of chart or view to display (required) ## Configuration Steps Report Designer Interface ### 1. Open Report Designer Navigate to the Reports page and click the **"Create Report"** button (or similar action) to open the Report Designer interface. ### 2. Select Object Choose the Object that contains the data you want to report on. This Object serves as the primary data source for your report. **How to select**: Use the Object selector in the left panel to browse and select an Object. **Note**: Once an Object is selected, all its fields become available for use in the report configuration. ### 3. Configure Show Fields Add fields that you want to display in the report. These fields appear as columns in table views or as data points in charts. **How to add fields**: * Drag fields from the field tree on the left side * Drop them into the **"Show"** drag-and-drop area **Field Types**: * **Regular Fields**: Standard Object fields * **Formula Fields**: Calculated fields using expressions * **Case Fields**: Fields with conditional logic **Field Settings**: Each field has a settings icon where you can configure: * **Display Name**: Customize the column header * **Aggregation**: For numeric fields, choose aggregation (SUM, AVG, COUNT, MIN, MAX, etc.) * **Pivot**: Enable pivoting for cross-tabulation * **Column Calculations**: Add calculations like sum, average, count * **Number Formatting**: Format numeric values * **Date Summarization**: Summarize date fields by day, week, month, etc. * **Hide**: Hide the field from display * **Show as Tag**: Display picklist values as tags ### 4. Configure Group By Fields (Optional) Add fields to group data by. Grouping organizes data hierarchically and enables aggregation. **How to add fields**: * Drag fields from the field tree * Drop them into the **"Group By"** drag-and-drop area **How it works**: * Records are organized by the grouped fields * Non-grouped fields can use aggregation functions * Grouping enables pivot table functionality **Field Settings**: Group By fields have settings for: * **Display Name**: Customize the group header * **Pivot**: Enable pivoting for cross-tabulation * **Row Group**: Configure row grouping behavior * **Date Summarization**: Summarize date fields ### 5. Configure Filters (Optional) Apply filters to narrow down the data displayed in the report. **How to configure**: 1. Click the **Filter icon** in the top toolbar 2. The filter modal opens with two tabs: * **Fields Tab**: Configure WHERE conditions for regular fields * **Measures Tab**: Configure HAVING conditions for aggregated fields **Filter Configuration**: * **Fields Tab**: Filter data before aggregation * Use the Query Builder to create filter conditions * Combine multiple conditions with AND/OR logic * Filter by field values, dates, numbers, etc. * **Measures Tab**: Filter aggregated data after grouping * Filter by aggregated values (e.g., SUM > 1000) * Apply conditions to calculated measures **Clear Filters**: Click "Clear Filter" to remove all filter conditions. ### 6. Include Soft Deleted Records (Optional) Toggle whether to include soft-deleted records in the report. **Default**: Disabled (only active records shown) **How to toggle**: Use the "Include Soft Deleted" switch in the top toolbar. **Note**: This option is only available when an Object is selected. ### 7. Select Visualization Type Choose how you want to visualize the data. The available visualization types depend on your field configuration. **Available Types**: * **Grid/Table**: Display data in a table format * **Bar Chart**: Compare values across categories * **Line Chart**: Show trends over time * **Pie Chart**: Display proportions and percentages * **Donut Chart**: Similar to pie chart with center hole * **Column Chart**: Vertical bar chart * **Stacked Bar**: Horizontal bars with stacked segments * **Stacked Column**: Vertical columns with stacked segments * **Scatter Chart**: Show relationships between two variables * **Bubble Chart**: Scatter chart with size as third dimension * **KPI**: Display key performance indicators * **Kanban**: Display data in kanban board format * **Heat Map**: Display data density with colors * **Progress Bar**: Show progress indicators * **Card View**: Display data as cards * **Sankey**: Show flow relationships **How to select**: Click on the visualization type icon in the visualization selector panel. **Note**: Some visualization types require specific field configurations (e.g., charts need at least one group by field). ### 8. Configure Settings Configure additional settings for your report by clicking the **Settings icon** (gear icon) in the top toolbar. The Settings dialog contains six tabs: * **General Settings**: Sort options, max read limit, row height, flow association, custom headers * **Drill-Down Settings**: Configure drill-down navigation to other reports, workflows, or tasks * **KPI Settings**: Icon, font styling, variance, and goal configuration for KPI visualizations * **Chart Settings**: X-axis, Y-axis, legend, data labels, and visual map settings for charts * **Kanban Settings**: Card display, column width, and field visibility for Kanban boards * **Card View Settings**: Card layout, field configuration, and display options for card views For detailed information about each settings tab, see **[Configuring Report Settings](/mbrix/reports/configuring-report-settings)**. ### 9. Execute Report Click the **"Run Report"** button (or refresh icon) to execute the report and view the results. **Validation**: The system validates your configuration before execution: * At least one Show field must be configured * Visualization type must be compatible with field configuration * Required fields for selected visualization must be present **Results**: After execution, the report displays: * Data visualization based on selected type * Interactive elements (clicking, filtering, sorting) * Export options ### 10. Save Report Click the **"Save"** button to save your report configuration. **Save Dialog**: * **Name**: Enter a unique name for the report (required) * **Description**: Provide an optional description * **Folder**: Select a folder to organize the report (optional) **After Saving**: * The report is created and appears in the Reports list * A materialized view is automatically created for performance * The report can be edited, executed, or deleted as needed * The report can be used in Builder pages and dashboards ## Editing Existing Reports To edit an existing report: 1. Navigate to the Reports page 2. Find the report in the list 3. Click the **"Edit"** icon (or click on the report name) in the actions dropdown 4. The Report Designer opens with existing configuration 5. Make your desired changes 6. Click **"Save"** to apply updates **Note**: When editing, all existing configurations are loaded. You can modify fields, filters, visualization, and settings as needed. ## Advanced Features ### Formula Fields Create calculated fields using expressions: 1. Click to add a formula field 2. Enter an expression using other fields, constants, and operators 3. The formula field is added to available fields 4. Drag the formula field into Show or Group By areas **Use Cases**: Calculate totals, percentages, differences, etc. ### Case Fields Create fields with conditional logic: 1. Click to add a case field 2. Define conditions and corresponding values 3. The case field is added to available fields 4. Use case fields for categorization and conditional values **Use Cases**: Categorize data, apply conditional formatting, create derived categories ### Pivot Tables Enable pivoting for cross-tabulation: 1. Add fields to Group By 2. Enable **Pivot** setting on Group By fields 3. Configure pivot settings (row groups, column groups) 4. View data in cross-tabulated format **Use Cases**: Compare data across multiple dimensions, create summary tables ### Column Calculations Add calculations to columns: 1. Select a field in Show 2. Open field settings 3. Configure **Column Calculations** 4. Choose calculation functions (SUM, AVG, COUNT) **Use Cases**: Add totals, subtotals, running totals to columns ## Best Practices ### Field Selection * **Relevant Fields**: Select only fields needed for analysis * **Appropriate Aggregations**: Use correct aggregation functions for numeric fields * **Meaningful Names**: Use display names that are clear to end users ### Grouping * **Logical Grouping**: Group by fields that make sense for analysis * **Hierarchical Grouping**: Use multiple Group By fields for detailed breakdowns * **Date Grouping**: Use date summarization for time-based analysis ### Filtering * **Efficient Filters**: Apply filters early to reduce data volume * **Clear Conditions**: Use clear filter conditions that are easy to understand * **Test Filters**: Test filters to ensure they return expected results ### Visualization Selection * **Appropriate Type**: Choose visualization type that best represents your data * **Chart Requirements**: Ensure field configuration meets chart requirements * **User Experience**: Consider how users will interact with the visualization ### Performance * **Limit Fields**: Don't select unnecessary fields * **Use Filters**: Apply filters to reduce data volume * **Materialized Views**: Reports automatically use materialized views for performance * **Max Read Limit**: Set appropriate limits for large datasets ## Related Introduction * [Configuring Report Settings](/mbrix/reports/configuring-report-settings) - Detailed guide to all report settings * [Reports Introduction](/mbrix/reports) - Overview of reports * [Objects Introduction](/mbrix/mobjects) - Understand the data sources used in reports * [Workflows Introduction](/mbrix/workflows) - Learn about workflows associated with reports * [Builder Introduction](/mbrix/builder) - Learn how to use reports in Builder pages --- # Reports Introduction URL: /mbrix/reports *** ## title: Reports Introduction Reports are data visualization and reporting tools that enable you to create dynamic reports from Object data. Reports use materialized views for performance optimization and support multiple chart types and visualization options. ## What are Reports? Reports enable you to: * **Visualize Data**: Create charts and tables from Object data * **Build Complex Queries**: Configure queries with joins, filters, grouping, and sorting * **Optimize Performance**: Use materialized views to cache query results * **Multiple Chart Types**: Display data as bar charts, line charts, pie charts, tables, and more * **Filter and Analyze**: Apply filters and analyze data interactively * **Export Data**: Export report data to Excel and other formats ## How Reports Work ### Materialized Views Reports use PostgreSQL materialized views to cache complex query results: * **Performance**: Materialized views provide fast data retrieval for dashboards and reports * **Automatic Refresh**: Views can be refreshed when underlying data changes * **Query Optimization**: Complex queries are executed once and cached for reuse ### Report Configuration Each report consists of: * **Name**: Unique identifier for the report * **Description**: Optional description explaining the report's purpose * **Chart Type**: The type of visualization (BAR, LINE, PIE, TABLE, etc.) * **Query Configuration**: Tables, joins, fields, filters, grouping, and sorting * **Chart Settings**: Visualization appearance and behavior settings * **Object Association**: Associated Objects that serve as data sources ### Query Building Reports build SQL queries dynamically based on configuration: * **Tables**: Select source tables from Objects * **Joins**: Configure relationships between tables * **Fields**: Choose which fields to display * **Filters**: Apply WHERE conditions to filter data * **Grouping**: Group data by fields for aggregation * **Sorting**: Sort results by fields ## Report Types ### Chart Reports Visual representations of data: * **Bar Chart**: Compare values across categories * **Line Chart**: Show trends over time * **Pie Chart**: Display proportions and percentages * **Table**: Display data in tabular format ### Data Reports Tabular and detailed data views: * **Table View**: Standard table with rows and columns * **Pivot Table**: Cross-tabulated data analysis * **Summary Reports**: Aggregated data summaries ## Key Features ### Dynamic Query Building Reports build SQL queries dynamically from configuration, allowing flexible report creation without writing SQL directly. ### Materialized View Management * **Automatic Creation**: Materialized views are created automatically when reports are saved * **Refresh Management**: Views can be refreshed manually or automatically * **Update Tracking**: System tracks when views need to be refreshed ### Visualization Options * **Multiple Chart Types**: Choose from various chart types based on data * **Customizable Settings**: Configure chart appearance, colors, labels, and more * **Interactive Charts**: Click on chart elements for drill-down and filtering ### Filtering and Analysis * **Where Conditions**: Apply filters to narrow down data * **Having Conditions**: Filter aggregated data * **Additional Filters**: Apply runtime filters when viewing reports * **Drill-Down**: Navigate to detailed views from summary data ### Export Capabilities * **Excel Export**: Export report data to Excel files * **Formatted Output**: Export with formatting and styling * **Large Datasets**: Handle large datasets efficiently ## Using Reports Reports can be: * **Created**: Define new reports with query configuration and visualization settings * **Edited**: Modify existing reports and their configurations * **Executed**: Run reports to view data and visualizations * **Embedded**: Embed reports in dashboards and Builder pages * **Exported**: Export report data to Excel and other formats * **Cloned**: Clone existing reports to create similar reports quickly ## Getting Started 1. **[Creating Reports](/mbrix/reports/creating-reports)**: Learn how to create reports with step-by-step instructions 2. **[Configuring Report Settings](/mbrix/reports/configuring-report-settings)**: Configure general settings, chart settings, KPI settings, drill-down, and more 3. **Configure Fields**: Add Show fields and Group By fields 4. **Apply Filters**: Set up WHERE and HAVING conditions 5. **Choose Visualization**: Select chart type and configure settings 6. **Test and Refine**: Execute reports and refine configurations as needed ## Related Introduction * [Creating Reports](/mbrix/reports/creating-reports) - Step-by-step guide to creating reports * [Configuring Report Settings](/mbrix/reports/configuring-report-settings) - Detailed guide to all report settings * [Objects Introduction](/mbrix/mobjects) - Understand the data sources used in reports * [Workflows Introduction](/mbrix/workflows) - Learn about workflows associated with reports * [Builder Introduction](/mbrix/builder) - Learn how to use reports in Builder pages * [Datagrids Introduction](/mbrix/datagrids) - Understand how reports relate to datagrids --- # Creating Templates URL: /mbrix/templates/creating-templates *** ## title: Creating Templates Templates are created using the Template Designer interface. Each template requires a name, type, and content with variable placeholders. ## Template Details ### Required Fields * **Template Name**: Unique identifier for the template * **Template Type**: Choose from: * `EMAIL` - For email notifications * `PDF` - For PDF document generation * `DOCUMENT` - For document templates * **Content**: HTML template content with Pebble syntax variables ### Optional Fields * **Email Subject**: Required for EMAIL templates, supports variable substitution (e.g., `Order {{orderNumber}} Confirmation`) * **Folder**: Organize templates into directories for better management ## Template Content Template Content Interface Templates use Pebble Template Engine syntax for dynamic content: ### Variables ```html

Dear {{customerName}},

Your order {{orderNumber}} has been confirmed.

``` ### Conditionals ```html {% if orderStatus == "shipped" %}

Your order has been shipped!

{% endif %} ``` ### Loops ```html
    {% for item in orderItems %}
  • {{item.name}} - {{item.price}}
  • {% endfor %}
``` ## Creating a Template 1. Navigate to Template Designer 2. Click "Create Template" 3. Enter template name and select type 4. For EMAIL templates, enter email subject 5. Write template content with variables 6. Optionally select a folder for organization 7. Save the template ## Template Structure Templates should include: * HTML structure (for PDF/EMAIL) * Variable placeholders using `{{variableName}}` * Conditional logic and loops as needed * Proper formatting and styling ## Related Introduction * [Template Preview](/mbrix/templates/template-preview) - Test your templates before use * [EmailNotification](/mbrix/workflows/functions/user-interactions/email-notification) - Use templates in email workflows * [HTMLToPDF](/mbrix/workflows/functions/system-functions/html-to-pdf) - Generate PDFs from templates --- # Templates Introduction URL: /mbrix/templates *** ## title: Templates Introduction Templates are reusable content structures that use the Pebble Template Engine to generate dynamic emails and PDF documents. They support variable substitution, allowing you to create personalized content by inserting data values into predefined templates. ## What are Templates? Templates are stored content structures that contain: * **Name**: Unique identifier for the template * **Content**: The template body with variable placeholders * **Template Type**: Either `EMAIL` or `PDF` * **Metadata**: Additional configuration (e.g., email subject for email templates) * **Directory**: Organizational grouping for templates ## Template Types ### Email Templates Email templates are used to send dynamic email notifications. They include: * **Content**: HTML or plain text email body with variable placeholders * **Email Subject**: Stored in metadata, also supports variable substitution * **Variable Substitution**: Uses `{{variableName}}` syntax ### PDF Templates PDF templates are used to generate PDF documents from HTML content. They include: * **Content**: HTML template that will be converted to PDF * **Variable Substitution**: Uses `{{variableName}}` syntax for dynamic content ## Template Syntax Templates use the Pebble Template Engine syntax for variable substitution: ### Basic Variables ```html

Dear {{customerName}},

Your order {{orderNumber}} has been confirmed.

Total Amount: {{totalAmount}}

``` ### Conditional Logic ```html {% if orderStatus == "shipped" %}

Your order has been shipped!

{% else %}

Your order is being processed.

{% endif %} ``` ### Loops ```html
    {% for item in orderItems %}
  • {{item.name}} - {{item.price}}
  • {% endfor %}
``` ## Using Templates in Workflows Templates are used in several workflow functions: ### Email Notification Use templates to send dynamic emails: ```json { "templateId": "email-template-uuid", "dataObject": { "customerName": "John Doe", "orderNumber": "ORD-123", "totalAmount": "$100.00" } } ``` **Related Function**: [EmailNotification](/mbrix/workflows/functions/user-interactions/email-notification) ### HTML to PDF Generate PDF documents from templates: ```json { "templateId": "pdf-template-uuid", "dataObject": { "invoiceNumber": "INV-001", "customerName": "John Doe", "items": [...] }, "fileName": "invoice" } ``` **Related Function**: [HTMLToPDF](/mbrix/workflows/functions/system-functions/html-to-pdf) ### User Action Send email notifications as part of user actions: ```json { "templateId": "approval-notification-uuid", "dataObject": { "requestType": "Purchase Order", "amount": "$5,000" } } ``` **Related Function**: [UserAction](/mbrix/workflows/functions/user-interactions/user-action) ## Key Features ### Variable Extraction The system automatically extracts all variables used in a template, allowing you to see what data fields are required when using the template. ### Directory Organization Templates can be organized into directories for better management and organization. ### Template Preview Preview templates with sample data before using them in production workflows. ## Getting Started 1. **[Create Templates](/mbrix/templates/creating-templates)**: Learn how to create email or PDF templates 2. **[Preview Templates](/mbrix/templates/template-preview)**: Test templates with sample data before use 3. **[Use in Workflows](/mbrix/workflows/functions/user-interactions/email-notification)**: Reference templates by ID in workflow functions ## Related Introduction * [EmailNotification](/mbrix/workflows/functions/user-interactions/email-notification) - Send emails using templates * [HTMLToPDF](/mbrix/workflows/functions/system-functions/html-to-pdf) - Generate PDFs from templates * [UserAction](/mbrix/workflows/functions/user-interactions/user-action) - Use templates in user actions * [Workflows](/mbrix/workflows) - Learn about workflow creation and management --- # Template Preview URL: /mbrix/templates/template-preview *** ## title: Template Preview Template Preview allows you to test templates with sample data to verify they render correctly before using them in workflows. ## Preview Methods Template Preview Methods Interface ### Manual Test Data Enter JSON test data manually in the preview panel: ```json { "customerName": "John Doe", "orderNumber": "ORD-123", "totalAmount": "$100.00" } ``` ### Object Data Use real Object data for more accurate testing: 1. Select an Object from the dropdown 2. Select a specific MData record 3. The system automatically generates test data from the selected record 4. Preview renders with actual field values ## Using Preview Using Preview Interface 1. Open a template in Template Designer 2. Write or edit template content 3. Provide test data (manual JSON or select Object/MData) 4. Click "Preview" to see rendered output 5. Verify variables are substituted correctly 6. Check formatting and styling ## Preview Features * **Real-time Rendering**: See how template renders with provided data * **Variable Validation**: Verify all variables are correctly substituted * **Format Checking**: Ensure HTML/PDF formatting is correct * **Data Testing**: Test with different data sets before production use ## Best Practices 1. **Test with Real Data**: Use Object/MData for realistic previews 2. **Test Edge Cases**: Try empty values, nulls, and missing fields 3. **Verify Formatting**: Check how content appears in final output 4. **Validate Variables**: Ensure all `{{variables}}` are properly replaced ## Related Introduction * [Creating Templates](/mbrix/templates/creating-templates) - Learn how to create templates * [EmailNotification](/mbrix/workflows/functions/user-interactions/email-notification) - Use templates in workflows * [HTMLToPDF](/mbrix/workflows/functions/system-functions/html-to-pdf) - Generate PDFs from templates --- # Creating Vectors URL: /mbrix/vectors/creating-vectors Learn how to create vector stores with data sources, embedding models, and knowledge graphs *** title: Creating Vectors description: Learn how to create vector stores with data sources, embedding models, and knowledge graphs -------------------------------------------------------------------------------------------------------- # Creating Vectors Vectors are created through a multi-step process that includes configuring basic information, selecting data sources, and building knowledge graphs. This guide walks you through each step. ## Required Information * **Name**: Unique name for the vector (required) * **Description**: Description of the vector's purpose (required) * **Model Provider**: AI provider for embeddings (required) * **Embedding Model**: Specific embedding model (required) * **Data Sources**: At least one data source (Objects, MFlows, MReports, or Files) ## Creation Process Vector creation consists of three steps: 1. **Basic Information**: Configure name, description, and embedding model 2. **Data Source**: Select data sources (Objects, MFlows, MReports, Files) 3. **Knowledge Graph**: Build knowledge graph defining relationships ## Step 1: Basic Information Configure the basic information for your vector: ### Enter Vector Name Provide a unique name for the vector. **Required**: Yes **Field**: Name **Validation**: Must be unique **Example**: "Customer Data Vector", "Product Knowledge Base", "Document Repository" ### Enter Description Provide a description explaining the vector's purpose and what data it contains. **Required**: Yes **Field**: Description **Example**: "Vector store containing customer information and order history for AI agent context" ### Select Model Provider Choose the AI provider for generating embeddings. **Required**: Yes **Field**: Model Provider **Available Providers**: * **OpenAI**: OpenAI embedding models * **Ollama**: Local Ollama embedding models * **VertexAI**: Google Vertex AI embedding models **How to select**: Use the dropdown to select a provider. The available embedding models will update based on your selection. ### Select Embedding Model Choose the specific embedding model to use. **Required**: Yes **Field**: Embedding Model **How to select**: * After selecting a provider, choose from available embedding models * Different providers offer different models * Model selection affects embedding quality and dimensions **Note**: Use the same embedding model consistently for a vector to ensure consistent embeddings. ### Configure Model Settings (Optional) Configure additional model settings: * **Temperature**: Controls randomness in embeddings (default: 0.7) * **Top K**: Number of top results to return in searches (default: 3) **Note**: These settings can typically be adjusted after vector creation. ### Navigate to Next Step Click **"Next"** or **"Confirm"** to proceed to the Data Source step. ## Step 2: Data Source Select the data sources to include in your vector: ### Select Objects Choose Objects whose data will be included in the vector. **Required**: No (but at least one data source is required) **Field**: Objects **How to select**: * Use the multi-select dropdown * Search for Objects by name * Select multiple Objects * Selected Objects' records will be embedded **Note**: Only non-transient Objects are included in embeddings. ### Select MFlows Choose workflows (MFlows) whose definitions will be included in the vector. **Required**: No **Field**: MFlows **How to select**: * Use the multi-select dropdown * Search for MFlows by name * Select multiple MFlows * Workflow definitions and configurations will be embedded ### Select MReports Choose reports (MReports) whose configurations will be included in the vector. **Required**: No **Field**: MReports **How to select**: * Use the multi-select dropdown * Search for MReports by name * Select multiple MReports * Report configurations and queries will be embedded ### Upload Files Upload files (documents, PDFs, etc.) to include in the vector. **Required**: No **Field**: Files **How to upload**: * Click the file upload area * Select files from your computer * Files are uploaded and processed * File content will be extracted and embedded **Supported Formats**: Documents, PDFs, and other text-based files ### Navigate to Next Step Click **"Next"** or **"Confirm"** to proceed to the Knowledge Graph step. ## Step 3: Knowledge Graph Build a knowledge graph defining relationships between data sources: ### Understanding Knowledge Graphs Knowledge graphs visualize relationships between data sources: * **Nodes**: Represent data sources (Objects, MFlows, MReports) * **Edges**: Represent relationships between data sources * **Visual Interface**: Drag-and-drop interface for building graphs * **Relationship Labels**: Custom labels describing relationships ### Building the Knowledge Graph #### Add Nodes 1. **Select Data Source**: Choose a data source from the sidebar (Objects, MFlows, MReports) 2. **Drag to Canvas**: Drag the data source onto the canvas 3. **Configure Node**: * **Select Columns**: For Object nodes, select specific columns to include * **Node Label**: Customize the node label * **Node Type**: Node type is automatically set based on data source #### Create Relationships 1. **Connect Nodes**: Click and drag from one node to another to create an edge 2. **Label Relationship**: Click on the edge to add/edit relationship label 3. **Relationship Types**: Define how data sources relate (e.g., "contains", "references", "belongs to") #### Configure Node Details For Object nodes: * **Select Columns**: Choose which columns from the Object to include in embeddings * **Column Selection**: Select specific fields that are relevant for search * **Metadata**: Column selections affect what data is embedded ### Knowledge Graph Best Practices * **Logical Relationships**: Create relationships that make logical sense * **Relevant Connections**: Connect related data sources * **Clear Labels**: Use clear, descriptive labels for relationships * **Column Selection**: Select relevant columns from Objects ### Create Vector Store After configuring the knowledge graph: 1. Review your configuration 2. Click **"Create"** or **"Save"** to create the vector store 3. The system will: * Create the vector store * Generate embeddings for selected data sources * Store embeddings in the vector database * Make the vector available for search and AI agent integration **Note**: Embedding generation may take time depending on the amount of data. ## Editing Vectors To edit an existing vector: 1. Navigate to the Vectors page 2. Find the vector in the list 3. Click the **"Edit"** icon next to the vector 4. The creation dialog opens with existing configuration 5. Navigate through steps to modify: * Basic information * Data sources * Knowledge graph 6. Click **"Save"** to apply changes **Note**: Changes to data sources may require regenerating embeddings. ## Searching Vectors To search a vector: 1. Navigate to the Vectors page 2. Find the vector in the list 3. Click the **"Search"** icon next to the vector 4. Enter your search query 5. View results showing: * **Similarity Score**: How similar the result is to your query * **Content**: The relevant content from data sources * **Source**: Which data source the result came from ## Best Practices ### Vector Naming * **Descriptive Names**: Use clear names that indicate the vector's purpose * **Consistent Naming**: Use consistent naming conventions * **Include Context**: Include context in names (e.g., "Customer Data Vector") ### Data Source Selection * **Relevant Data**: Select only relevant data sources * **Avoid Overload**: Don't include unnecessary data * **Quality over Quantity**: Focus on quality, relevant data ### Knowledge Graph Design * **Logical Structure**: Create logical relationships * **Clear Relationships**: Use clear relationship labels * **Column Selection**: Select relevant columns from Objects * **Avoid Complexity**: Keep knowledge graphs simple and understandable ### Embedding Model Selection * **Consistent Models**: Use the same model for a vector * **Appropriate Models**: Choose models appropriate for your data type * **Provider Selection**: Consider provider costs and capabilities ## Related Introduction * [Vectors Introduction](/mbrix/vectors) - Overview of vectors * [Objects Introduction](/mbrix/mobjects) - Understand Objects used as vector data sources * [Workflows Introduction](/mbrix/workflows) - Learn about workflows used as vector data sources * [Reports Introduction](/mbrix/reports) - Understand reports used as vector data sources --- # Vectors Introduction URL: /mbrix/vectors Learn about Vectors - vector stores for RAG (Retrieval-Augmented Generation) with AI agents *** title: Vectors Introduction description: Learn about Vectors - vector stores for RAG (Retrieval-Augmented Generation) with AI agents -------------------------------------------------------------------------------------------------------- # Vectors Vectors are vector stores used for RAG (Retrieval-Augmented Generation) with AI agents. They enable semantic search and similarity matching by storing embeddings of your data, allowing AI agents to retrieve relevant information based on meaning rather than exact keyword matches. ## What are Vectors? Vectors enable you to: * **Store Embeddings**: Convert data into vector embeddings using AI models * **Semantic Search**: Search data by meaning and context, not just keywords * **AI Agent Integration**: Provide context to AI agents for better responses * **Knowledge Graphs**: Define relationships between data sources * **Multi-Source Data**: Include data from Objects, MFlows, MReports, and Files ## Key Concepts ### Vector Stores Vector stores are databases optimized for storing and searching vector embeddings: * **Embeddings**: Numerical representations of data that capture semantic meaning * **Similarity Search**: Find similar data based on vector distance * **Efficient Retrieval**: Fast search across large amounts of data * **PostgreSQL pgvector**: Uses PostgreSQL with pgvector extension for storage ### Embedding Models Embedding models convert text/data into vector embeddings: * **Model Providers**: OpenAI, Ollama, VertexAI * **Model Selection**: Choose appropriate embedding model for your use case * **Model Configuration**: Configure model settings (temperature, topK, etc.) * **Consistent Embeddings**: Same model produces consistent embeddings ### Knowledge Graphs Knowledge graphs define relationships between data sources: * **Nodes**: Represent data sources (Objects, MFlows, MReports) * **Edges**: Represent relationships between data sources * **Visual Representation**: Graph view showing connections * **Relationship Labels**: Custom labels for relationships ### Data Sources Vectors can include data from multiple sources: * **Objects**: Object records and their data * **MFlows**: Workflow definitions and configurations * **MReports**: Report definitions and configurations * **Files**: Uploaded files (documents, PDFs, etc.) ## How Vectors Work ### Embedding Process Data is converted into embeddings: 1. **Data Selection**: Select data sources (Objects, MFlows, MReports, Files) 2. **Text Extraction**: Extract text content from selected sources 3. **Embedding Generation**: Use embedding model to generate vector embeddings 4. **Storage**: Store embeddings in vector store with metadata ### Vector Search When searching vectors: 1. **Query Embedding**: Convert search query into embedding using same model 2. **Similarity Calculation**: Calculate similarity between query and stored embeddings 3. **Top-K Results**: Retrieve top-K most similar results 4. **Context Retrieval**: Return relevant data for AI agent context ### AI Agent Integration Vectors are used with AI agents: * **Context Retrieval**: Agents retrieve relevant context from vectors * **RAG Pattern**: Retrieval-Augmented Generation for better responses * **Semantic Understanding**: Agents understand meaning, not just keywords * **Dynamic Context**: Context adapts to user queries ## Vector Features ### Multi-Source Data Include data from various sources: * **Objects**: Object records and schema * **MFlows**: Workflow definitions and logic * **MReports**: Report configurations and queries * **Files**: Document content and metadata ### Knowledge Graph Define relationships between data sources: * **Visual Graph**: Drag-and-drop interface for creating knowledge graphs * **Node Types**: Different node types for different data sources * **Relationship Mapping**: Define how data sources relate to each other * **Column Selection**: Select specific columns from Objects to include ### Embedding Configuration Configure embedding generation: * **Model Provider**: Choose provider (OpenAI, Ollama, VertexAI) * **Embedding Model**: Select specific embedding model * **Model Settings**: Configure temperature, topK, and other parameters * **Consistent Models**: Use same model for consistent embeddings ### Vector Search Search vectors for relevant information: * **Semantic Search**: Search by meaning and context * **Similarity Threshold**: Set minimum similarity threshold * **Top-K Results**: Configure number of results to return * **Filtered Search**: Filter results by metadata ## Using Vectors Vectors can be: * **Created**: Create new vector stores with data sources and knowledge graphs * **Edited**: Modify vector configurations, data sources, and knowledge graphs * **Searched**: Search vectors for relevant information * **Used with AI Agents**: Integrate vectors with AI agents for RAG * **Managed**: View, update, and delete vector stores ## Getting Started 1. **[Creating Vectors](/mbrix/vectors/creating-vectors)**: Learn how to create vector stores with data sources and knowledge graphs 2. **[Searching Vectors](/mbrix/vectors/searching-vectors)**: Learn how to search vectors for semantic similarity 3. **[Using Vectors with AI Agents](/mbrix/vectors/using-with-ai-agents)**: Understand how to configure vectors for AI agents 4. **Configure Data Sources**: Select Objects, MFlows, MReports, and Files 5. **Build Knowledge Graph**: Define relationships between data sources ## Related Introduction * [Objects Introduction](/mbrix/mobjects) - Understand Objects used as vector data sources * [Workflows Introduction](/mbrix/workflows) - Learn about workflows used as vector data sources * [Reports Introduction](/mbrix/reports) - Understand reports used as vector data sources --- # Searching Vectors URL: /mbrix/vectors/searching-vectors Learn how to search vectors for semantic similarity and retrieve relevant results *** title: Searching Vectors description: Learn how to search vectors for semantic similarity and retrieve relevant results ---------------------------------------------------------------------------------------------- # Searching Vectors Vector search enables you to find relevant information from your vector stores using semantic similarity. Unlike traditional keyword search, vector search understands meaning and context, making it ideal for finding related information even when exact keywords don't match. ## What is Vector Search? Vector search uses semantic similarity to find relevant information: * **Semantic Understanding**: Understands meaning and context, not just keywords * **Similarity Matching**: Finds similar content based on vector distance * **Relevance Scoring**: Returns results with similarity scores * **Filtered Results**: Filter results by data source (Objects, Files, Reports) ## How Vector Search Works ### Search Process 1. **Query Input**: Enter your search query as natural language 2. **Query Embedding**: Your query is converted to an embedding using the same model as the vector 3. **Similarity Calculation**: System calculates similarity between query embedding and stored embeddings 4. **Result Retrieval**: Returns top-K most similar results above the similarity threshold 5. **Result Display**: Shows results with content, similarity scores, and metadata ### Similarity Scoring Results are scored based on similarity: * **Score Range**: 0.0 to 1.0 (0% to 100%) * **Higher Scores**: Indicate more similar/relevant results * **Threshold Filtering**: Only results above the similarity threshold are returned * **Cosine Similarity**: Uses cosine distance to measure similarity ## Searching a Vector ### Access Vector Search To search a vector: 1. Navigate to the Vectors page 2. Find the vector in the list 3. Click the **"Search"** icon next to the vector 4. The vector search interface opens ### Configure Search Parameters Before searching, configure search parameters: #### Set Similarity Threshold Set the minimum similarity score for results. **Field**: Similarity Threshold **Range**: 0.0 to 1.0 **Default**: 0.3 (30%) **How to set**: * Use the slider to adjust threshold * Or enter a value directly in the input field * Lower threshold = more results (less strict) * Higher threshold = fewer results (more strict) **Recommendation**: Start with 0.3 and adjust based on result quality. #### Set Top K Set the maximum number of results to return. **Field**: Top K **Range**: 1 to 100 **Default**: 5 **How to set**: * Enter the number of results you want * Higher values return more results but may include less relevant ones * Lower values return fewer but more relevant results **Recommendation**: Start with 5-10 results and adjust based on needs. #### Filter by Data Sources (Optional) Filter results to specific data sources: **For Object Vectors**: * **Objects Filter**: Select specific Objects to search within * **How to select**: Use multi-select dropdown to choose Objects * **Use Case**: Search within specific Objects only **For File Vectors**: * **Files Filter**: Select specific files to search within * **How to select**: Use multi-select dropdown to choose files * **Use Case**: Search within specific documents only **For Report Vectors**: * **Reports Filter**: Select specific reports to search within * **How to select**: Use multi-select dropdown to choose reports * **Use Case**: Search within specific report configurations only **Note**: Filters are optional. If no filters are selected, all data sources in the vector are searched. ### Enter Search Query Enter your search query: **Field**: Search Query **How to enter**: * Type your query in natural language * Use descriptive phrases that capture what you're looking for * Examples: * "customer orders from last month" * "product pricing information" * "workflow for order processing" **Query Processing**: * Query is automatically debounced (waits 500ms after typing stops) * Query is converted to embedding using the vector's embedding model * Search executes automatically when query is ready ### Execute Search Click the **"Search"** button or press Enter to execute the search. **Search Execution**: * Query embedding is generated * Similarity search is performed * Results are filtered by threshold and top-K * Results are displayed in a table ## Understanding Search Results ### Result Table Search results are displayed in a table with three columns: #### Content Column Shows the actual content from the data source: * **Text Content**: The text that matched your query * **Scrollable**: Long content can be scrolled within the cell * **Source Context**: Content comes from the original data source #### Score Column Shows the similarity score: * **Percentage**: Displayed as percentage (0% to 100%) * **Higher = Better**: Higher scores indicate more relevant results * **Threshold**: Only results above threshold are shown #### Metadata Column Shows metadata about the result: * **Source Information**: Which data source the result came from * **Source ID**: ID of the source (Object ID, File ID, etc.) * **Additional Metadata**: Other relevant information * **JSON Format**: Metadata displayed as formatted JSON ### Result Information Above the results table: * **Result Count**: Number of results found * **Filtered Results**: Only results above similarity threshold are shown * **Sorted by Score**: Results sorted by similarity score (highest first) ## Search Best Practices ### Query Formulation * **Natural Language**: Use natural language queries, not keywords * **Descriptive**: Be descriptive about what you're looking for * **Context-Aware**: Include context in your query * **Examples**: * Good: "customer orders with status pending" * Less Effective: "orders pending" ### Similarity Threshold * **Start Low**: Start with lower threshold (0.3) to see more results * **Adjust Up**: Increase threshold if too many irrelevant results * **Adjust Down**: Decrease threshold if missing relevant results * **Domain-Specific**: Threshold may vary by domain and data type ### Top K Configuration * **Start Moderate**: Start with 5-10 results * **Increase if Needed**: Increase if you need more results * **Decrease for Precision**: Decrease for more focused results * **Consider Use Case**: Adjust based on your specific use case ### Filtering * **Use Filters**: Use data source filters to narrow search scope * **Specific Searches**: Filter to specific Objects/Files/Reports when needed * **Broad Searches**: Remove filters for broader searches * **Performance**: Filtering can improve search performance ## Use Cases ### Finding Related Data Search for data related to a specific topic: * **Example**: "customer contact information" * **Use Case**: Find all customer records and related data * **Result**: Returns relevant customer records with contact details ### Semantic Discovery Discover information using meaning: * **Example**: "order processing workflows" * **Use Case**: Find workflows related to order processing * **Result**: Returns workflows that handle orders, even if they don't contain exact keywords ### Context Retrieval for AI Retrieve context for AI agents: * **Example**: "product specifications" * **Use Case**: Provide context to AI agent about products * **Result**: Returns relevant product information for AI agent context ## Related Introduction * [Vectors Introduction](/mbrix/vectors) - Overview of vectors * [Creating Vectors](/mbrix/vectors/creating-vectors) - Learn how to create vectors * [Using Vectors with AI Agents](/mbrix/vectors/using-with-ai-agents) - Understand how vectors integrate with AI agents --- # Using Vectors with AI Agents URL: /mbrix/vectors/using-with-ai-agents Learn how to configure vectors for AI agents to enable RAG (Retrieval-Augmented Generation) *** title: Using Vectors with AI Agents description: Learn how to configure vectors for AI agents to enable RAG (Retrieval-Augmented Generation) -------------------------------------------------------------------------------------------------------- # Using Vectors with AI Agents Vectors are integrated with AI agents to enable RAG (Retrieval-Augmented Generation), allowing agents to retrieve relevant context from your data and provide more accurate, context-aware responses. ## What is RAG? RAG (Retrieval-Augmented Generation) combines: * **Retrieval**: Finding relevant information from vector stores * **Augmentation**: Adding retrieved context to AI agent prompts * **Generation**: AI agent generates responses using retrieved context This enables AI agents to: * **Access Your Data**: Use your actual data as context * **Provide Accurate Answers**: Answer questions based on your data * **Stay Up-to-Date**: Use current data, not just training data * **Domain-Specific**: Understand your specific domain and terminology ## How Vectors Work with AI Agents ### Vector Configuration When configuring an AI agent, you can associate vectors: 1. **Select Vector**: Choose a vector store to use with the agent 2. **Configure Parameters**: Set search parameters (top-K, similarity threshold) 3. **Filter Data Sources**: Optionally filter to specific Objects/Files/Reports 4. **Enable RAG**: Agent uses vector for context retrieval ### Context Retrieval Process When an AI agent receives a query: 1. **Query Analysis**: Agent analyzes the user's query 2. **Vector Search**: Agent searches the configured vector(s) for relevant context 3. **Context Retrieval**: Retrieves top-K most similar results above threshold 4. **Context Augmentation**: Adds retrieved context to the agent's prompt 5. **Response Generation**: Agent generates response using retrieved context ### Multiple Vectors Agents can be configured with multiple vectors: * **Multiple Context Sources**: Use different vectors for different types of context * **Combined Context**: Combine context from multiple vectors * **Specialized Vectors**: Use specialized vectors for specific domains ## Configuring Vectors for AI Agents ### Vector Selection Select which vector(s) to use with the agent: **Field**: Vector Configuration **How to configure**: 1. Navigate to AI Agent configuration 2. Find the Vector Configuration section 3. Select one or more vectors from the dropdown 4. Each vector can have its own configuration **Considerations**: * **Relevance**: Choose vectors relevant to the agent's purpose * **Data Coverage**: Ensure vectors contain data the agent needs * **Performance**: Consider performance impact of multiple vectors ### Search Parameters Configure search parameters for each vector: #### Top K Set the number of results to retrieve from the vector. **Field**: Top K **Range**: 1 to 100 **Default**: 3 **Recommendation**: * Start with 3-5 results * Increase if agent needs more context * Decrease if context is too verbose #### Similarity Threshold Set the minimum similarity score for retrieved results. **Field**: Similarity Threshold **Range**: 0.0 to 1.0 **Default**: 0.7 **Recommendation**: * Higher threshold (0.7-0.9) for precise, relevant context * Lower threshold (0.5-0.7) for broader context * Adjust based on agent response quality ### Data Source Filtering Filter vector search to specific data sources: #### Object Filtering For Object vectors, filter to specific Objects: **Field**: Objects Filter **How to configure**: * Select specific Objects from multi-select dropdown * Only those Objects will be searched * Useful when agent needs specific data subsets **Use Cases**: * Agent focused on specific business areas * Limiting context to relevant Objects * Improving search performance #### File Filtering For file vectors, filter to specific files: **Field**: Files Filter **How to configure**: * Select specific files from multi-select dropdown * Only those files will be searched * Useful for document-specific agents **Use Cases**: * Agent focused on specific documents * Limiting context to relevant files * Document-based knowledge agents #### Report Filtering For report vectors, filter to specific reports: **Field**: Reports Filter **How to configure**: * Select specific reports from multi-select dropdown * Only those reports will be searched * Useful for report-specific agents **Use Cases**: * Agent focused on specific report types * Limiting context to relevant reports * Report analysis agents ## Vector Configuration Best Practices ### Vector Selection * **Relevant Vectors**: Choose vectors that contain relevant data * **Quality over Quantity**: Fewer, high-quality vectors are better than many low-quality ones * **Domain Alignment**: Ensure vectors align with agent's domain * **Data Freshness**: Use vectors with up-to-date data ### Parameter Tuning * **Start Conservative**: Start with default parameters * **Test and Adjust**: Test agent responses and adjust parameters * **Balance Context**: Balance between too little and too much context * **Monitor Performance**: Monitor agent performance and adjust accordingly ### Filtering Strategy * **Use Filters When Needed**: Filter when agent needs specific data subsets * **Avoid Over-Filtering**: Don't filter too aggressively, may miss relevant context * **Test Without Filters**: Test agent without filters first, then add if needed * **Document Filters**: Document why filters are used ## Agent Response Quality ### Good Context Retrieval Signs of good context retrieval: * **Relevant Responses**: Agent provides relevant, accurate responses * **Uses Your Data**: Responses reference your actual data * **Context-Aware**: Agent understands context from your data * **Accurate Information**: Information is accurate and up-to-date ### Poor Context Retrieval Signs of poor context retrieval: * **Irrelevant Responses**: Agent provides irrelevant information * **Generic Responses**: Responses don't use your data * **Outdated Information**: Information is outdated or incorrect * **Missing Context**: Agent lacks necessary context ### Improving Context Retrieval To improve context retrieval: 1. **Adjust Similarity Threshold**: Lower threshold for more context, higher for more relevant 2. **Increase Top K**: Retrieve more results for broader context 3. **Improve Vector Data**: Ensure vectors contain relevant, high-quality data 4. **Use Filters**: Filter to relevant data sources 5. **Test Different Vectors**: Try different vectors or combinations ## Use Cases ### Customer Support Agent Configure agent with customer data vector: * **Vector**: Customer data vector with Objects (Customers, Orders, Products) * **Top K**: 5-10 results * **Threshold**: 0.7 * **Use Case**: Answer customer questions using actual customer data ### Document Q\&A Agent Configure agent with document vector: * **Vector**: Document vector with uploaded files * **Top K**: 3-5 results * **Threshold**: 0.8 * **Use Case**: Answer questions about documents ### Workflow Assistant Agent Configure agent with workflow vector: * **Vector**: Workflow vector with MFlows * **Top K**: 3-5 results * **Threshold**: 0.7 * **Use Case**: Help users understand and use workflows ## Related Introduction * [Vectors Introduction](/mbrix/vectors) - Overview of vectors * [Creating Vectors](/mbrix/vectors/creating-vectors) - Learn how to create vectors * [Searching Vectors](/mbrix/vectors/searching-vectors) - Understand how to search vectors --- # Workflow Introduction URL: /mbrix/workflows Complete documentation for Monetize360 workflow automation platform *** title: Workflow Introduction description: Complete documentation for Monetize360 workflow automation platform -------------------------------------------------------------------------------- # Welcome to Monetize360 Monetize360 is a powerful workflow automation platform that enables you to build complex business processes using visual workflows with simple, drag-and-drop functions. ## What is Monetize360? Monetize360 helps you automate business processes without writing code. Build workflows by connecting pre-built functions, manage your data with custom objects, and integrate with external systems - all through an intuitive visual interface. ## Function Categories Functions in Monetize360 are organized into simple, easy-to-understand categories: ### CRUD Operations Work with your data - create, read, update, and delete records in your Objects. Everything you need for basic data management. **Use when you need to**: Save customer information, fetch order details, update records, or delete old data. [Learn more about CRUD Operations →](/mbrix/workflows/functions/crud-operations/insert-mdata) ### User Interactions Connect with people through email notifications and user actions. Pause workflows to get human input or send updates to users. **Use when you need to**: Send confirmation emails, request approvals, notify users of important events, or collect user input. [Learn more about User Interactions →](/mbrix/workflows/functions/user-interactions/email-notification) ### System Functions Core workflow capabilities including loops, subflows, data transformations, and more. The building blocks for workflow logic. **Use when you need to**: Process arrays of data, call other workflows, write custom JavaScript, evaluate expressions, or generate PDFs. [Learn more about System Functions →](/mbrix/workflows/functions/system-functions/subflow) ### External API Connect Monetize360 with any external system using HTTP APIs. Integrate with payment gateways, CRMs, ERPs, and more. **Use when you need to**: Call REST APIs, integrate with third-party services, or connect to external databases. [Learn more about External API →](/mbrix/workflows/functions/external-api/call-external-api) ## Why Monetize360? ### Visual Workflow Builder Build complex workflows visually - no coding required. Drag and drop functions, connect them together, and watch your automation come to life. ### Powerful Function Library Access 38+ pre-built functions covering everything from data operations to AI agent integration. Each function is designed to handle common business scenarios. ### Flexible Data Models Create custom Objects to match your business data structure. Define fields, relationships, and validation rules that fit your needs. ### Enterprise-Ready Role-based security, audit trails, error handling, and monitoring built-in. ## Documentation Structure Our documentation is organized to help you find what you need: * **[Getting Started](/mbrix/workflows/getting-started)** - Fundamentals and first workflow * **[Functions](/mbrix/workflows/functions)** - Complete function reference * **[API Reference](/mbrix/workflows/api-reference)** - REST API documentation ## Quick Links ### By Task * [Creating records](/mbrix/workflows/functions/crud-operations/insert-mdata) - Create or Update Record * [Fetching data](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Get Single Record * [Sending emails](/mbrix/workflows/functions/user-interactions/email-notification) - Send Email * [Calling APIs](/mbrix/workflows/functions/external-api/call-external-api) - Call External API * [Processing arrays](/mbrix/workflows/functions/system-functions/foreach) - Loop Through Items * [User approvals](/mbrix/workflows/functions/user-interactions/user-action) - Assign Task ### By Role * **Developers**: Start with [System Functions](/mbrix/workflows/functions/system-functions/subflow) and [External API](/mbrix/workflows/functions/external-api/call-external-api) * **Business Users**: Focus on [CRUD Operations](/mbrix/workflows/functions/crud-operations/insert-mdata) and [User Interactions](/mbrix/workflows/functions/user-interactions/email-notification) * **Administrators**: Review [API Reference](/mbrix/workflows/api-reference) for integration options ## Getting Help * **Documentation**: You're in it! Use the search to find specific topics * **Examples**: Each function page includes real-world examples * **Community**: Join our community forum for questions and tips * **Support**: Contact support for technical assistance ## What's Next? 1. **[Read the Getting Started Guide](/mbrix/workflows/getting-started)** - Build your first workflow 2. **[Browse Functions](/mbrix/workflows/functions)** - See what's available 3. **[Explore the API](/mbrix/workflows/api-reference)** - Integrate programmatically Let's start automating! 🚀 --- # Activate access profile URL: /finops-api/access-profiles/activateAccessProfile *** title: Activate access profile full: true \_openapi: method: PUT route: /api/access-profiles/{id}/activate toc: \[] structuredData: headings: \[] contents: * content: Sets the profile active. Idempotent. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Sets the profile active. Idempotent. --- # Add an extra virtual key under a user's access profile URL: /finops-api/access-profiles/addUserAccessProfileVirtualKey *** title: Add an extra virtual key under a user's access profile full: true \_openapi: method: POST route: /api/users/{target_user_id}/access-profiles/{profile_id}/virtual-keys toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Attach roles to access profile URL: /finops-api/access-profiles/attachRolesToAccessProfile *** title: Attach roles to access profile full: true \_openapi: method: POST route: /api/access-profiles/{id}/roles toc: \[] structuredData: headings: \[] contents: * content: > Attaches one or more roles. Setting `is_default: true` makes the profile the role's default for new users. `apply_to_existing: true` provisions the profile to users already in the role. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Attaches one or more roles. Setting `is_default: true` makes the profile the role's default for new users. `apply_to_existing: true` provisions the profile to users already in the role. --- # Clone an access profile URL: /finops-api/access-profiles/cloneAccessProfile *** title: Clone an access profile full: true \_openapi: method: POST route: /api/access-profiles/{id}/clone toc: \[] structuredData: headings: \[] contents: * content: >- Creates a fresh copy of the profile under a new name. The clone has no role attachments or user copies. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a fresh copy of the profile under a new name. The clone has no role attachments or user copies. --- # Create access profile URL: /finops-api/access-profiles/createAccessProfile *** title: Create access profile full: true \_openapi: method: POST route: /api/access-profiles toc: \[] structuredData: headings: \[] contents: * content: > Creates a new access profile template. The profile is inactive until attached to a role. No size limits are enforced on create; the limits apply on update. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new access profile template. The profile is inactive until attached to a role. No size limits are enforced on create; the limits apply on update. --- # Deactivate access profile URL: /finops-api/access-profiles/deactivateAccessProfile *** title: Deactivate access profile full: true \_openapi: method: PUT route: /api/access-profiles/{id}/deactivate toc: \[] structuredData: headings: \[] contents: * content: >- Sets the profile inactive. Idempotent. User copies are preserved; the profile is hidden from selection menus. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Sets the profile inactive. Idempotent. User copies are preserved; the profile is hidden from selection menus. --- # Delete access profile URL: /finops-api/access-profiles/deleteAccessProfile *** title: Delete access profile full: true \_openapi: method: DELETE route: /api/access-profiles/{id} toc: \[] structuredData: headings: \[] contents: * content: >- Blocked with 409 if any users still hold copies. Detach role attachments or remove user assignments first. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Blocked with 409 if any users still hold copies. Detach role attachments or remove user assignments first. --- # Delete a virtual key from a user's access profile URL: /finops-api/access-profiles/deleteUserAccessProfileVirtualKey *** title: Delete a virtual key from a user's access profile full: true \_openapi: method: DELETE route: /api/users/{target_user_id}/access-profiles/virtual-keys/{vk_id} toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Detach role from access profile URL: /finops-api/access-profiles/detachRoleFromAccessProfile *** title: Detach role from access profile full: true \_openapi: method: DELETE route: /api/access-profiles/{id}/roles/{role_id} toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Detach a user's access profile URL: /finops-api/access-profiles/detachUserAccessProfile *** title: Detach a user's access profile full: true \_openapi: method: DELETE route: /api/users/{target_user_id}/access-profiles/{profile_id} toc: \[] structuredData: headings: \[] contents: * content: >- Removes the profile from the user and deletes every virtual key it produced. Fails closed if a virtual key cannot be deleted. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Removes the profile from the user and deletes every virtual key it produced. Fails closed if a virtual key cannot be deleted. --- # Get access profile by ID URL: /finops-api/access-profiles/getAccessProfile *** title: Get access profile by ID full: true \_openapi: method: GET route: /api/access-profiles/{id} toc: \[] structuredData: headings: \[] contents: * content: >- Returns the profile plus its role attachments and the count of users holding a copy. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the profile plus its role attachments and the count of users holding a copy. --- # Get a single version snapshot URL: /finops-api/access-profiles/getAccessProfileVersion *** title: Get a single version snapshot full: true \_openapi: method: GET route: /api/access-profiles/{id}/versions/{version} toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # List workspace-wide audit log entries URL: /finops-api/access-profiles/listAccessProfileAuditLogs *** title: List workspace-wide audit log entries full: true \_openapi: method: GET route: /api/access-profiles/audit-logs toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # List audit log entries for a single profile URL: /finops-api/access-profiles/listAccessProfileAuditLogsById *** title: List audit log entries for a single profile full: true \_openapi: method: GET route: /api/access-profiles/{id}/audit-logs toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # List version snapshots for an access profile URL: /finops-api/access-profiles/listAccessProfileVersions *** title: List version snapshots for an access profile full: true \_openapi: method: GET route: /api/access-profiles/{id}/versions toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # List access profiles URL: /finops-api/access-profiles/listAccessProfiles *** title: List access profiles full: true \_openapi: method: GET route: /api/access-profiles toc: \[] structuredData: headings: \[] contents: * content: Returns access profiles visible to the caller. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns access profiles visible to the caller. --- # List access profiles held by a user URL: /finops-api/access-profiles/listUserAccessProfiles *** title: List access profiles held by a user full: true \_openapi: method: GET route: /api/users/{target_user_id}/access-profiles toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Propagate template changes to user copies URL: /finops-api/access-profiles/propagateAccessProfile *** title: Propagate template changes to user copies full: true \_openapi: method: POST route: /api/access-profiles/{id}/propagate toc: \[] structuredData: headings: \[] contents: * content: > Pushes selected fields from the template to every user that holds a copy. Use `dry_run: true` to preview the impact. By default, accumulated usage is preserved. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Pushes selected fields from the template to every user that holds a copy. Use `dry_run: true` to preview the impact. By default, accumulated usage is preserved. --- # Update access profile URL: /finops-api/access-profiles/updateAccessProfile *** title: Update access profile full: true \_openapi: method: PUT route: /api/access-profiles/{id} toc: \[] structuredData: headings: \[] contents: * content: > Partial update. Omitted fields preserve the current value. `rate_limit: null` explicitly clears the existing rate limit. Size limits enforced: max 100 provider\_configs, max 100 budgets, max 50 tags. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Partial update. Omitted fields preserve the current value. `rate_limit: null` explicitly clears the existing rate limit. Size limits enforced: max 100 provider\_configs, max 100 budgets, max 50 tags. --- # Cancel batch job (Anthropic format) URL: /finops-api/anthropic-integration/anthropicCancelBatch *** title: Cancel batch job (Anthropic format) full: true \_openapi: method: POST route: /anthropic/v1/messages/batches/{batch_id}/cancel toc: \[] structuredData: headings: \[] contents: * content: | Cancels a batch processing job. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Cancels a batch processing job. --- # Count tokens (Anthropic format) URL: /finops-api/anthropic-integration/anthropicCountTokens *** title: Count tokens (Anthropic format) full: true \_openapi: method: POST route: /anthropic/v1/messages/count\_tokens toc: \[] structuredData: headings: \[] contents: * content: | Counts the number of tokens in a message request. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Counts the number of tokens in a message request. --- # Create batch job (Anthropic format) URL: /finops-api/anthropic-integration/anthropicCreateBatch *** title: Create batch job (Anthropic format) full: true \_openapi: method: POST route: /anthropic/v1/messages/batches toc: \[] structuredData: headings: \[] contents: * content: | Creates a batch processing job using Anthropic format. Use x-model-provider header to specify the provider. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a batch processing job using Anthropic format. Use x-model-provider header to specify the provider. --- # Create completion (Anthropic legacy format) URL: /finops-api/anthropic-integration/anthropicCreateComplete *** title: Create completion (Anthropic legacy format) full: true \_openapi: method: POST route: /anthropic/v1/complete toc: \[] structuredData: headings: \[] contents: * content: | Creates a text completion using Anthropic's legacy Complete API. Supports streaming via SSE. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a text completion using Anthropic's legacy Complete API. Supports streaming via SSE. --- # Create message (Anthropic format) URL: /finops-api/anthropic-integration/anthropicCreateMessage *** title: Create message (Anthropic format) full: true \_openapi: method: POST route: /anthropic/v1/messages toc: \[] structuredData: headings: \[] contents: * content: > Creates a message using Anthropic Messages API format. Supports streaming via SSE. **Async inference:** Send `x-bf-async: true` to submit the request as a background job and receive a job ID immediately. Poll with `x-bf-async-id: ` to retrieve the result. When the job is still processing, the response will have an empty `content` array. When completed, `content` will contain the full result. See [Async Inference](/features/async-inference) for details. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a message using Anthropic Messages API format. Supports streaming via SSE. **Async inference:** Send `x-bf-async: true` to submit the request as a background job and receive a job ID immediately. Poll with `x-bf-async-id: ` to retrieve the result. When the job is still processing, the response will have an empty `content` array. When completed, `content` will contain the full result. See [Async Inference](/features/async-inference) for details. --- # Create message (Anthropic format) - wildcard URL: /finops-api/anthropic-integration/anthropicCreateMessageWildcard *** title: Create message (Anthropic format) - wildcard full: true \_openapi: method: POST route: /anthropic/v1/messages/{path} toc: \[] structuredData: headings: \[] contents: * content: | Handles extended messages API paths. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Handles extended messages API paths. --- # Delete file (Anthropic format) URL: /finops-api/anthropic-integration/anthropicDeleteFile *** title: Delete file (Anthropic format) full: true \_openapi: method: DELETE route: /anthropic/v1/files/{file_id} toc: \[] structuredData: headings: \[] contents: * content: | Deletes an uploaded file. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes an uploaded file. --- # Get batch results (Anthropic format) URL: /finops-api/anthropic-integration/anthropicGetBatchResults *** title: Get batch results (Anthropic format) full: true \_openapi: method: GET route: /anthropic/v1/messages/batches/{batch_id}/results toc: \[] structuredData: headings: \[] contents: * content: | Retrieves results of a completed batch job. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves results of a completed batch job. --- # Get file content (Anthropic format) URL: /finops-api/anthropic-integration/anthropicGetFileContent *** title: Get file content (Anthropic format) full: true \_openapi: method: GET route: /anthropic/v1/files/{file_id}/content toc: \[] structuredData: headings: \[] contents: * content: > Retrieves file content. Returns raw binary file data when Accept header is set to application/octet-stream, or file metadata as JSON when Accept header is set to application/json. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves file content. Returns raw binary file data when Accept header is set to application/octet-stream, or file metadata as JSON when Accept header is set to application/json. --- # List batch jobs (Anthropic format) URL: /finops-api/anthropic-integration/anthropicListBatches *** title: List batch jobs (Anthropic format) full: true \_openapi: method: GET route: /anthropic/v1/messages/batches toc: \[] structuredData: headings: \[] contents: * content: | Lists batch processing jobs. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists batch processing jobs. --- # List files (Anthropic format) URL: /finops-api/anthropic-integration/anthropicListFiles *** title: List files (Anthropic format) full: true \_openapi: method: GET route: /anthropic/v1/files toc: \[] structuredData: headings: \[] contents: * content: | Lists uploaded files. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists uploaded files. --- # List models (Anthropic format) URL: /finops-api/anthropic-integration/anthropicListModels *** title: List models (Anthropic format) full: true \_openapi: method: GET route: /anthropic/v1/models toc: \[] structuredData: headings: \[] contents: * content: | Lists available models in Anthropic format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models in Anthropic format. --- # Retrieve batch job (Anthropic format) URL: /finops-api/anthropic-integration/anthropicRetrieveBatch *** title: Retrieve batch job (Anthropic format) full: true \_openapi: method: GET route: /anthropic/v1/messages/batches/{batch_id} toc: \[] structuredData: headings: \[] contents: * content: | Retrieves details of a batch processing job. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves details of a batch processing job. --- # Upload file (Anthropic format) URL: /finops-api/anthropic-integration/anthropicUploadFile *** title: Upload file (Anthropic format) full: true \_openapi: method: POST route: /anthropic/v1/files toc: \[] structuredData: headings: \[] contents: * content: | Uploads a file. Use x-model-provider header to specify the provider. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Uploads a file. Use x-model-provider header to specify the provider. --- # Create speech URL: /finops-api/audio/createSpeech *** title: Create speech full: true \_openapi: method: POST route: /v1/audio/speech toc: \[] structuredData: headings: \[] contents: * content: > Generates audio from the input text. Returns audio data or streams via SSE. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates audio from the input text. Returns audio data or streams via SSE. --- # Create transcription URL: /finops-api/audio/createTranscription *** title: Create transcription full: true \_openapi: method: POST route: /v1/audio/transcriptions toc: \[] structuredData: headings: \[] contents: * content: | Transcribes audio into text in the input language. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Transcribes audio into text in the input language. --- # Create chat completion (Azure OpenAI) URL: /finops-api/azure-integration/azureCreateChatCompletion *** title: Create chat completion (Azure OpenAI) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/chat/completions toc: \[] structuredData: headings: \[] contents: * content: | Creates a chat completion using Azure OpenAI deployment. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a chat completion using Azure OpenAI deployment. --- # Create embeddings (Azure OpenAI) URL: /finops-api/azure-integration/azureCreateEmbedding *** title: Create embeddings (Azure OpenAI) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/embeddings toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Create image (Azure OpenAI) URL: /finops-api/azure-integration/azureCreateImage *** title: Create image (Azure OpenAI) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/images/generations toc: \[] structuredData: headings: \[] contents: * content: | Generates images from text prompts using Azure OpenAI deployment. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates images from text prompts using Azure OpenAI deployment. --- # Create response (Azure OpenAI) URL: /finops-api/azure-integration/azureCreateResponse *** title: Create response (Azure OpenAI) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/responses toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Create speech (Azure OpenAI TTS) URL: /finops-api/azure-integration/azureCreateSpeech *** title: Create speech (Azure OpenAI TTS) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/audio/speech toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Create text completion (Azure OpenAI) URL: /finops-api/azure-integration/azureCreateTextCompletion *** title: Create text completion (Azure OpenAI) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/completions toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Create transcription (Azure OpenAI) URL: /finops-api/azure-integration/azureCreateTranscription *** title: Create transcription (Azure OpenAI) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/audio/transcriptions toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # List models (Azure OpenAI) URL: /finops-api/azure-integration/azureListModels *** title: List models (Azure OpenAI) full: true \_openapi: method: GET route: /openai/openai/deployments/{deployment-id}/models toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Cancel a batch job URL: /finops-api/batch/cancelBatch *** title: Cancel a batch job full: true \_openapi: method: POST route: /v1/batches/{batch_id}/cancel toc: \[] structuredData: headings: \[] contents: * content: | Cancels a batch job. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Cancels a batch job. --- # Create a batch job URL: /finops-api/batch/createBatch *** title: Create a batch job full: true \_openapi: method: POST route: /v1/batches toc: \[] structuredData: headings: \[] contents: * content: | Creates a batch job for asynchronous processing. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a batch job for asynchronous processing. --- # Get batch results URL: /finops-api/batch/getBatchResults *** title: Get batch results full: true \_openapi: method: GET route: /v1/batches/{batch_id}/results toc: \[] structuredData: headings: \[] contents: * content: | Retrieves results from a completed batch job. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves results from a completed batch job. --- # List batch jobs URL: /finops-api/batch/listBatches *** title: List batch jobs full: true \_openapi: method: GET route: /v1/batches toc: \[] structuredData: headings: \[] contents: * content: | Lists batch jobs for a provider. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists batch jobs for a provider. --- # Retrieve a batch job URL: /finops-api/batch/retrieveBatch *** title: Retrieve a batch job full: true \_openapi: method: GET route: /v1/batches/{batch_id} toc: \[] structuredData: headings: \[] contents: * content: | Retrieves a specific batch job by ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves a specific batch job by ID. --- # Create async chat completion URL: /finops-api/async-jobs/createAsyncChatCompletion *** title: Create async chat completion full: true \_openapi: method: POST route: /v1/async/chat/completions toc: \[] structuredData: headings: \[] contents: * content: > Submits a chat completion request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. Streaming is not supported for async requests. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Submits a chat completion request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. Streaming is not supported for async requests. --- # Create async embedding URL: /finops-api/async-jobs/createAsyncEmbedding *** title: Create async embedding full: true \_openapi: method: POST route: /v1/async/embeddings toc: \[] structuredData: headings: \[] contents: * content: > Submits an embedding request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Submits an embedding request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. --- # Create async image edit URL: /finops-api/async-jobs/createAsyncImageEdit *** title: Create async image edit full: true \_openapi: method: POST route: /v1/async/images/edits toc: \[] structuredData: headings: \[] contents: * content: > Submits an image edit request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. Streaming is not supported for async requests. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Submits an image edit request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. Streaming is not supported for async requests. --- # Create async image generation URL: /finops-api/async-jobs/createAsyncImageGeneration *** title: Create async image generation full: true \_openapi: method: POST route: /v1/async/images/generations toc: \[] structuredData: headings: \[] contents: * content: > Submits an image generation request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. Streaming is not supported for async requests. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Submits an image generation request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. Streaming is not supported for async requests. --- # Create async image variation URL: /finops-api/async-jobs/createAsyncImageVariation *** title: Create async image variation full: true \_openapi: method: POST route: /v1/async/images/variations toc: \[] structuredData: headings: \[] contents: * content: > Submits an image variation request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Submits an image variation request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. --- # Create async OCR job URL: /finops-api/async-jobs/createAsyncOCR *** title: Create async OCR job full: true \_openapi: method: POST route: /v1/async/ocr toc: \[] structuredData: headings: \[] contents: * content: > Submits an OCR request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Submits an OCR request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. --- # Create async rerank URL: /finops-api/async-jobs/createAsyncRerank *** title: Create async rerank full: true \_openapi: method: POST route: /v1/async/rerank toc: \[] structuredData: headings: \[] contents: * content: > Submits a rerank request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Submits a rerank request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. --- # Create async response URL: /finops-api/async-jobs/createAsyncResponse *** title: Create async response full: true \_openapi: method: POST route: /v1/async/responses toc: \[] structuredData: headings: \[] contents: * content: > Submits a response request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. Streaming is not supported for async requests. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Submits a response request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. Streaming is not supported for async requests. --- # Create async speech URL: /finops-api/async-jobs/createAsyncSpeech *** title: Create async speech full: true \_openapi: method: POST route: /v1/async/audio/speech toc: \[] structuredData: headings: \[] contents: * content: > Submits a speech synthesis request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. SSE streaming is not supported for async requests. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Submits a speech synthesis request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. SSE streaming is not supported for async requests. --- # Create async text completion URL: /finops-api/async-jobs/createAsyncTextCompletion *** title: Create async text completion full: true \_openapi: method: POST route: /v1/async/completions toc: \[] structuredData: headings: \[] contents: * content: > Submits a text completion request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. Streaming is not supported for async requests. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Submits a text completion request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. Streaming is not supported for async requests. --- # Create async transcription URL: /finops-api/async-jobs/createAsyncTranscription *** title: Create async transcription full: true \_openapi: method: POST route: /v1/async/audio/transcriptions toc: \[] structuredData: headings: \[] contents: * content: > Submits a transcription request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. Streaming is not supported for async requests. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Submits a transcription request for asynchronous execution. Returns a job ID immediately with HTTP 202. Poll the corresponding GET endpoint with the job ID to retrieve the result. Streaming is not supported for async requests. --- # Get async chat completion job URL: /finops-api/async-jobs/getAsyncChatCompletionJob *** title: Get async chat completion job full: true \_openapi: method: GET route: /v1/async/chat/completions/{job_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the status and result of an async chat completion job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the status and result of an async chat completion job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. --- # Get async embedding job URL: /finops-api/async-jobs/getAsyncEmbeddingJob *** title: Get async embedding job full: true \_openapi: method: GET route: /v1/async/embeddings/{job_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the status and result of an async embedding job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the status and result of an async embedding job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. --- # Get async image edit job URL: /finops-api/async-jobs/getAsyncImageEditJob *** title: Get async image edit job full: true \_openapi: method: GET route: /v1/async/images/edits/{job_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the status and result of an async image edit job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the status and result of an async image edit job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. --- # Get async image generation job URL: /finops-api/async-jobs/getAsyncImageGenerationJob *** title: Get async image generation job full: true \_openapi: method: GET route: /v1/async/images/generations/{job_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the status and result of an async image generation job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the status and result of an async image generation job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. --- # Get async image variation job URL: /finops-api/async-jobs/getAsyncImageVariationJob *** title: Get async image variation job full: true \_openapi: method: GET route: /v1/async/images/variations/{job_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the status and result of an async image variation job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the status and result of an async image variation job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. --- # Get async OCR job URL: /finops-api/async-jobs/getAsyncOCRJob *** title: Get async OCR job full: true \_openapi: method: GET route: /v1/async/ocr/{job_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the status and result of an async OCR job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the status and result of an async OCR job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. --- # Get async rerank job URL: /finops-api/async-jobs/getAsyncRerankJob *** title: Get async rerank job full: true \_openapi: method: GET route: /v1/async/rerank/{job_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the status and result of an async rerank job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the status and result of an async rerank job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. --- # Get async response job URL: /finops-api/async-jobs/getAsyncResponseJob *** title: Get async response job full: true \_openapi: method: GET route: /v1/async/responses/{job_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the status and result of an async response job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the status and result of an async response job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. --- # Get async speech job URL: /finops-api/async-jobs/getAsyncSpeechJob *** title: Get async speech job full: true \_openapi: method: GET route: /v1/async/audio/speech/{job_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the status and result of an async speech job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the status and result of an async speech job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. --- # Get async text completion job URL: /finops-api/async-jobs/getAsyncTextCompletionJob *** title: Get async text completion job full: true \_openapi: method: GET route: /v1/async/completions/{job_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the status and result of an async text completion job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the status and result of an async text completion job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. --- # Get async transcription job URL: /finops-api/async-jobs/getAsyncTranscriptionJob *** title: Get async transcription job full: true \_openapi: method: GET route: /v1/async/audio/transcriptions/{job_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the status and result of an async transcription job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the status and result of an async transcription job. Returns HTTP 202 if the job is still pending or processing, HTTP 200 if completed or failed. --- # Clear cache entry by cache ID URL: /finops-api/cache/clearCacheByCacheId *** title: Clear cache entry by cache ID full: true \_openapi: method: DELETE route: /api/cache/clear/{cacheId} toc: \[] structuredData: headings: \[] contents: * content: > Deletes a single cache entry by its storage ID. Read the cache ID from `extra_fields.cache_debug.cache_id` on a prior response — it is populated on both cache hits and cache misses. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a single cache entry by its storage ID. Read the cache ID from `extra_fields.cache_debug.cache_id` on a prior response — it is populated on both cache hits and cache misses. --- # Clear cache by cache key URL: /finops-api/cache/clearCacheByCacheKey *** title: Clear cache by cache key full: true \_openapi: method: DELETE route: /api/cache/clear-by-key/{cacheKey} toc: \[] structuredData: headings: \[] contents: * content: Clears a cache entry by its direct cache key. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Clears a cache entry by its direct cache key. --- # Cancel batch inference job (Bedrock format) URL: /finops-api/bedrock-integration/bedrockCancelBatchJob *** title: Cancel batch inference job (Bedrock format) full: true \_openapi: method: POST route: /bedrock/model-invocation-job/{job_arn}/stop toc: \[] structuredData: headings: \[] contents: * content: | Stops a batch inference job using AWS Bedrock format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Stops a batch inference job using AWS Bedrock format. --- # Converse with model (Bedrock format) URL: /finops-api/bedrock-integration/bedrockConverse *** title: Converse with model (Bedrock format) full: true \_openapi: method: POST route: /bedrock/model/{modelId}/converse toc: \[] structuredData: headings: \[] contents: * content: | Sends messages to a model using AWS Bedrock Converse API format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Sends messages to a model using AWS Bedrock Converse API format. --- # Stream converse with model (Bedrock format) URL: /finops-api/bedrock-integration/bedrockConverseStream *** title: Stream converse with model (Bedrock format) full: true \_openapi: method: POST route: /bedrock/model/{modelId}/converse-stream toc: \[] structuredData: headings: \[] contents: * content: | Streams messages from a model using AWS Bedrock Converse API format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Streams messages from a model using AWS Bedrock Converse API format. --- # Count tokens (Bedrock format) URL: /finops-api/bedrock-integration/bedrockCountTokens *** title: Count tokens (Bedrock format) full: true \_openapi: method: POST route: /bedrock/model/{modelId}/count-tokens toc: \[] structuredData: headings: \[] contents: * content: > Counts tokens for a Converse-style request using AWS Bedrock format. The request body must include `input.converse` with a complete Converse payload; only Converse-shaped input is supported. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Counts tokens for a Converse-style request using AWS Bedrock format. The request body must include `input.converse` with a complete Converse payload; only Converse-shaped input is supported. --- # Create batch inference job (Bedrock format) URL: /finops-api/bedrock-integration/bedrockCreateBatchJob *** title: Create batch inference job (Bedrock format) full: true \_openapi: method: POST route: /bedrock/model-invocation-job toc: \[] structuredData: headings: \[] contents: * content: > Creates a batch inference job using AWS Bedrock format. Routes to native Bedrock by default; set `x-model-provider` to route the job to another provider (`openai`, `gemini`, etc.). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a batch inference job using AWS Bedrock format. Routes to native Bedrock by default; set `x-model-provider` to route the job to another provider (`openai`, `gemini`, etc.). --- # Invoke model (Bedrock format) URL: /finops-api/bedrock-integration/bedrockInvokeModel *** title: Invoke model (Bedrock format) full: true \_openapi: method: POST route: /bedrock/model/{modelId}/invoke toc: \[] structuredData: headings: \[] contents: * content: | Invokes a model using AWS Bedrock InvokeModel API format. Accepts raw model-specific request body. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Invokes a model using AWS Bedrock InvokeModel API format. Accepts raw model-specific request body. --- # Invoke model with streaming (Bedrock format) URL: /finops-api/bedrock-integration/bedrockInvokeModelStream *** title: Invoke model with streaming (Bedrock format) full: true \_openapi: method: POST route: /bedrock/model/{modelId}/invoke-with-response-stream toc: \[] structuredData: headings: \[] contents: * content: > Invokes a model with streaming using AWS Bedrock InvokeModelWithResponseStream API format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Invokes a model with streaming using AWS Bedrock InvokeModelWithResponseStream API format. --- # List batch inference jobs (Bedrock format) URL: /finops-api/bedrock-integration/bedrockListBatchJobs *** title: List batch inference jobs (Bedrock format) full: true \_openapi: method: GET route: /bedrock/model-invocation-jobs toc: \[] structuredData: headings: \[] contents: * content: | Lists batch inference jobs using AWS Bedrock format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists batch inference jobs using AWS Bedrock format. --- # Retrieve batch inference job (Bedrock format) URL: /finops-api/bedrock-integration/bedrockRetrieveBatchJob *** title: Retrieve batch inference job (Bedrock format) full: true \_openapi: method: GET route: /bedrock/model-invocation-job/{job_arn} toc: \[] structuredData: headings: \[] contents: * content: | Retrieves a batch inference job using AWS Bedrock format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves a batch inference job using AWS Bedrock format. --- # S3-compatible DeleteObject URL: /finops-api/bedrock-integration/bedrockS3DeleteObject *** title: S3-compatible DeleteObject full: true \_openapi: method: DELETE route: /bedrock/files/{bucket}/{key} toc: \[] structuredData: headings: \[] contents: * content: Deletes an object from the Bifrost file store. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes an object from the Bifrost file store. --- # S3-compatible GetObject URL: /finops-api/bedrock-integration/bedrockS3GetObject *** title: S3-compatible GetObject full: true \_openapi: method: GET route: /bedrock/files/{bucket}/{key} toc: \[] structuredData: headings: \[] contents: * content: Retrieves raw object bytes from the Bifrost file store. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves raw object bytes from the Bifrost file store. --- # S3-compatible HeadObject URL: /finops-api/bedrock-integration/bedrockS3HeadObject *** title: S3-compatible HeadObject full: true \_openapi: method: HEAD route: /bedrock/files/{bucket}/{key} toc: \[] structuredData: headings: \[] contents: * content: > Returns S3 metadata headers (ETag, Content-Length, etc.) without a body. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns S3 metadata headers (ETag, Content-Length, etc.) without a body. --- # S3-compatible ListObjectsV2 URL: /finops-api/bedrock-integration/bedrockS3ListObjects *** title: S3-compatible ListObjectsV2 full: true \_openapi: method: GET route: /bedrock/files/{bucket} toc: \[] structuredData: headings: \[] contents: * content: | Lists objects in a bucket using S3 ListObjectsV2 semantics. Supports the `prefix` and `max-keys` query parameters used by boto3. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists objects in a bucket using S3 ListObjectsV2 semantics. Supports the `prefix` and `max-keys` query parameters used by boto3. --- # S3-compatible PutObject URL: /finops-api/bedrock-integration/bedrockS3PutObject *** title: S3-compatible PutObject full: true \_openapi: method: PUT route: /bedrock/files/{bucket}/{key} toc: \[] structuredData: headings: \[] contents: * content: > Uploads an object to the Bifrost file store using S3 PutObject semantics. The response is empty with an `ETag` header, mirroring native S3. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Uploads an object to the Bifrost file store using S3 PutObject semantics. The response is empty with an `ETag` header, mirroring native S3. --- # Create a chat completion URL: /finops-api/chat-completions/createChatCompletion *** title: Create a chat completion full: true \_openapi: method: POST route: /v1/chat/completions toc: \[] structuredData: headings: \[] contents: * content: > Creates a completion for the provided messages. Supports streaming via SSE. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a completion for the provided messages. Supports streaming via SSE. --- # Chat with model (Cohere v2 format) URL: /finops-api/cohere-integration/cohereChatV2 *** title: Chat with model (Cohere v2 format) full: true \_openapi: method: POST route: /cohere/v2/chat toc: \[] structuredData: headings: \[] contents: * content: | Sends a chat request using Cohere v2 API format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Sends a chat request using Cohere v2 API format. --- # Create embeddings (Cohere v2 format) URL: /finops-api/cohere-integration/cohereEmbedV2 *** title: Create embeddings (Cohere v2 format) full: true \_openapi: method: POST route: /cohere/v2/embed toc: \[] structuredData: headings: \[] contents: * content: | Creates embeddings using Cohere v2 API format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates embeddings using Cohere v2 API format. --- # Rerank documents (Cohere format) URL: /finops-api/cohere-integration/cohereRerank *** title: Rerank documents (Cohere format) full: true \_openapi: method: POST route: /cohere/v2/rerank toc: \[] structuredData: headings: \[] contents: * content: | Reranks a list of documents against a query using Cohere's v2 Rerank API. The request body matches Cohere's native format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Reranks a list of documents against a query using Cohere's v2 Rerank API. The request body matches Cohere's native format. --- # Tokenize text (Cohere format) URL: /finops-api/cohere-integration/cohereTokenize *** title: Tokenize text (Cohere format) full: true \_openapi: method: POST route: /cohere/v1/tokenize toc: \[] structuredData: headings: \[] contents: * content: | Tokenizes text using Cohere v1 API format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Tokenizes text using Cohere v1 API format. --- # Force pricing sync URL: /finops-api/configuration/forceSyncPricing *** title: Force pricing sync full: true \_openapi: method: POST route: /api/pricing/force-sync toc: \[] structuredData: headings: \[] contents: * content: Triggers an immediate pricing sync and resets the pricing sync timer. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Triggers an immediate pricing sync and resets the pricing sync timer. --- # Get configuration URL: /finops-api/configuration/getConfig *** title: Get configuration full: true \_openapi: method: GET route: /api/config toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the current Bifrost configuration including client config, framework config, auth config, and connection status for various stores. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the current Bifrost configuration including client config, framework config, auth config, and connection status for various stores. --- # Get proxy configuration URL: /finops-api/configuration/getProxyConfig *** title: Get proxy configuration full: true \_openapi: method: GET route: /api/proxy-config toc: \[] structuredData: headings: \[] contents: * content: Retrieves the current global proxy configuration. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the current global proxy configuration. --- # Get version URL: /finops-api/configuration/getVersion *** title: Get version full: true \_openapi: method: GET route: /api/version toc: \[] structuredData: headings: \[] contents: * content: Returns the current Bifrost version information. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the current Bifrost version information. --- # Update configuration URL: /finops-api/configuration/updateConfig *** title: Update configuration full: true \_openapi: method: PUT route: /api/config toc: \[] structuredData: headings: \[] contents: * content: > Updates the Bifrost configuration. Supports hot-reloading of certain settings like drop\_excess\_requests. Some settings may require a restart to take effect. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates the Bifrost configuration. Supports hot-reloading of certain settings like drop\_excess\_requests. Some settings may require a restart to take effect. --- # Update proxy configuration URL: /finops-api/configuration/updateProxyConfig *** title: Update proxy configuration full: true \_openapi: method: PUT route: /api/proxy-config toc: \[] structuredData: headings: \[] contents: * content: Updates the global proxy configuration. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates the global proxy configuration. --- # Create a container URL: /finops-api/containers/createContainer *** title: Create a container full: true \_openapi: method: POST route: /v1/containers toc: \[] structuredData: headings: \[] contents: * content: | Creates a new container for storing files and data. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new container for storing files and data. --- # Create a file in a container URL: /finops-api/containers/createContainerFile *** title: Create a file in a container full: true \_openapi: method: POST route: /v1/containers/{container_id}/files toc: \[] structuredData: headings: \[] contents: * content: > Creates a new file in a container. You can either upload file content directly via multipart/form-data or reference an existing file by its ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new file in a container. You can either upload file content directly via multipart/form-data or reference an existing file by its ID. --- # Delete a container URL: /finops-api/containers/deleteContainer *** title: Delete a container full: true \_openapi: method: DELETE route: /v1/containers/{container_id} toc: \[] structuredData: headings: \[] contents: * content: | Deletes a container. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a container. --- # Delete a file from a container URL: /finops-api/containers/deleteContainerFile *** title: Delete a file from a container full: true \_openapi: method: DELETE route: /v1/containers/{container_id}/files/{file_id} toc: \[] structuredData: headings: \[] contents: * content: | Deletes a file from a container. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a file from a container. --- # Download file content from a container URL: /finops-api/containers/getContainerFileContent *** title: Download file content from a container full: true \_openapi: method: GET route: /v1/containers/{container_id}/files/{file_id}/content toc: \[] structuredData: headings: \[] contents: * content: | Downloads the content of a file from a container. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Downloads the content of a file from a container. --- # List files in a container URL: /finops-api/containers/listContainerFiles *** title: List files in a container full: true \_openapi: method: GET route: /v1/containers/{container_id}/files toc: \[] structuredData: headings: \[] contents: * content: | Lists all files in a container. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists all files in a container. --- # List containers URL: /finops-api/containers/listContainers *** title: List containers full: true \_openapi: method: GET route: /v1/containers toc: \[] structuredData: headings: \[] contents: * content: | Lists containers for a provider. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists containers for a provider. --- # Retrieve a container URL: /finops-api/containers/retrieveContainer *** title: Retrieve a container full: true \_openapi: method: GET route: /v1/containers/{container_id} toc: \[] structuredData: headings: \[] contents: * content: | Retrieves a specific container by ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves a specific container by ID. --- # Retrieve a file from a container URL: /finops-api/containers/retrieveContainerFile *** title: Retrieve a file from a container full: true \_openapi: method: GET route: /v1/containers/{container_id}/files/{file_id} toc: \[] structuredData: headings: \[] contents: * content: | Retrieves metadata for a specific file in a container. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves metadata for a specific file in a container. --- # Consent identity selection page URL: /finops-api/consent-flow/getConsentIdentityPage *** title: Consent identity selection page full: true \_openapi: method: GET route: /oauth/consent toc: \[] structuredData: headings: \[] contents: * content: > Renders the identity selection screen where the user chooses how to identify themselves for the session: Virtual Key, User ID, or Skip (session-only auth). The `__bifrost_flow_secret` HttpOnly cookie set during `/api/oauth/per-user/authorize` must be present - it binds the consent flow to the initiating browser. The Skip option is only shown when `enforce_auth_on_inference` is `false` in config. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Renders the identity selection screen where the user chooses how to identify themselves for the session: Virtual Key, User ID, or Skip (session-only auth). The `__bifrost_flow_secret` HttpOnly cookie set during `/api/oauth/per-user/authorize` must be present - it binds the consent flow to the initiating browser. The Skip option is only shown when `enforce_auth_on_inference` is `false` in config. --- # Consent MCP services page URL: /finops-api/consent-flow/getConsentMCPsPage *** title: Consent MCP services page full: true \_openapi: method: GET route: /oauth/consent/mcps toc: \[] structuredData: headings: \[] contents: * content: > Renders the MCP services connection screen. Shows all per-user OAuth MCP servers available on the user's Virtual Key (or all servers if no VK was selected). Each service shows a "Connect" link or a "Connected ✓" badge. Requires the `__bifrost_flow_secret` browser-binding cookie. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Renders the MCP services connection screen. Shows all per-user OAuth MCP servers available on the user's Virtual Key (or all servers if no VK was selected). Each service shows a "Connect" link or a "Connected ✓" badge. Requires the `__bifrost_flow_secret` browser-binding cookie. --- # Skip identity selection URL: /finops-api/consent-flow/skipConsentIdentity *** title: Skip identity selection full: true \_openapi: method: POST route: /api/oauth/per-user/consent/skip toc: \[] structuredData: headings: \[] contents: * content: > Skips identity selection and proceeds directly to the MCPs page. Upstream service tokens will be stored against the session token only (not a persistent identity), so they will not carry over to other sessions or the LLM Gateway. Only available when `enforce_auth_on_inference` is `false` in config. Returns a redirect back to the identity page with an error if auth enforcement is enabled. Request body is `application/x-www-form-urlencoded` (browser form submission). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Skips identity selection and proceeds directly to the MCPs page. Upstream service tokens will be stored against the session token only (not a persistent identity), so they will not carry over to other sessions or the LLM Gateway. Only available when `enforce_auth_on_inference` is `false` in config. Returns a redirect back to the identity page with an error if auth enforcement is enabled. Request body is `application/x-www-form-urlencoded` (browser form submission). --- # Finalize consent flow URL: /finops-api/consent-flow/submitConsent *** title: Finalize consent flow full: true \_openapi: method: POST route: /api/oauth/per-user/consent/submit toc: \[] structuredData: headings: \[] contents: * content: > Finalizes the consent flow atomically: 1. Creates a `TablePerUserOAuthSession` (24h Bifrost session token) 2. Transfers upstream tokens from the flow proxy to the session 3. Issues a single-use `TablePerUserOAuthCode` (5-minute TTL, PKCE-bound) 4. Deletes the `PendingFlow` 5. Redirects to the MCP client's `redirect_uri` with `code` and `state` The MCP client then exchanges the code at `/api/oauth/per-user/token`. Request body is `application/x-www-form-urlencoded` (browser form submission). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Finalizes the consent flow atomically: 1. Creates a `TablePerUserOAuthSession` (24h Bifrost session token) 2. Transfers upstream tokens from the flow proxy to the session 3. Issues a single-use `TablePerUserOAuthCode` (5-minute TTL, PKCE-bound) 4. Deletes the `PendingFlow` 5. Redirects to the MCP client's `redirect_uri` with `code` and `state` The MCP client then exchanges the code at `/api/oauth/per-user/token`. Request body is `application/x-www-form-urlencoded` (browser form submission). --- # Submit User ID identity URL: /finops-api/consent-flow/submitConsentUserID *** title: Submit User ID identity full: true \_openapi: method: POST route: /api/oauth/per-user/consent/user-id toc: \[] structuredData: headings: \[] contents: * content: > Links a self-declared User ID to the pending flow as the user's identity. On success, redirects to the MCPs page. The User ID is self-declared with no server-side verification - it matches the trust model of the `X-Bf-User-Id` header in the LLM Gateway path. Request body is `application/x-www-form-urlencoded` (browser form submission). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Links a self-declared User ID to the pending flow as the user's identity. On success, redirects to the MCPs page. The User ID is self-declared with no server-side verification - it matches the trust model of the `X-Bf-User-Id` header in the LLM Gateway path. Request body is `application/x-www-form-urlencoded` (browser form submission). --- # Submit Virtual Key identity URL: /finops-api/consent-flow/submitConsentVirtualKey *** title: Submit Virtual Key identity full: true \_openapi: method: POST route: /api/oauth/per-user/consent/vk toc: \[] structuredData: headings: \[] contents: * content: > Validates the submitted Virtual Key and links it to the pending flow as the user's identity. On success, redirects to the MCPs page. On failure, redirects back to the identity page with an error message. Request body is `application/x-www-form-urlencoded` (browser form submission). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Validates the submitted Virtual Key and links it to the pending flow as the user's identity. On success, redirects to the MCPs page. On failure, redirects back to the identity page with an error message. Request body is `application/x-www-form-urlencoded` (browser form submission). --- # Count tokens URL: /finops-api/count-tokens/countTokens *** title: Count tokens full: true \_openapi: method: POST route: /v1/responses/input\_tokens toc: \[] structuredData: headings: \[] contents: * content: | Counts the number of tokens in the provided messages. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Counts the number of tokens in the provided messages. --- # Create embeddings URL: /finops-api/embeddings/createEmbedding *** title: Create embeddings full: true \_openapi: method: POST route: /v1/embeddings toc: \[] structuredData: headings: \[] contents: * content: | Creates an embedding vector representing the input text. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates an embedding vector representing the input text. --- # Delete a file URL: /finops-api/files/deleteFile *** title: Delete a file full: true \_openapi: method: DELETE route: /v1/files/{file_id} toc: \[] structuredData: headings: \[] contents: * content: | Deletes a file. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a file. --- # Download file content URL: /finops-api/files/getFileContent *** title: Download file content full: true \_openapi: method: GET route: /v1/files/{file_id}/content toc: \[] structuredData: headings: \[] contents: * content: | Downloads the content of a file. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Downloads the content of a file. --- # List files URL: /finops-api/files/listFiles *** title: List files full: true \_openapi: method: GET route: /v1/files toc: \[] structuredData: headings: \[] contents: * content: | Lists files for a provider. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists files for a provider. --- # Retrieve file metadata URL: /finops-api/files/retrieveFile *** title: Retrieve file metadata full: true \_openapi: method: GET route: /v1/files/{file_id} toc: \[] structuredData: headings: \[] contents: * content: | Retrieves metadata for a specific file. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves metadata for a specific file. --- # Upload a file URL: /finops-api/files/uploadFile *** title: Upload a file full: true \_openapi: method: POST route: /v1/files toc: \[] structuredData: headings: \[] contents: * content: | Uploads a file to be used with batch operations or other features. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Uploads a file to be used with batch operations or other features. --- # Anthropic complete (Cursor mount) URL: /finops-api/cursor-integration/cursorAnthropicComplete *** title: Anthropic complete (Cursor mount) full: true \_openapi: method: POST route: /cursor/v1/complete toc: \[] structuredData: headings: \[] contents: * content: Cursor mount of the legacy Anthropic `POST /v1/complete` endpoint. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Cursor mount of the legacy Anthropic `POST /v1/complete` endpoint. --- # Anthropic count tokens (Cursor mount) URL: /finops-api/cursor-integration/cursorAnthropicCountTokens *** title: Anthropic count tokens (Cursor mount) full: true \_openapi: method: POST route: /cursor/v1/messages/count\_tokens toc: \[] structuredData: headings: \[] contents: * content: Cursor mount of `POST /anthropic/v1/messages/count_tokens`. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Cursor mount of `POST /anthropic/v1/messages/count_tokens`. --- # Anthropic messages (Cursor mount) URL: /finops-api/cursor-integration/cursorAnthropicMessages *** title: Anthropic messages (Cursor mount) full: true \_openapi: method: POST route: /cursor/v1/messages toc: \[] structuredData: headings: \[] contents: * content: >- Cursor mount of `POST /anthropic/v1/messages`. Same request/response shape and streaming behaviour. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Cursor mount of `POST /anthropic/v1/messages`. Same request/response shape and streaming behaviour. --- # Anthropic messages — wildcard (Cursor mount) URL: /finops-api/cursor-integration/cursorAnthropicMessagesWildcard *** title: Anthropic messages — wildcard (Cursor mount) full: true \_openapi: method: POST route: /cursor/v1/messages/{path} toc: \[] structuredData: headings: \[] contents: * content: > Cursor mount of the Anthropic messages wildcard (`POST /anthropic/v1/messages/{path}`). Routes extended Anthropic messages endpoints (e.g. batches, count tokens) through Cursor. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Cursor mount of the Anthropic messages wildcard (`POST /anthropic/v1/messages/{path}`). Routes extended Anthropic messages endpoints (e.g. batches, count tokens) through Cursor. --- # Bedrock converse (Cursor mount) URL: /finops-api/cursor-integration/cursorBedrockConverse *** title: Bedrock converse (Cursor mount) full: true \_openapi: method: POST route: /cursor/model/{modelId}/converse toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Bedrock converse stream (Cursor mount) URL: /finops-api/cursor-integration/cursorBedrockConverseStream *** title: Bedrock converse stream (Cursor mount) full: true \_openapi: method: POST route: /cursor/model/{modelId}/converse-stream toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Bedrock count tokens (Cursor mount) URL: /finops-api/cursor-integration/cursorBedrockCountTokens *** title: Bedrock count tokens (Cursor mount) full: true \_openapi: method: POST route: /cursor/model/{modelId}/count-tokens toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Bedrock invoke (Cursor mount) URL: /finops-api/cursor-integration/cursorBedrockInvoke *** title: Bedrock invoke (Cursor mount) full: true \_openapi: method: POST route: /cursor/model/{modelId}/invoke toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Bedrock invoke-with-response-stream (Cursor mount) URL: /finops-api/cursor-integration/cursorBedrockInvokeStream *** title: Bedrock invoke-with-response-stream (Cursor mount) full: true \_openapi: method: POST route: /cursor/model/{modelId}/invoke-with-response-stream toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Bedrock rerank (Cursor mount) URL: /finops-api/cursor-integration/cursorBedrockRerank *** title: Bedrock rerank (Cursor mount) full: true \_openapi: method: POST route: /cursor/rerank toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Cursor hybrid chat completions URL: /finops-api/cursor-integration/cursorChatCompletions *** title: Cursor hybrid chat completions full: true \_openapi: method: POST route: /cursor/v1/chat/completions toc: \[] structuredData: headings: \[] contents: * content: > Accepts Cursor's hybrid chat-completions payload (which is structurally a Responses API request with `input` blocks) and returns a chat- completions-shaped response (`choices` + `delta` chunks for streams). Routes the request through the Responses pipeline internally. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Accepts Cursor's hybrid chat-completions payload (which is structurally a Responses API request with `input` blocks) and returns a chat- completions-shaped response (`choices` + `delta` chunks for streams). Routes the request through the Responses pipeline internally. --- # Cohere chat (Cursor mount) URL: /finops-api/cursor-integration/cursorCohereChat *** title: Cohere chat (Cursor mount) full: true \_openapi: method: POST route: /cursor/v2/chat toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Cohere embed (Cursor mount) URL: /finops-api/cursor-integration/cursorCohereEmbed *** title: Cohere embed (Cursor mount) full: true \_openapi: method: POST route: /cursor/v2/embed toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Cohere rerank (Cursor mount) URL: /finops-api/cursor-integration/cursorCohereRerank *** title: Cohere rerank (Cursor mount) full: true \_openapi: method: POST route: /cursor/v2/rerank toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Cohere tokenize (Cursor mount) URL: /finops-api/cursor-integration/cursorCohereTokenize *** title: Cohere tokenize (Cursor mount) full: true \_openapi: method: POST route: /cursor/v1/tokenize toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Gemini list models (Cursor mount) URL: /finops-api/cursor-integration/cursorGeminiListModels *** title: Gemini list models (Cursor mount) full: true \_openapi: method: GET route: /cursor/v1beta/models toc: \[] structuredData: headings: \[] contents: * content: Cursor mount of `GET /genai/v1beta/models`. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Cursor mount of `GET /genai/v1beta/models`. --- # Gemini model action (Cursor mount) URL: /finops-api/cursor-integration/cursorGeminiModelAction *** title: Gemini model action (Cursor mount) full: true \_openapi: method: POST route: /cursor/v1beta/models/{model} toc: \[] structuredData: headings: \[] contents: * content: | Cursor mount of Gemini's wildcard generate-content/embed/count-tokens/ predict endpoints. The `model` path parameter includes the action suffix (e.g. `gemini-pro:generateContent`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Cursor mount of Gemini's wildcard generate-content/embed/count-tokens/ predict endpoints. The `model` path parameter includes the action suffix (e.g. `gemini-pro:generateContent`). --- # Gemini video operation polling (Cursor mount) URL: /finops-api/cursor-integration/cursorGeminiRetrieveVideoOperation *** title: Gemini video operation polling (Cursor mount) full: true \_openapi: method: GET route: /cursor/v1beta/models/{model}/operations/{operation_id} toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # List models (Cursor) URL: /finops-api/cursor-integration/cursorListModels *** title: List models (Cursor) full: true \_openapi: method: GET route: /cursor/v1/models toc: \[] structuredData: headings: \[] contents: * content: Lists available models, returning the OpenAI `/v1/models` shape. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models, returning the OpenAI `/v1/models` shape. --- # Vertex rank (Cursor mount) URL: /finops-api/cursor-integration/cursorVertexRank *** title: Vertex rank (Cursor mount) full: true \_openapi: method: POST route: /cursor/v1/rank toc: \[] structuredData: headings: \[] contents: * content: Cursor mount of `POST /genai/v1/rank` — Vertex AI ranking. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Cursor mount of `POST /genai/v1/rank` — Vertex AI ranking. --- # Health check URL: /finops-api/health/getHealth *** title: Health check full: true \_openapi: method: GET route: /health toc: \[] structuredData: headings: \[] contents: * content: > Returns the health status of the Bifrost server. Checks connectivity to config store, log store, and vector store if configured. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the health status of the Bifrost server. Checks connectivity to config store, log store, and vector store if configured. --- # Edit an image URL: /finops-api/images/imageEdit *** title: Edit an image full: true \_openapi: method: POST route: /v1/images/edits toc: \[] structuredData: headings: \[] contents: * content: > Edits an image using a text prompt and optional mask. Request must be sent as multipart/form-data with at least `model`, `prompt` (unless `type` is `background_removal`), and `image` (or `image[]`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Edits an image using a text prompt and optional mask. Request must be sent as multipart/form-data with at least `model`, `prompt` (unless `type` is `background_removal`), and `image` (or `image[]`). --- # Generate an image URL: /finops-api/images/imageGeneration *** title: Generate an image full: true \_openapi: method: POST route: /v1/images/generations toc: \[] structuredData: headings: \[] contents: * content: | Generates images from text prompts using the specified model. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates images from text prompts using the specified model. --- # Create Variation URL: /finops-api/images/imageVariation *** title: Create Variation full: true \_openapi: method: POST route: /v1/images/variations toc: \[] structuredData: headings: \[] contents: * content: > Creates variations of an image. Request must be sent as multipart/form-data with `model` and `image` (or `image[]`). Does not support streaming. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates variations of an image. Request must be sent as multipart/form-data with `model` and `image` (or `image[]`). Does not support streaming. --- # Cancel a batch job (Gemini format) URL: /finops-api/genai-integration/geminiCancelBatch *** title: Cancel a batch job (Gemini format) full: true \_openapi: method: POST route: /genai/v1beta/batches/{batch_id} toc: \[] structuredData: headings: \[] contents: * content: | Cancels a batch job. Gemini conventionally sends the request as `/v1beta/batches/{batch_id}:cancel`; the router matches the `:cancel` suffix into the `batch_id` path parameter. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Cancels a batch job. Gemini conventionally sends the request as `/v1beta/batches/{batch_id}:cancel`; the router matches the `:cancel` suffix into the `batch_id` path parameter. --- # Count tokens (Gemini format) URL: /finops-api/genai-integration/geminiCountTokens *** title: Count tokens (Gemini format) full: true \_openapi: method: POST route: /genai/v1beta/models/{model}:countTokens toc: \[] structuredData: headings: \[] contents: * content: | Counts tokens using Google Gemini API format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Counts tokens using Google Gemini API format. --- # Create cached content (Gemini format) URL: /finops-api/genai-integration/geminiCreateCachedContent *** title: Create cached content (Gemini format) full: true \_openapi: method: POST route: /genai/v1beta/cachedContents toc: \[] structuredData: headings: \[] contents: * content: | Creates a cached content entry that can be re-used across subsequent generate-content calls to reduce repeated prefix tokens. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a cached content entry that can be re-used across subsequent generate-content calls to reduce repeated prefix tokens. --- # Delete a batch job (Gemini format) URL: /finops-api/genai-integration/geminiDeleteBatch *** title: Delete a batch job (Gemini format) full: true \_openapi: method: DELETE route: /genai/v1beta/batches/{batch_id} toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Delete cached content (Gemini format) URL: /finops-api/genai-integration/geminiDeleteCachedContent *** title: Delete cached content (Gemini format) full: true \_openapi: method: DELETE route: /genai/v1beta/cachedContents/{cached_id} toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Delete file (Gemini format) URL: /finops-api/genai-integration/geminiDeleteFile *** title: Delete file (Gemini format) full: true \_openapi: method: DELETE route: /genai/v1beta/files/{file_id} toc: \[] structuredData: headings: \[] contents: * content: | Deletes a file in Google Gemini API format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a file in Google Gemini API format. --- # Embed content (Gemini format) URL: /finops-api/genai-integration/geminiEmbedContent *** title: Embed content (Gemini format) full: true \_openapi: method: POST route: /genai/v1beta/models/{model}:embedContent toc: \[] structuredData: headings: \[] contents: * content: | Creates embeddings using Google Gemini API format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates embeddings using Google Gemini API format. --- # Generate content (Gemini format) URL: /finops-api/genai-integration/geminiGenerateContent *** title: Generate content (Gemini format) full: true \_openapi: method: POST route: /genai/v1beta/models/{model}:generateContent toc: \[] structuredData: headings: \[] contents: * content: | Generates content using Google Gemini API format. The model is specified in the URL path. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates content using Google Gemini API format. The model is specified in the URL path. --- # Generate image (Gemini format) URL: /finops-api/genai-integration/geminiGenerateImage *** title: Generate image (Gemini format) full: true \_openapi: method: POST route: /genai/v1beta/models/{model}:predict toc: \[] structuredData: headings: \[] contents: * content: > For Imagen models, use the `:predict` suffix (e.g., `imagen-3.0-generate-001:predict`). For Gemini models, use `:generateContent` with `generationConfig.responseModalities: ["IMAGE"]` in the request body. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} For Imagen models, use the `:predict` suffix (e.g., `imagen-3.0-generate-001:predict`). For Gemini models, use `:generateContent` with `generationConfig.responseModalities: ["IMAGE"]` in the request body. --- # List batch jobs (Gemini format) URL: /finops-api/genai-integration/geminiListBatches *** title: List batch jobs (Gemini format) full: true \_openapi: method: GET route: /genai/v1beta/batches toc: \[] structuredData: headings: \[] contents: * content: >- Lists batch jobs in Gemini format. Supports `pageSize` / `pageToken` pagination. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists batch jobs in Gemini format. Supports `pageSize` / `pageToken` pagination. --- # List cached content entries (Gemini format) URL: /finops-api/genai-integration/geminiListCachedContents *** title: List cached content entries (Gemini format) full: true \_openapi: method: GET route: /genai/v1beta/cachedContents toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # List files (Gemini format) URL: /finops-api/genai-integration/geminiListFiles *** title: List files (Gemini format) full: true \_openapi: method: GET route: /genai/v1beta/files toc: \[] structuredData: headings: \[] contents: * content: | Lists uploaded files in Google Gemini API format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists uploaded files in Google Gemini API format. --- # List models (Gemini format) URL: /finops-api/genai-integration/geminiListModels *** title: List models (Gemini format) full: true \_openapi: method: GET route: /genai/v1beta/models toc: \[] structuredData: headings: \[] contents: * content: | Lists available models in Google Gemini API format. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models in Google Gemini API format. --- # Retrieve a batch job (Gemini format) URL: /finops-api/genai-integration/geminiRetrieveBatch *** title: Retrieve a batch job (Gemini format) full: true \_openapi: method: GET route: /genai/v1beta/batches/{batch_id} toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Retrieve cached content (Gemini format) URL: /finops-api/genai-integration/geminiRetrieveCachedContent *** title: Retrieve cached content (Gemini format) full: true \_openapi: method: GET route: /genai/v1beta/cachedContents/{cached_id} toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Retrieve file (Gemini format) URL: /finops-api/genai-integration/geminiRetrieveFile *** title: Retrieve file (Gemini format) full: true \_openapi: method: GET route: /genai/v1beta/files/{file_id} toc: \[] structuredData: headings: \[] contents: * content: | Retrieves file metadata in Google Gemini API format. Note: This endpoint returns file metadata only. Direct file content download is not supported by Gemini Files API. Use the file.uri field from the response to access the file content. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves file metadata in Google Gemini API format. Note: This endpoint returns file metadata only. Direct file content download is not supported by Gemini Files API. Use the file.uri field from the response to access the file content. --- # Retrieve video generation operation (Gemini format) URL: /finops-api/genai-integration/geminiRetrieveVideoOperation *** title: Retrieve video generation operation (Gemini format) full: true \_openapi: method: GET route: /genai/v1beta/models/{model}/operations/{operation_id} toc: \[] structuredData: headings: \[] contents: * content: | Polls the status of a long-running video generation operation produced by `models/{model}:generateVideos`. The Gemini SDK appends the operation name as a wildcard path segment. If the operation name contains `/`, it must be percent-encoded in the request path (for example, `%2F`) to remain conformant with OpenAPI 3.x path-parameter semantics. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Polls the status of a long-running video generation operation produced by `models/{model}:generateVideos`. The Gemini SDK appends the operation name as a wildcard path segment. If the operation name contains `/`, it must be percent-encoded in the request path (for example, `%2F`) to remain conformant with OpenAPI 3.x path-parameter semantics. --- # Stream generate content (Gemini format) URL: /finops-api/genai-integration/geminiStreamGenerateContent *** title: Stream generate content (Gemini format) full: true \_openapi: method: POST route: /genai/v1beta/models/{model}:streamGenerateContent toc: \[] structuredData: headings: \[] contents: * content: | Streams content generation using Google Gemini API format. The model is specified in the URL path. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Streams content generation using Google Gemini API format. The model is specified in the URL path. --- # Update cached content (Gemini format) URL: /finops-api/genai-integration/geminiUpdateCachedContent *** title: Update cached content (Gemini format) full: true \_openapi: method: PATCH route: /genai/v1beta/cachedContents/{cached_id} toc: \[] structuredData: headings: \[] contents: * content: | Updates the TTL or expiration time of a cached content entry. Only `ttl` or `expireTime` may be modified. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates the TTL or expiration time of a cached content entry. Only `ttl` or `expireTime` may be modified. --- # Upload file (Gemini format) URL: /finops-api/genai-integration/geminiUploadFile *** title: Upload file (Gemini format) full: true \_openapi: method: POST route: /genai/upload/v1beta/files toc: \[] structuredData: headings: \[] contents: * content: > Uploads a file using Google Gemini API format. This is a multipart upload with two parts: * "metadata": JSON object containing file metadata * "file": Binary file content Note: Direct file content download is not supported by Gemini Files API. Use the file.uri field from the response to access uploaded files. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Uploads a file using Google Gemini API format. This is a multipart upload with two parts: * "metadata": JSON object containing file metadata * "file": Binary file content Note: Direct file content download is not supported by Gemini Files API. Use the file.uri field from the response to access uploaded files. --- # Rerank documents (Vertex Rank) URL: /finops-api/genai-integration/vertexRank *** title: Rerank documents (Vertex Rank) full: true \_openapi: method: POST route: /genai/v1/rank toc: \[] structuredData: headings: \[] contents: * content: | Reranks records using Google Vertex AI's Ranking API. The request body follows the Vertex `rankRecords` schema. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Reranks records using Google Vertex AI's Ranking API. The request body follows the Vertex `rankRecords` schema. --- # Create customer URL: /finops-api/governance/createCustomer *** title: Create customer full: true \_openapi: method: POST route: /api/governance/customers toc: \[] structuredData: headings: \[] contents: * content: Creates a new customer. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new customer. --- # Create model config URL: /finops-api/governance/createModelConfig *** title: Create model config full: true \_openapi: method: POST route: /api/governance/model-configs toc: \[] structuredData: headings: \[] contents: * content: Creates a new model configuration with budget and rate limit settings. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new model configuration with budget and rate limit settings. --- # Create pricing override URL: /finops-api/governance/createPricingOverride *** title: Create pricing override full: true \_openapi: method: POST route: /api/governance/pricing-overrides toc: \[] structuredData: headings: \[] contents: * content: >- Creates a new pricing override. The most specific matching scope always wins during cost resolution. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new pricing override. The most specific matching scope always wins during cost resolution. --- # Create routing rule URL: /finops-api/governance/createRoutingRule *** title: Create routing rule full: true \_openapi: method: POST route: /api/governance/routing-rules toc: \[] structuredData: headings: \[] contents: * content: >- Creates a new CEL-based routing rule for intelligent request routing. Provider and model can be left empty to use the incoming request values. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new CEL-based routing rule for intelligent request routing. Provider and model can be left empty to use the incoming request values. --- # Create team URL: /finops-api/governance/createTeam *** title: Create team full: true \_openapi: method: POST route: /api/governance/teams toc: \[] structuredData: headings: \[] contents: * content: Creates a new team. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new team. --- # Create virtual key URL: /finops-api/governance/createVirtualKey *** title: Create virtual key full: true \_openapi: method: POST route: /api/governance/virtual-keys toc: \[] structuredData: headings: \[] contents: * content: Creates a new virtual key with the specified configuration. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new virtual key with the specified configuration. --- # Delete customer URL: /finops-api/governance/deleteCustomer *** title: Delete customer full: true \_openapi: method: DELETE route: /api/governance/customers/{customer_id} toc: \[] structuredData: headings: \[] contents: * content: Deletes a customer. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a customer. --- # Delete model config URL: /finops-api/governance/deleteModelConfig *** title: Delete model config full: true \_openapi: method: DELETE route: /api/governance/model-configs/{mc_id} toc: \[] structuredData: headings: \[] contents: * content: Deletes a model configuration. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a model configuration. --- # Delete pricing override URL: /finops-api/governance/deletePricingOverride *** title: Delete pricing override full: true \_openapi: method: DELETE route: /api/governance/pricing-overrides/{id} toc: \[] structuredData: headings: \[] contents: * content: Deletes a pricing override by ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a pricing override by ID. --- # Delete provider governance URL: /finops-api/governance/deleteProviderGovernance *** title: Delete provider governance full: true \_openapi: method: DELETE route: /api/governance/providers/{provider_name} toc: \[] structuredData: headings: \[] contents: * content: >- Removes governance settings (budget and rate limits) for a specific provider. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Removes governance settings (budget and rate limits) for a specific provider. --- # Delete routing rule URL: /finops-api/governance/deleteRoutingRule *** title: Delete routing rule full: true \_openapi: method: DELETE route: /api/governance/routing-rules/{rule_id} toc: \[] structuredData: headings: \[] contents: * content: Deletes a routing rule. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a routing rule. --- # Delete team URL: /finops-api/governance/deleteTeam *** title: Delete team full: true \_openapi: method: DELETE route: /api/governance/teams/{team_id} toc: \[] structuredData: headings: \[] contents: * content: Deletes a team. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a team. --- # Delete virtual key URL: /finops-api/governance/deleteVirtualKey *** title: Delete virtual key full: true \_openapi: method: DELETE route: /api/governance/virtual-keys/{vk_id} toc: \[] structuredData: headings: \[] contents: * content: Deletes a virtual key. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a virtual key. --- # Get customer URL: /finops-api/governance/getCustomer *** title: Get customer full: true \_openapi: method: GET route: /api/governance/customers/{customer_id} toc: \[] structuredData: headings: \[] contents: * content: Returns a specific customer by ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a specific customer by ID. --- # Get model config URL: /finops-api/governance/getModelConfig *** title: Get model config full: true \_openapi: method: GET route: /api/governance/model-configs/{mc_id} toc: \[] structuredData: headings: \[] contents: * content: Returns a specific model configuration by ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a specific model configuration by ID. --- # Get routing rule URL: /finops-api/governance/getRoutingRule *** title: Get routing rule full: true \_openapi: method: GET route: /api/governance/routing-rules/{rule_id} toc: \[] structuredData: headings: \[] contents: * content: Returns a specific routing rule by ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a specific routing rule by ID. --- # Get team URL: /finops-api/governance/getTeam *** title: Get team full: true \_openapi: method: GET route: /api/governance/teams/{team_id} toc: \[] structuredData: headings: \[] contents: * content: Returns a specific team by ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a specific team by ID. --- # Get virtual key URL: /finops-api/governance/getVirtualKey *** title: Get virtual key full: true \_openapi: method: GET route: /api/governance/virtual-keys/{vk_id} toc: \[] structuredData: headings: \[] contents: * content: Returns a specific virtual key by ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a specific virtual key by ID. --- # Get virtual key quota URL: /finops-api/governance/getVirtualKeyQuota *** title: Get virtual key quota full: true \_openapi: method: GET route: /api/governance/virtual-keys/quota toc: \[] structuredData: headings: \[] contents: * content: > Returns the overall budget and rate limit quota for the authenticated virtual key, as well as per-provider budgets and rate limits. This is a self-service endpoint - no admin authentication required. The virtual key value itself (provided via header) is the credential. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the overall budget and rate limit quota for the authenticated virtual key, as well as per-provider budgets and rate limits. This is a self-service endpoint - no admin authentication required. The virtual key value itself (provided via header) is the credential. --- # List budgets URL: /finops-api/governance/listBudgets *** title: List budgets full: true \_openapi: method: GET route: /api/governance/budgets toc: \[] structuredData: headings: \[] contents: * content: >- Returns a list of all budgets. Use the `from_memory` query parameter to get data from in-memory cache. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of all budgets. Use the `from_memory` query parameter to get data from in-memory cache. --- # List customers URL: /finops-api/governance/listCustomers *** title: List customers full: true \_openapi: method: GET route: /api/governance/customers toc: \[] structuredData: headings: \[] contents: * content: Returns a list of all customers. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of all customers. --- # List model configs URL: /finops-api/governance/listModelConfigs *** title: List model configs full: true \_openapi: method: GET route: /api/governance/model-configs toc: \[] structuredData: headings: \[] contents: * content: >- Returns a list of all model configurations with their budget and rate limit settings. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of all model configurations with their budget and rate limit settings. --- # List pricing overrides URL: /finops-api/governance/listPricingOverrides *** title: List pricing overrides full: true \_openapi: method: GET route: /api/governance/pricing-overrides toc: \[] structuredData: headings: \[] contents: * content: Returns all pricing overrides, optionally filtered by scope. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns all pricing overrides, optionally filtered by scope. --- # List provider governance URL: /finops-api/governance/listProviderGovernance *** title: List provider governance full: true \_openapi: method: GET route: /api/governance/providers toc: \[] structuredData: headings: \[] contents: * content: >- Returns a list of all providers with their governance settings (budget and rate limits). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of all providers with their governance settings (budget and rate limits). --- # List rate limits URL: /finops-api/governance/listRateLimits *** title: List rate limits full: true \_openapi: method: GET route: /api/governance/rate-limits toc: \[] structuredData: headings: \[] contents: * content: >- Returns a list of all rate limits. Use the `from_memory` query parameter to get data from in-memory cache. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of all rate limits. Use the `from_memory` query parameter to get data from in-memory cache. --- # List routing rules URL: /finops-api/governance/listRoutingRules *** title: List routing rules full: true \_openapi: method: GET route: /api/governance/routing-rules toc: \[] structuredData: headings: \[] contents: * content: >- Returns a list of all routing rules configured for intelligent request routing across providers. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of all routing rules configured for intelligent request routing across providers. --- # List teams URL: /finops-api/governance/listTeams *** title: List teams full: true \_openapi: method: GET route: /api/governance/teams toc: \[] structuredData: headings: \[] contents: * content: Returns a list of all teams. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of all teams. --- # List virtual keys URL: /finops-api/governance/listVirtualKeys *** title: List virtual keys full: true \_openapi: method: GET route: /api/governance/virtual-keys toc: \[] structuredData: headings: \[] contents: * content: Returns a list of all virtual keys with their configurations. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of all virtual keys with their configurations. --- # Update customer URL: /finops-api/governance/updateCustomer *** title: Update customer full: true \_openapi: method: PUT route: /api/governance/customers/{customer_id} toc: \[] structuredData: headings: \[] contents: * content: Updates an existing customer. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates an existing customer. --- # Update model config URL: /finops-api/governance/updateModelConfig *** title: Update model config full: true \_openapi: method: PUT route: /api/governance/model-configs/{mc_id} toc: \[] structuredData: headings: \[] contents: * content: >- Updates an existing model configuration's budget and rate limit settings. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates an existing model configuration's budget and rate limit settings. --- # Update pricing override URL: /finops-api/governance/updatePricingOverride *** title: Update pricing override full: true \_openapi: method: PUT route: /api/governance/pricing-overrides/{id} toc: \[] structuredData: headings: \[] contents: * content: >- Updates an existing pricing override. Omitted fields are merged from the existing record. The `patch` field is always replaced in full when provided. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates an existing pricing override. Omitted fields are merged from the existing record. The `patch` field is always replaced in full when provided. --- # Update provider governance URL: /finops-api/governance/updateProviderGovernance *** title: Update provider governance full: true \_openapi: method: PUT route: /api/governance/providers/{provider_name} toc: \[] structuredData: headings: \[] contents: * content: >- Updates governance settings (budget and rate limits) for a specific provider. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates governance settings (budget and rate limits) for a specific provider. --- # Update routing rule URL: /finops-api/governance/updateRoutingRule *** title: Update routing rule full: true \_openapi: method: PUT route: /api/governance/routing-rules/{rule_id} toc: \[] structuredData: headings: \[] contents: * content: Updates an existing routing rule's configuration. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates an existing routing rule's configuration. --- # Update team URL: /finops-api/governance/updateTeam *** title: Update team full: true \_openapi: method: PUT route: /api/governance/teams/{team_id} toc: \[] structuredData: headings: \[] contents: * content: Updates an existing team. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates an existing team. --- # Update virtual key URL: /finops-api/governance/updateVirtualKey *** title: Update virtual key full: true \_openapi: method: PUT route: /api/governance/virtual-keys/{vk_id} toc: \[] structuredData: headings: \[] contents: * content: Updates an existing virtual key's configuration. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates an existing virtual key's configuration. --- # Prometheus metrics URL: /finops-api/infrastructure/getMetrics *** title: Prometheus metrics full: true \_openapi: method: GET route: /metrics toc: \[] structuredData: headings: \[] contents: * content: Returns Prometheus-formatted metrics for monitoring. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns Prometheus-formatted metrics for monitoring. --- # MCP protocol message URL: /finops-api/infrastructure/mcpServerMessage *** title: MCP protocol message full: true \_openapi: method: POST route: /mcp toc: \[] structuredData: headings: \[] contents: * content: | Receives a JSON-RPC 2.0 message for the MCP protocol server. Returns a JSON-RPC 2.0 response, or null for notifications. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Receives a JSON-RPC 2.0 message for the MCP protocol server. Returns a JSON-RPC 2.0 response, or null for notifications. --- # MCP protocol SSE stream URL: /finops-api/infrastructure/mcpServerSSE *** title: MCP protocol SSE stream full: true \_openapi: method: GET route: /mcp toc: \[] structuredData: headings: \[] contents: * content: | Opens a Server-Sent Events stream for the MCP protocol server. Returns `Content-Type: text/event-stream`. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Opens a Server-Sent Events stream for the MCP protocol server. Returns `Content-Type: text/event-stream`. --- # WebSocket connection URL: /finops-api/infrastructure/websocketConnect *** title: WebSocket connection full: true \_openapi: method: GET route: /ws toc: \[] structuredData: headings: \[] contents: * content: > Upgrades to a WebSocket connection for real-time updates. Server pushes log events, MCP log events, and store update notifications. Heartbeat pings are sent every 30 seconds. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Upgrades to a WebSocket connection for real-time updates. Server pushes log events, MCP log events, and store update notifications. Heartbeat pings are sent every 30 seconds. --- # Count tokens (LangChain - Anthropic format) URL: /finops-api/langchain-integration/langchainAnthropicCountTokens *** title: Count tokens (LangChain - Anthropic format) full: true \_openapi: method: POST route: /langchain/anthropic/v1/messages/count\_tokens toc: \[] structuredData: headings: \[] contents: * content: | Counts tokens using Anthropic-compatible format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Counts tokens using Anthropic-compatible format via LangChain. --- # Create message (LangChain - Anthropic format) URL: /finops-api/langchain-integration/langchainAnthropicMessages *** title: Create message (LangChain - Anthropic format) full: true \_openapi: method: POST route: /langchain/anthropic/v1/messages toc: \[] structuredData: headings: \[] contents: * content: | Creates a message using Anthropic-compatible format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a message using Anthropic-compatible format via LangChain. --- # Converse with model (LangChain - Bedrock format) URL: /finops-api/langchain-integration/langchainBedrockConverse *** title: Converse with model (LangChain - Bedrock format) full: true \_openapi: method: POST route: /langchain/bedrock/model/{modelId}/converse toc: \[] structuredData: headings: \[] contents: * content: > Sends messages using AWS Bedrock Converse-compatible format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Sends messages using AWS Bedrock Converse-compatible format via LangChain. --- # Stream converse with model (LangChain - Bedrock format) URL: /finops-api/langchain-integration/langchainBedrockConverseStream *** title: Stream converse with model (LangChain - Bedrock format) full: true \_openapi: method: POST route: /langchain/bedrock/model/{modelId}/converse-stream toc: \[] structuredData: headings: \[] contents: * content: > Streams messages using AWS Bedrock Converse-compatible format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Streams messages using AWS Bedrock Converse-compatible format via LangChain. --- # Chat with model (LangChain - Cohere format) URL: /finops-api/langchain-integration/langchainCohereChat *** title: Chat with model (LangChain - Cohere format) full: true \_openapi: method: POST route: /langchain/cohere/v2/chat toc: \[] structuredData: headings: \[] contents: * content: | Sends a chat request using Cohere-compatible format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Sends a chat request using Cohere-compatible format via LangChain. --- # Create embeddings (LangChain - Cohere format) URL: /finops-api/langchain-integration/langchainCohereEmbed *** title: Create embeddings (LangChain - Cohere format) full: true \_openapi: method: POST route: /langchain/cohere/v2/embed toc: \[] structuredData: headings: \[] contents: * content: | Creates embeddings using Cohere-compatible format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates embeddings using Cohere-compatible format via LangChain. --- # Tokenize text (LangChain - Cohere format) URL: /finops-api/langchain-integration/langchainCohereTokenize *** title: Tokenize text (LangChain - Cohere format) full: true \_openapi: method: POST route: /langchain/cohere/v1/tokenize toc: \[] structuredData: headings: \[] contents: * content: | Tokenizes text using Cohere-compatible format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Tokenizes text using Cohere-compatible format via LangChain. --- # Generate content (LangChain - Gemini format) URL: /finops-api/langchain-integration/langchainGeminiGenerateContent *** title: Generate content (LangChain - Gemini format) full: true \_openapi: method: POST route: /langchain/genai/v1beta/models/{model}:generateContent toc: \[] structuredData: headings: \[] contents: * content: | Generates content using Google Gemini-compatible format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates content using Google Gemini-compatible format via LangChain. --- # List models (LangChain - Gemini format) URL: /finops-api/langchain-integration/langchainGeminiListModels *** title: List models (LangChain - Gemini format) full: true \_openapi: method: GET route: /langchain/genai/v1beta/models toc: \[] structuredData: headings: \[] contents: * content: | Lists available models in Google Gemini API format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models in Google Gemini API format via LangChain. --- # Stream generate content (LangChain - Gemini format) URL: /finops-api/langchain-integration/langchainGeminiStreamGenerateContent *** title: Stream generate content (LangChain - Gemini format) full: true \_openapi: method: POST route: /langchain/genai/v1beta/models/{model}:streamGenerateContent toc: \[] structuredData: headings: \[] contents: * content: > Streams content generation using Google Gemini-compatible format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Streams content generation using Google Gemini-compatible format via LangChain. --- # Chat completions (LangChain - OpenAI format) URL: /finops-api/langchain-integration/langchainOpenAIChatCompletions *** title: Chat completions (LangChain - OpenAI format) full: true \_openapi: method: POST route: /langchain/v1/chat/completions toc: \[] structuredData: headings: \[] contents: * content: > Creates a chat completion using OpenAI-compatible format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a chat completion using OpenAI-compatible format via LangChain. --- # Count input tokens (LangChain - OpenAI format) URL: /finops-api/langchain-integration/langchainOpenAICountInputTokens *** title: Count input tokens (LangChain - OpenAI format) full: true \_openapi: method: POST route: /langchain/v1/responses/input\_tokens toc: \[] structuredData: headings: \[] contents: * content: | Counts the number of tokens in a Responses API request via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Counts the number of tokens in a Responses API request via LangChain. --- # Create embeddings (LangChain - OpenAI format) URL: /finops-api/langchain-integration/langchainOpenAIEmbeddings *** title: Create embeddings (LangChain - OpenAI format) full: true \_openapi: method: POST route: /langchain/v1/embeddings toc: \[] structuredData: headings: \[] contents: * content: | Creates embeddings using OpenAI-compatible format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates embeddings using OpenAI-compatible format via LangChain. --- # List models (LangChain - OpenAI format) URL: /finops-api/langchain-integration/langchainOpenAIListModels *** title: List models (LangChain - OpenAI format) full: true \_openapi: method: GET route: /langchain/v1/models toc: \[] structuredData: headings: \[] contents: * content: | Lists available models using OpenAI-compatible format via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models using OpenAI-compatible format via LangChain. --- # Create response (LangChain - OpenAI Responses API) URL: /finops-api/langchain-integration/langchainOpenAIResponses *** title: Create response (LangChain - OpenAI Responses API) full: true \_openapi: method: POST route: /langchain/v1/responses toc: \[] structuredData: headings: \[] contents: * content: | Creates a response using OpenAI Responses API format via LangChain. Supports streaming via SSE. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a response using OpenAI Responses API format via LangChain. Supports streaming via SSE. --- # Create speech (LangChain - OpenAI TTS) URL: /finops-api/langchain-integration/langchainOpenAISpeech *** title: Create speech (LangChain - OpenAI TTS) full: true \_openapi: method: POST route: /langchain/v1/audio/speech toc: \[] structuredData: headings: \[] contents: * content: | Generates audio from text using OpenAI TTS via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates audio from text using OpenAI TTS via LangChain. --- # Text completions (LangChain - OpenAI format) URL: /finops-api/langchain-integration/langchainOpenAITextCompletions *** title: Text completions (LangChain - OpenAI format) full: true \_openapi: method: POST route: /langchain/v1/completions toc: \[] structuredData: headings: \[] contents: * content: > Creates a text completion using OpenAI-compatible format via LangChain. This is the legacy completions API. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a text completion using OpenAI-compatible format via LangChain. This is the legacy completions API. --- # Create transcription (LangChain - OpenAI Whisper) URL: /finops-api/langchain-integration/langchainOpenAITranscriptions *** title: Create transcription (LangChain - OpenAI Whisper) full: true \_openapi: method: POST route: /langchain/v1/audio/transcriptions toc: \[] structuredData: headings: \[] contents: * content: | Transcribes audio into text using OpenAI Whisper via LangChain. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Transcribes audio into text using OpenAI Whisper via LangChain. --- # Create message (LiteLLM - Anthropic format) URL: /finops-api/litellm-integration/litellmAnthropicMessages *** title: Create message (LiteLLM - Anthropic format) full: true \_openapi: method: POST route: /litellm/anthropic/v1/messages toc: \[] structuredData: headings: \[] contents: * content: | Creates a message using Anthropic-compatible format via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a message using Anthropic-compatible format via LiteLLM. --- # Converse with model (LiteLLM - Bedrock format) URL: /finops-api/litellm-integration/litellmBedrockConverse *** title: Converse with model (LiteLLM - Bedrock format) full: true \_openapi: method: POST route: /litellm/bedrock/model/{modelId}/converse toc: \[] structuredData: headings: \[] contents: * content: > Sends messages using AWS Bedrock Converse-compatible format via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Sends messages using AWS Bedrock Converse-compatible format via LiteLLM. --- # Stream converse with model (LiteLLM - Bedrock format) URL: /finops-api/litellm-integration/litellmBedrockConverseStream *** title: Stream converse with model (LiteLLM - Bedrock format) full: true \_openapi: method: POST route: /litellm/bedrock/model/{modelId}/converse-stream toc: \[] structuredData: headings: \[] contents: * content: > Streams messages using AWS Bedrock Converse-compatible format via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Streams messages using AWS Bedrock Converse-compatible format via LiteLLM. --- # Chat with model (LiteLLM - Cohere format) URL: /finops-api/litellm-integration/litellmCohereChat *** title: Chat with model (LiteLLM - Cohere format) full: true \_openapi: method: POST route: /litellm/cohere/v2/chat toc: \[] structuredData: headings: \[] contents: * content: | Sends a chat request using Cohere-compatible format via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Sends a chat request using Cohere-compatible format via LiteLLM. --- # Create embeddings (LiteLLM - Cohere format) URL: /finops-api/litellm-integration/litellmCohereEmbed *** title: Create embeddings (LiteLLM - Cohere format) full: true \_openapi: method: POST route: /litellm/cohere/v2/embed toc: \[] structuredData: headings: \[] contents: * content: | Creates embeddings using Cohere-compatible format via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates embeddings using Cohere-compatible format via LiteLLM. --- # Tokenize text (LiteLLM - Cohere format) URL: /finops-api/litellm-integration/litellmCohereTokenize *** title: Tokenize text (LiteLLM - Cohere format) full: true \_openapi: method: POST route: /litellm/cohere/v1/tokenize toc: \[] structuredData: headings: \[] contents: * content: | Tokenizes text using Cohere-compatible format via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Tokenizes text using Cohere-compatible format via LiteLLM. --- # Generate content (LiteLLM - Gemini format) URL: /finops-api/litellm-integration/litellmGeminiGenerateContent *** title: Generate content (LiteLLM - Gemini format) full: true \_openapi: method: POST route: /litellm/genai/v1beta/models/{model}:generateContent toc: \[] structuredData: headings: \[] contents: * content: | Generates content using Google Gemini-compatible format via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates content using Google Gemini-compatible format via LiteLLM. --- # List models (LiteLLM - Gemini format) URL: /finops-api/litellm-integration/litellmGeminiListModels *** title: List models (LiteLLM - Gemini format) full: true \_openapi: method: GET route: /litellm/genai/v1beta/models toc: \[] structuredData: headings: \[] contents: * content: | Lists available models in Google Gemini API format via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models in Google Gemini API format via LiteLLM. --- # Stream generate content (LiteLLM - Gemini format) URL: /finops-api/litellm-integration/litellmGeminiStreamGenerateContent *** title: Stream generate content (LiteLLM - Gemini format) full: true \_openapi: method: POST route: /litellm/genai/v1beta/models/{model}:streamGenerateContent toc: \[] structuredData: headings: \[] contents: * content: > Streams content generation using Google Gemini-compatible format via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Streams content generation using Google Gemini-compatible format via LiteLLM. --- # Chat completions (LiteLLM - OpenAI format) URL: /finops-api/litellm-integration/litellmOpenAIChatCompletions *** title: Chat completions (LiteLLM - OpenAI format) full: true \_openapi: method: POST route: /litellm/v1/chat/completions toc: \[] structuredData: headings: \[] contents: * content: | Creates a chat completion using OpenAI-compatible format via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a chat completion using OpenAI-compatible format via LiteLLM. --- # Count input tokens (LiteLLM - OpenAI format) URL: /finops-api/litellm-integration/litellmOpenAICountInputTokens *** title: Count input tokens (LiteLLM - OpenAI format) full: true \_openapi: method: POST route: /litellm/v1/responses/input\_tokens toc: \[] structuredData: headings: \[] contents: * content: | Counts the number of tokens in a Responses API request via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Counts the number of tokens in a Responses API request via LiteLLM. --- # Create embeddings (LiteLLM - OpenAI format) URL: /finops-api/litellm-integration/litellmOpenAIEmbeddings *** title: Create embeddings (LiteLLM - OpenAI format) full: true \_openapi: method: POST route: /litellm/v1/embeddings toc: \[] structuredData: headings: \[] contents: * content: | Creates embeddings using OpenAI-compatible format via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates embeddings using OpenAI-compatible format via LiteLLM. --- # List models (LiteLLM - OpenAI format) URL: /finops-api/litellm-integration/litellmOpenAIListModels *** title: List models (LiteLLM - OpenAI format) full: true \_openapi: method: GET route: /litellm/v1/models toc: \[] structuredData: headings: \[] contents: * content: | Lists available models using OpenAI-compatible format via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models using OpenAI-compatible format via LiteLLM. --- # Create response (LiteLLM - OpenAI Responses API) URL: /finops-api/litellm-integration/litellmOpenAIResponses *** title: Create response (LiteLLM - OpenAI Responses API) full: true \_openapi: method: POST route: /litellm/v1/responses toc: \[] structuredData: headings: \[] contents: * content: | Creates a response using OpenAI Responses API format via LiteLLM. Supports streaming via SSE. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a response using OpenAI Responses API format via LiteLLM. Supports streaming via SSE. --- # Create speech (LiteLLM - OpenAI TTS) URL: /finops-api/litellm-integration/litellmOpenAISpeech *** title: Create speech (LiteLLM - OpenAI TTS) full: true \_openapi: method: POST route: /litellm/v1/audio/speech toc: \[] structuredData: headings: \[] contents: * content: | Generates audio from text using OpenAI TTS via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates audio from text using OpenAI TTS via LiteLLM. --- # Text completions (LiteLLM - OpenAI format) URL: /finops-api/litellm-integration/litellmOpenAITextCompletions *** title: Text completions (LiteLLM - OpenAI format) full: true \_openapi: method: POST route: /litellm/v1/completions toc: \[] structuredData: headings: \[] contents: * content: | Creates a text completion using OpenAI-compatible format via LiteLLM. This is the legacy completions API. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a text completion using OpenAI-compatible format via LiteLLM. This is the legacy completions API. --- # Create transcription (LiteLLM - OpenAI Whisper) URL: /finops-api/litellm-integration/litellmOpenAITranscriptions *** title: Create transcription (LiteLLM - OpenAI Whisper) full: true \_openapi: method: POST route: /litellm/v1/audio/transcriptions toc: \[] structuredData: headings: \[] contents: * content: | Transcribes audio into text using OpenAI Whisper via LiteLLM. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Transcribes audio into text using OpenAI Whisper via LiteLLM. --- # Delete logs URL: /finops-api/logging/deleteLogs *** title: Delete logs full: true \_openapi: method: DELETE route: /api/logs toc: \[] structuredData: headings: \[] contents: * content: Deletes logs by their IDs. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes logs by their IDs. --- # Delete MCP tool logs URL: /finops-api/logging/deleteMCPLogs *** title: Delete MCP tool logs full: true \_openapi: method: DELETE route: /api/mcp-logs toc: \[] structuredData: headings: \[] contents: * content: Deletes MCP tool logs by their IDs. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes MCP tool logs by their IDs. --- # Get available filter data URL: /finops-api/logging/getAvailableFilterData *** title: Get available filter data full: true \_openapi: method: GET route: /api/logs/filterdata toc: \[] structuredData: headings: \[] contents: * content: Returns all unique filter data from logs (models, keys, virtual keys). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns all unique filter data from logs (models, keys, virtual keys). --- # Get dropped requests count URL: /finops-api/logging/getDroppedRequests *** title: Get dropped requests count full: true \_openapi: method: GET route: /api/logs/dropped toc: \[] structuredData: headings: \[] contents: * content: Returns the number of dropped requests. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the number of dropped requests. --- # Get a single log entry URL: /finops-api/logging/getLogById *** title: Get a single log entry full: true \_openapi: method: GET route: /api/logs/{id} toc: \[] structuredData: headings: \[] contents: * content: Retrieves a single log entry by its ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves a single log entry by its ID. --- # Get logs for a session URL: /finops-api/logging/getLogSessionById *** title: Get logs for a session full: true \_openapi: method: GET route: /api/logs/sessions/{session_id} toc: \[] structuredData: headings: \[] contents: * content: > Returns the paginated logs belonging to a single parent-request session (grouped by `parent_request_id`). Sorted ascending by timestamp by default. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the paginated logs belonging to a single parent-request session (grouped by `parent_request_id`). Sorted ascending by timestamp by default. --- # Get aggregate totals for a session URL: /finops-api/logging/getLogSessionSummaryById *** title: Get aggregate totals for a session full: true \_openapi: method: GET route: /api/logs/sessions/{session_id}/summary toc: \[] structuredData: headings: \[] contents: * content: >- Returns aggregate request count, token usage, cost, and duration for a single session. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns aggregate request count, token usage, cost, and duration for a single session. --- # Get logs URL: /finops-api/logging/getLogs *** title: Get logs full: true \_openapi: method: GET route: /api/logs toc: \[] structuredData: headings: \[] contents: * content: > Retrieves logs with filtering, search, and pagination via query parameters. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves logs with filtering, search, and pagination via query parameters. --- # Get cost histogram URL: /finops-api/logging/getLogsCostHistogram *** title: Get cost histogram full: true \_openapi: method: GET route: /api/logs/histogram/cost toc: \[] structuredData: headings: \[] contents: * content: Returns time-bucketed cost data with model breakdown. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed cost data with model breakdown. --- # Get cost histogram by dimension URL: /finops-api/logging/getLogsDimensionCostHistogram *** title: Get cost histogram by dimension full: true \_openapi: method: GET route: /api/logs/histogram/cost/by-dimension toc: \[] structuredData: headings: \[] contents: * content: > Returns time-bucketed cost data grouped by an arbitrary dimension (`provider`, `team_id`, `customer_id`, `user_id`, `business_unit_id`). The dimension is supplied via the required `dimension` query parameter. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed cost data grouped by an arbitrary dimension (`provider`, `team_id`, `customer_id`, `user_id`, `business_unit_id`). The dimension is supplied via the required `dimension` query parameter. --- # Get latency histogram by dimension URL: /finops-api/logging/getLogsDimensionLatencyHistogram *** title: Get latency histogram by dimension full: true \_openapi: method: GET route: /api/logs/histogram/latency/by-dimension toc: \[] structuredData: headings: \[] contents: * content: > Returns time-bucketed latency percentiles (avg, p90, p95, p99) grouped by an arbitrary dimension. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed latency percentiles (avg, p90, p95, p99) grouped by an arbitrary dimension. --- # Get token histogram by dimension URL: /finops-api/logging/getLogsDimensionTokenHistogram *** title: Get token histogram by dimension full: true \_openapi: method: GET route: /api/logs/histogram/tokens/by-dimension toc: \[] structuredData: headings: \[] contents: * content: > Returns time-bucketed token usage grouped by an arbitrary dimension. See `getLogsDimensionCostHistogram` for the list of supported dimensions. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed token usage grouped by an arbitrary dimension. See `getLogsDimensionCostHistogram` for the list of supported dimensions. --- # Get request count histogram URL: /finops-api/logging/getLogsHistogram *** title: Get request count histogram full: true \_openapi: method: GET route: /api/logs/histogram toc: \[] structuredData: headings: \[] contents: * content: > Returns time-bucketed request counts. Bucket size is auto-calculated from the time range. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed request counts. Bucket size is auto-calculated from the time range. --- # Get latency histogram URL: /finops-api/logging/getLogsLatencyHistogram *** title: Get latency histogram full: true \_openapi: method: GET route: /api/logs/histogram/latency toc: \[] structuredData: headings: \[] contents: * content: Returns time-bucketed latency percentiles (avg, p90, p95, p99). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed latency percentiles (avg, p90, p95, p99). --- # Get model usage histogram URL: /finops-api/logging/getLogsModelHistogram *** title: Get model usage histogram full: true \_openapi: method: GET route: /api/logs/histogram/models toc: \[] structuredData: headings: \[] contents: * content: Returns time-bucketed model usage with success/error breakdown. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed model usage with success/error breakdown. --- # Get cost histogram by provider URL: /finops-api/logging/getLogsProviderCostHistogram *** title: Get cost histogram by provider full: true \_openapi: method: GET route: /api/logs/histogram/cost/by-provider toc: \[] structuredData: headings: \[] contents: * content: Returns time-bucketed cost data with provider breakdown. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed cost data with provider breakdown. --- # Get latency histogram by provider URL: /finops-api/logging/getLogsProviderLatencyHistogram *** title: Get latency histogram by provider full: true \_openapi: method: GET route: /api/logs/histogram/latency/by-provider toc: \[] structuredData: headings: \[] contents: * content: Returns time-bucketed latency percentiles with provider breakdown. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed latency percentiles with provider breakdown. --- # Get token histogram by provider URL: /finops-api/logging/getLogsProviderTokenHistogram *** title: Get token histogram by provider full: true \_openapi: method: GET route: /api/logs/histogram/tokens/by-provider toc: \[] structuredData: headings: \[] contents: * content: Returns time-bucketed token usage with provider breakdown. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed token usage with provider breakdown. --- # Get log statistics URL: /finops-api/logging/getLogsStats *** title: Get log statistics full: true \_openapi: method: GET route: /api/logs/stats toc: \[] structuredData: headings: \[] contents: * content: Returns statistics for logs matching the specified filters. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns statistics for logs matching the specified filters. --- # Get token usage histogram URL: /finops-api/logging/getLogsTokenHistogram *** title: Get token usage histogram full: true \_openapi: method: GET route: /api/logs/histogram/tokens toc: \[] structuredData: headings: \[] contents: * content: Returns time-bucketed token usage (prompt, completion, total). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed token usage (prompt, completion, total). --- # Get MCP tool log by ID URL: /finops-api/logging/getMCPLogById *** title: Get MCP tool log by ID full: true \_openapi: method: GET route: /api/mcp-logs/{id} toc: \[] structuredData: headings: \[] contents: * content: >- Retrieves a single MCP tool execution log by ID, including hydrated object-storage payloads when configured. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves a single MCP tool execution log by ID, including hydrated object-storage payloads when configured. --- # Get MCP tool logs URL: /finops-api/logging/getMCPLogs *** title: Get MCP tool logs full: true \_openapi: method: GET route: /api/mcp-logs toc: \[] structuredData: headings: \[] contents: * content: > Retrieves MCP tool execution logs with filtering, search, and pagination via query parameters. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves MCP tool execution logs with filtering, search, and pagination via query parameters. --- # Get MCP cost histogram URL: /finops-api/logging/getMCPLogsCostHistogram *** title: Get MCP cost histogram full: true \_openapi: method: GET route: /api/mcp-logs/histogram/cost toc: \[] structuredData: headings: \[] contents: * content: Returns time-bucketed MCP tool call cost data. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed MCP tool call cost data. --- # Get available MCP log filter data URL: /finops-api/logging/getMCPLogsFilterData *** title: Get available MCP log filter data full: true \_openapi: method: GET route: /api/mcp-logs/filterdata toc: \[] structuredData: headings: \[] contents: * content: >- Returns all unique filter data from MCP tool logs (tool names, server labels). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns all unique filter data from MCP tool logs (tool names, server labels). --- # Get MCP tool call volume histogram URL: /finops-api/logging/getMCPLogsHistogram *** title: Get MCP tool call volume histogram full: true \_openapi: method: GET route: /api/mcp-logs/histogram toc: \[] structuredData: headings: \[] contents: * content: >- Returns time-bucketed MCP tool call volume with success/error breakdown. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns time-bucketed MCP tool call volume with success/error breakdown. --- # Get MCP tool log statistics URL: /finops-api/logging/getMCPLogsStats *** title: Get MCP tool log statistics full: true \_openapi: method: GET route: /api/mcp-logs/stats toc: \[] structuredData: headings: \[] contents: * content: Returns statistics for MCP tool logs matching the specified filters. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns statistics for MCP tool logs matching the specified filters. --- # Get top MCP tools by call count URL: /finops-api/logging/getMCPLogsTopTools *** title: Get top MCP tools by call count full: true \_openapi: method: GET route: /api/mcp-logs/histogram/top-tools toc: \[] structuredData: headings: \[] contents: * content: Returns the top 10 MCP tools by call count, with cost totals. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the top 10 MCP tools by call count, with cost totals. --- # Get model usage rankings URL: /finops-api/logging/getModelRankings *** title: Get model usage rankings full: true \_openapi: method: GET route: /api/logs/rankings toc: \[] structuredData: headings: \[] contents: * content: > Returns models ranked by usage with trend percentages versus the previous comparable period. Accepts the same filter parameters as the histogram endpoints. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns models ranked by usage with trend percentages versus the previous comparable period. Accepts the same filter parameters as the histogram endpoints. --- # Recalculate log costs URL: /finops-api/logging/recalculateLogCosts *** title: Recalculate log costs full: true \_openapi: method: POST route: /api/logs/recalculate-cost toc: \[] structuredData: headings: \[] contents: * content: > Recomputes missing costs in batches. Processes logs with missing cost values and updates them based on current pricing data. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Recomputes missing costs in batches. Processes logs with missing cost values and updates them based on current pricing data. --- # Create MCP Tool Group URL: /finops-api/mcp-tool-groups/createMCPToolGroup *** title: Create MCP Tool Group full: true \_openapi: method: POST route: /api/mcp/tool-groups toc: \[] structuredData: headings: \[] contents: * content: > Creates a new tool group along with its attachments in a single transaction. Validates that every `mcp_client_id` points to a deployed MCP client and that every named tool exists on its server. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new tool group along with its attachments in a single transaction. Validates that every `mcp_client_id` points to a deployed MCP client and that every named tool exists on its server. --- # Delete MCP Tool Group URL: /finops-api/mcp-tool-groups/deleteMCPToolGroup *** title: Delete MCP Tool Group full: true \_openapi: method: DELETE route: /api/mcp/tool-groups/{id} toc: \[] structuredData: headings: \[] contents: * content: Deletes the group; attachments are removed automatically. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes the group; attachments are removed automatically. --- # Get MCP Tool Group by ID URL: /finops-api/mcp-tool-groups/getMCPToolGroup *** title: Get MCP Tool Group by ID full: true \_openapi: method: GET route: /api/mcp/tool-groups/{id} toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # List MCP Tool Groups URL: /finops-api/mcp-tool-groups/listMCPToolGroups *** title: List MCP Tool Groups full: true \_openapi: method: GET route: /api/mcp/tool-groups toc: \[] structuredData: headings: \[] contents: * content: > Returns tool groups visible to the caller. When all of `limit`, `offset`, and `search` are omitted, every group is returned in one response. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns tool groups visible to the caller. When all of `limit`, `offset`, and `search` are omitted, every group is returned in one response. --- # Update MCP Tool Group URL: /finops-api/mcp-tool-groups/updateMCPToolGroup *** title: Update MCP Tool Group full: true \_openapi: method: PUT route: /api/mcp/tool-groups/{id} toc: \[] structuredData: headings: \[] contents: * content: > Partial update. Scalar fields preserve the current value when omitted. Array fields are replace-on-send: an empty array clears all attachments in that dimension. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Partial update. Scalar fields preserve the current value when omitted. Array fields are replace-on-send: an empty array clears all attachments in that dimension. --- # Add MCP client URL: /finops-api/mcp/addMCPClient *** title: Add MCP client full: true \_openapi: method: POST route: /api/mcp/client toc: \[] structuredData: headings: \[] contents: * content: > Adds a new MCP client with the specified configuration. Note: tool\_pricing is not available when creating a new client as tools are fetched after client creation. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Adds a new MCP client with the specified configuration. Note: tool\_pricing is not available when creating a new client as tools are fetched after client creation. --- # Complete MCP client OAuth flow URL: /finops-api/mcp/completeMCPClientOAuth *** title: Complete MCP client OAuth flow full: true \_openapi: method: POST route: /api/mcp/client/{id}/complete-oauth toc: \[] structuredData: headings: \[] contents: * content: > Completes the OAuth flow for an MCP client after the user has authorized the request. This endpoint should be called after the OAuth provider redirects back to the callback endpoint and the OAuth token has been stored. It retrieves the pending MCP client configuration and establishes the connection with the OAuth-provided credentials. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Completes the OAuth flow for an MCP client after the user has authorized the request. This endpoint should be called after the OAuth provider redirects back to the callback endpoint and the OAuth token has been stored. It retrieves the pending MCP client configuration and establishes the connection with the OAuth-provided credentials. --- # Edit MCP client URL: /finops-api/mcp/editMCPClient *** title: Edit MCP client full: true \_openapi: method: PUT route: /api/mcp/client/{id} toc: \[] structuredData: headings: \[] contents: * content: > Updates an existing MCP client's configuration. Unlike client creation, tool\_pricing can be included to set per-tool execution costs since tools are already fetched. Optionally provide vk\_configs to manage which virtual keys have access to this MCP server and with which tools. When provided, this fully replaces all existing VK assignments in a single atomic transaction. Set disabled: true to shut down the client's connection and workers without removing it. Set disabled: false to reconnect a previously disabled client. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates an existing MCP client's configuration. Unlike client creation, tool\_pricing can be included to set per-tool execution costs since tools are already fetched. Optionally provide vk\_configs to manage which virtual keys have access to this MCP server and with which tools. When provided, this fully replaces all existing VK assignments in a single atomic transaction. Set disabled: true to shut down the client's connection and workers without removing it. Set disabled: false to reconnect a previously disabled client. --- # Execute MCP tool URL: /finops-api/mcp/executeMCPTool *** title: Execute MCP tool full: true \_openapi: method: POST route: /v1/mcp/tool/execute toc: \[] structuredData: headings: \[] contents: * content: Executes an MCP tool and returns the result. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Executes an MCP tool and returns the result. --- # List MCP clients URL: /finops-api/mcp/getMCPClients *** title: List MCP clients full: true \_openapi: method: GET route: /api/mcp/clients toc: \[] structuredData: headings: \[] contents: * content: >- Returns a list of all configured MCP clients with their tools and connection state. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of all configured MCP clients with their tools and connection state. --- # Reconnect MCP client URL: /finops-api/mcp/reconnectMCPClient *** title: Reconnect MCP client full: true \_openapi: method: POST route: /api/mcp/client/{id}/reconnect toc: \[] structuredData: headings: \[] contents: * content: Reconnects an MCP client that is in an error or disconnected state. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Reconnects an MCP client that is in an error or disconnected state. --- # Remove MCP client URL: /finops-api/mcp/removeMCPClient *** title: Remove MCP client full: true \_openapi: method: DELETE route: /api/mcp/client/{id} toc: \[] structuredData: headings: \[] contents: * content: Removes an MCP client from the configuration. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Removes an MCP client from the configuration. --- # List available models URL: /finops-api/models/listModels *** title: List available models full: true \_openapi: method: GET route: /v1/models toc: \[] structuredData: headings: \[] contents: * content: > Lists available models. If provider is not specified, lists all models from all configured providers. If a virtual key is provided, Bifrost only lists (and only queries) providers allowed by that virtual key. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models. If provider is not specified, lists all models from all configured providers. If a virtual key is provided, Bifrost only lists (and only queries) providers allowed by that virtual key. --- # Authorization endpoint (OAuth 2.1) URL: /finops-api/oauth/authorizePerUserOAuth *** title: Authorization endpoint (OAuth 2.1) full: true \_openapi: method: GET route: /api/oauth/per-user/authorize toc: \[] structuredData: headings: \[] contents: * content: > OAuth 2.1 authorization endpoint. Validates the request parameters, creates a browser-bound `PendingFlow` record (15-minute TTL), and redirects the user to the Bifrost consent screen at `/oauth/consent?flow_id=xxx`. **PKCE is required** - `code_challenge` and `code_challenge_method=S256` must be provided. Plain code challenges are not supported. A `__bifrost_flow_secret` HttpOnly SameSite=Lax cookie is set on redirect to bind the consent flow to the initiating browser session (CSRF protection). Authentication is not required - this is part of the unauthenticated OAuth bootstrap flow. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} OAuth 2.1 authorization endpoint. Validates the request parameters, creates a browser-bound `PendingFlow` record (15-minute TTL), and redirects the user to the Bifrost consent screen at `/oauth/consent?flow_id=xxx`. **PKCE is required** - `code_challenge` and `code_challenge_method=S256` must be provided. Plain code challenges are not supported. A `__bifrost_flow_secret` HttpOnly SameSite=Lax cookie is set on redirect to bind the consent flow to the initiating browser session (CSRF protection). Authentication is not required - this is part of the unauthenticated OAuth bootstrap flow. --- # Upstream OAuth proxy - authorize with upstream service URL: /finops-api/oauth/authorizeUpstreamPerUserOAuth *** title: Upstream OAuth proxy - authorize with upstream service full: true \_openapi: method: GET route: /api/oauth/per-user/upstream/authorize toc: \[] structuredData: headings: \[] contents: * content: > Initiates an OAuth flow with an upstream MCP service (Notion, GitHub, etc.) on behalf of the current user. Used during the consent flow (via "Connect" buttons on the MCPs page) and at runtime when a tool call is made to an unauthenticated service. **Consent flow** - provide `flow_id` (from the pending consent flow). The browser-binding cookie (`__bifrost_flow_secret`) is validated. **Runtime flow** - provide `session` (the Bifrost session ID from the token endpoint). Used when a service was skipped during consent and needs to be connected later. On success, redirects the user to the upstream provider's authorize URL. After the user grants access, the upstream callback lands at `/api/oauth/callback`, stores the upstream token against the user's identity, and redirects back to the consent screen (consent flow) or returns an authorization success page (runtime flow). Authentication is not required - cookie/session validation is performed instead. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Initiates an OAuth flow with an upstream MCP service (Notion, GitHub, etc.) on behalf of the current user. Used during the consent flow (via "Connect" buttons on the MCPs page) and at runtime when a tool call is made to an unauthenticated service. **Consent flow** - provide `flow_id` (from the pending consent flow). The browser-binding cookie (`__bifrost_flow_secret`) is validated. **Runtime flow** - provide `session` (the Bifrost session ID from the token endpoint). Used when a service was skipped during consent and needs to be connected later. On success, redirects the user to the upstream provider's authorize URL. After the user grants access, the upstream callback lands at `/api/oauth/callback`, stores the upstream token against the user's identity, and redirects back to the consent screen (consent flow) or returns an authorization success page (runtime flow). Authentication is not required - cookie/session validation is performed instead. --- # Complete MCP client OAuth flow URL: /finops-api/oauth/completeMCPClientOAuth *** title: Complete MCP client OAuth flow full: true \_openapi: method: POST route: /api/mcp/client/{id}/complete-oauth toc: \[] structuredData: headings: \[] contents: * content: > Completes the OAuth flow for an MCP client after the user has authorized the request. This endpoint should be called after the OAuth provider redirects back to the callback endpoint and the OAuth token has been stored. It retrieves the pending MCP client configuration and establishes the connection with the OAuth-provided credentials. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Completes the OAuth flow for an MCP client after the user has authorized the request. This endpoint should be called after the OAuth provider redirects back to the callback endpoint and the OAuth token has been stored. It retrieves the pending MCP client configuration and establishes the connection with the OAuth-provided credentials. --- # Token endpoint (OAuth 2.1) URL: /finops-api/oauth/exchangePerUserOAuthToken *** title: Token endpoint (OAuth 2.1) full: true \_openapi: method: POST route: /api/oauth/per-user/token toc: \[] structuredData: headings: \[] contents: * content: > OAuth 2.1 token endpoint. Exchanges a single-use authorization code (5-minute TTL) for a Bifrost-issued access token (24-hour TTL) using PKCE verification. The request body must be `application/x-www-form-urlencoded`. The returned `access_token` is the Bearer token to use on subsequent `/mcp` requests. It carries the user's upstream service tokens (Notion, GitHub, etc.) linked to their identity (Virtual Key or User ID) from the consent flow. Authentication is not required - this is part of the unauthenticated OAuth bootstrap flow. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} OAuth 2.1 token endpoint. Exchanges a single-use authorization code (5-minute TTL) for a Bifrost-issued access token (24-hour TTL) using PKCE verification. The request body must be `application/x-www-form-urlencoded`. The returned `access_token` is the Bearer token to use on subsequent `/mcp` requests. It carries the user's upstream service tokens (Notion, GitHub, etc.) linked to their identity (Virtual Key or User ID) from the consent flow. Authentication is not required - this is part of the unauthenticated OAuth bootstrap flow. --- # Authorization Server Metadata (RFC 8414) URL: /finops-api/oauth/getOAuthAuthorizationServerMetadata *** title: Authorization Server Metadata (RFC 8414) full: true \_openapi: method: GET route: /.well-known/oauth-authorization-server toc: \[] structuredData: headings: \[] contents: * content: > Returns the OAuth 2.0 Authorization Server Metadata document per RFC 8414\. After fetching the Protected Resource Metadata, MCP clients fetch this endpoint to discover Bifrost's OAuth endpoints (register, authorize, token) and capabilities (PKCE methods, grant types, etc.). Returns `404` when no MCP clients are configured with `auth_type: per_user_oauth`. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the OAuth 2.0 Authorization Server Metadata document per RFC 8414. After fetching the Protected Resource Metadata, MCP clients fetch this endpoint to discover Bifrost's OAuth endpoints (register, authorize, token) and capabilities (PKCE methods, grant types, etc.). Returns `404` when no MCP clients are configured with `auth_type: per_user_oauth`. --- # Get OAuth config status URL: /finops-api/oauth/getOAuthConfigStatus *** title: Get OAuth config status full: true \_openapi: method: GET route: /api/oauth/config/{id}/status toc: \[] structuredData: headings: \[] contents: * content: | Retrieves the current status of an OAuth configuration. Shows whether the OAuth flow is pending, authorized, or failed, and includes token expiration and scopes if authorized. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the current status of an OAuth configuration. Shows whether the OAuth flow is pending, authorized, or failed, and includes token expiration and scopes if authorized. --- # Protected Resource Metadata (RFC 9728) URL: /finops-api/oauth/getOAuthProtectedResourceMetadata *** title: Protected Resource Metadata (RFC 9728) full: true \_openapi: method: GET route: /.well-known/oauth-protected-resource toc: \[] structuredData: headings: \[] contents: * content: > Returns the OAuth 2.0 Protected Resource Metadata document per RFC 9728\. MCP clients fetch this after receiving a `401` response from `/mcp` (with a `WWW-Authenticate: Bearer resource_metadata=".../.well-known/oauth-protected-resource"` header). The response tells the client which authorization server(s) protect the `/mcp` resource so it can proceed with discovery. Returns `404` when no MCP clients are configured with `auth_type: per_user_oauth`. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the OAuth 2.0 Protected Resource Metadata document per RFC 9728. MCP clients fetch this after receiving a `401` response from `/mcp` (with a `WWW-Authenticate: Bearer resource_metadata=".../.well-known/oauth-protected-resource"` header). The response tells the client which authorization server(s) protect the `/mcp` resource so it can proceed with discovery. Returns `404` when no MCP clients are configured with `auth_type: per_user_oauth`. --- # OAuth callback endpoint URL: /finops-api/oauth/handleOAuthCallback *** title: OAuth callback endpoint full: true \_openapi: method: GET route: /api/oauth/callback toc: \[] structuredData: headings: \[] contents: * content: > Handles the OAuth provider callback after user authorization. This endpoint processes the authorization code and exchanges it for an access token. On success, displays an HTML page that closes the authorization window. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Handles the OAuth provider callback after user authorization. This endpoint processes the authorization code and exchanges it for an access token. On success, displays an HTML page that closes the authorization window. --- # Register OAuth client (RFC 7591) URL: /finops-api/oauth/registerPerUserOAuthClient *** title: Register OAuth client (RFC 7591) full: true \_openapi: method: POST route: /api/oauth/per-user/register toc: \[] structuredData: headings: \[] contents: * content: > Dynamic Client Registration per RFC 7591. MCP clients (Claude Code, Cursor, etc.) call this endpoint to obtain a `client_id` before initiating the authorization flow. This endpoint is only available when at least one MCP client is configured with `auth_type: per_user_oauth`. Returns `404` otherwise. Authentication is not required - this is part of the unauthenticated OAuth bootstrap flow. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Dynamic Client Registration per RFC 7591. MCP clients (Claude Code, Cursor, etc.) call this endpoint to obtain a `client_id` before initiating the authorization flow. This endpoint is only available when at least one MCP client is configured with `auth_type: per_user_oauth`. Returns `404` otherwise. Authentication is not required - this is part of the unauthenticated OAuth bootstrap flow. --- # Revoke OAuth config URL: /finops-api/oauth/revokeOAuthConfig *** title: Revoke OAuth config full: true \_openapi: method: DELETE route: /api/oauth/config/{id}/status toc: \[] structuredData: headings: \[] contents: * content: > Revokes an OAuth configuration and its associated access token. After revocation, the MCP client will no longer be able to use this OAuth token. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Revokes an OAuth configuration and its associated access token. After revocation, the MCP client will no longer be able to use this OAuth token. --- # Perform OCR URL: /finops-api/ocr/performOCR *** title: Perform OCR full: true \_openapi: method: POST route: /v1/ocr toc: \[] structuredData: headings: \[] contents: * content: > Extracts text and content from documents or images using optical character recognition. Supports PDF URLs, base64-encoded documents, and image URLs. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Extracts text and content from documents or images using optical character recognition. Supports PDF URLs, base64-encoded documents, and image URLs. --- # Create a new plugin URL: /finops-api/plugins/createPlugin *** title: Create a new plugin full: true \_openapi: method: POST route: /api/plugins toc: \[] structuredData: headings: \[] contents: * content: Creates a new plugin with the specified configuration. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new plugin with the specified configuration. --- # Delete a plugin URL: /finops-api/plugins/deletePlugin *** title: Delete a plugin full: true \_openapi: method: DELETE route: /api/plugins/{name} toc: \[] structuredData: headings: \[] contents: * content: Removes a plugin from the configuration and stops it if running. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Removes a plugin from the configuration and stops it if running. --- # Get a specific plugin URL: /finops-api/plugins/getPlugin *** title: Get a specific plugin full: true \_openapi: method: GET route: /api/plugins/{name} toc: \[] structuredData: headings: \[] contents: * content: > Returns the configuration for a specific plugin. The response includes the plugin status with types array showing which interfaces the plugin implements (llm, mcp, http). The `actualName` field shows the plugin name from GetName() (used as the map key), which may differ from the display name (`name`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the configuration for a specific plugin. The response includes the plugin status with types array showing which interfaces the plugin implements (llm, mcp, http). The `actualName` field shows the plugin name from GetName() (used as the map key), which may differ from the display name (`name`). --- # List built-in plugin names URL: /finops-api/plugins/listBuiltinPlugins *** title: List built-in plugin names full: true \_openapi: method: GET route: /api/plugins/builtins toc: \[] structuredData: headings: \[] contents: * content: > Returns the canonical list of built-in plugin names available in this Bifrost build. Use this to discover which plugins can be enabled without supplying a custom binary. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the canonical list of built-in plugin names available in this Bifrost build. Use this to discover which plugins can be enabled without supplying a custom binary. --- # List all plugins URL: /finops-api/plugins/listPlugins *** title: List all plugins full: true \_openapi: method: GET route: /api/plugins toc: \[] structuredData: headings: \[] contents: * content: > Returns a list of all plugins with their configurations and status. The `actualName` field contains the plugin name from `GetName()` (used as the map key), while `name` contains the display name from the configuration. The `types` array in the status shows which interfaces the plugin implements (llm, mcp, http). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of all plugins with their configurations and status. The `actualName` field contains the plugin name from `GetName()` (used as the map key), while `name` contains the display name from the configuration. The `types` array in the status shows which interfaces the plugin implements (llm, mcp, http). --- # Update a plugin URL: /finops-api/plugins/updatePlugin *** title: Update a plugin full: true \_openapi: method: PUT route: /api/plugins/{name} toc: \[] structuredData: headings: \[] contents: * content: > Updates a plugin's configuration. Will reload or stop the plugin based on enabled status. The response `actualName` field shows the plugin name from GetName() (used as the map key), which may differ from the display name (`name`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates a plugin's configuration. Will reload or stop the plugin based on enabled status. The response `actualName` field shows the plugin name from GetName() (used as the map key), which may differ from the display name (`name`). --- # Authorization endpoint (OAuth 2.1) URL: /finops-api/per-user-oauth/authorizePerUserOAuth *** title: Authorization endpoint (OAuth 2.1) full: true \_openapi: method: GET route: /api/oauth/per-user/authorize toc: \[] structuredData: headings: \[] contents: * content: > OAuth 2.1 authorization endpoint. Validates the request parameters, creates a browser-bound `PendingFlow` record (15-minute TTL), and redirects the user to the Bifrost consent screen at `/oauth/consent?flow_id=xxx`. **PKCE is required** - `code_challenge` and `code_challenge_method=S256` must be provided. Plain code challenges are not supported. A `__bifrost_flow_secret` HttpOnly SameSite=Lax cookie is set on redirect to bind the consent flow to the initiating browser session (CSRF protection). Authentication is not required - this is part of the unauthenticated OAuth bootstrap flow. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} OAuth 2.1 authorization endpoint. Validates the request parameters, creates a browser-bound `PendingFlow` record (15-minute TTL), and redirects the user to the Bifrost consent screen at `/oauth/consent?flow_id=xxx`. **PKCE is required** - `code_challenge` and `code_challenge_method=S256` must be provided. Plain code challenges are not supported. A `__bifrost_flow_secret` HttpOnly SameSite=Lax cookie is set on redirect to bind the consent flow to the initiating browser session (CSRF protection). Authentication is not required - this is part of the unauthenticated OAuth bootstrap flow. --- # Upstream OAuth proxy - authorize with upstream service URL: /finops-api/per-user-oauth/authorizeUpstreamPerUserOAuth *** title: Upstream OAuth proxy - authorize with upstream service full: true \_openapi: method: GET route: /api/oauth/per-user/upstream/authorize toc: \[] structuredData: headings: \[] contents: * content: > Initiates an OAuth flow with an upstream MCP service (Notion, GitHub, etc.) on behalf of the current user. Used during the consent flow (via "Connect" buttons on the MCPs page) and at runtime when a tool call is made to an unauthenticated service. **Consent flow** - provide `flow_id` (from the pending consent flow). The browser-binding cookie (`__bifrost_flow_secret`) is validated. **Runtime flow** - provide `session` (the Bifrost session ID from the token endpoint). Used when a service was skipped during consent and needs to be connected later. On success, redirects the user to the upstream provider's authorize URL. After the user grants access, the upstream callback lands at `/api/oauth/callback`, stores the upstream token against the user's identity, and redirects back to the consent screen (consent flow) or returns an authorization success page (runtime flow). Authentication is not required - cookie/session validation is performed instead. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Initiates an OAuth flow with an upstream MCP service (Notion, GitHub, etc.) on behalf of the current user. Used during the consent flow (via "Connect" buttons on the MCPs page) and at runtime when a tool call is made to an unauthenticated service. **Consent flow** - provide `flow_id` (from the pending consent flow). The browser-binding cookie (`__bifrost_flow_secret`) is validated. **Runtime flow** - provide `session` (the Bifrost session ID from the token endpoint). Used when a service was skipped during consent and needs to be connected later. On success, redirects the user to the upstream provider's authorize URL. After the user grants access, the upstream callback lands at `/api/oauth/callback`, stores the upstream token against the user's identity, and redirects back to the consent screen (consent flow) or returns an authorization success page (runtime flow). Authentication is not required - cookie/session validation is performed instead. --- # Token endpoint (OAuth 2.1) URL: /finops-api/per-user-oauth/exchangePerUserOAuthToken *** title: Token endpoint (OAuth 2.1) full: true \_openapi: method: POST route: /api/oauth/per-user/token toc: \[] structuredData: headings: \[] contents: * content: > OAuth 2.1 token endpoint. Exchanges a single-use authorization code (5-minute TTL) for a Bifrost-issued access token (24-hour TTL) using PKCE verification. The request body must be `application/x-www-form-urlencoded`. The returned `access_token` is the Bearer token to use on subsequent `/mcp` requests. It carries the user's upstream service tokens (Notion, GitHub, etc.) linked to their identity (Virtual Key or User ID) from the consent flow. Authentication is not required - this is part of the unauthenticated OAuth bootstrap flow. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} OAuth 2.1 token endpoint. Exchanges a single-use authorization code (5-minute TTL) for a Bifrost-issued access token (24-hour TTL) using PKCE verification. The request body must be `application/x-www-form-urlencoded`. The returned `access_token` is the Bearer token to use on subsequent `/mcp` requests. It carries the user's upstream service tokens (Notion, GitHub, etc.) linked to their identity (Virtual Key or User ID) from the consent flow. Authentication is not required - this is part of the unauthenticated OAuth bootstrap flow. --- # Consent identity selection page URL: /finops-api/per-user-oauth/getConsentIdentityPage *** title: Consent identity selection page full: true \_openapi: method: GET route: /oauth/consent toc: \[] structuredData: headings: \[] contents: * content: > Renders the identity selection screen where the user chooses how to identify themselves for the session: Virtual Key, User ID, or Skip (session-only auth). The `__bifrost_flow_secret` HttpOnly cookie set during `/api/oauth/per-user/authorize` must be present - it binds the consent flow to the initiating browser. The Skip option is only shown when `enforce_auth_on_inference` is `false` in config. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Renders the identity selection screen where the user chooses how to identify themselves for the session: Virtual Key, User ID, or Skip (session-only auth). The `__bifrost_flow_secret` HttpOnly cookie set during `/api/oauth/per-user/authorize` must be present - it binds the consent flow to the initiating browser. The Skip option is only shown when `enforce_auth_on_inference` is `false` in config. --- # Consent MCP services page URL: /finops-api/per-user-oauth/getConsentMCPsPage *** title: Consent MCP services page full: true \_openapi: method: GET route: /oauth/consent/mcps toc: \[] structuredData: headings: \[] contents: * content: > Renders the MCP services connection screen. Shows all per-user OAuth MCP servers available on the user's Virtual Key (or all servers if no VK was selected). Each service shows a "Connect" link or a "Connected ✓" badge. Requires the `__bifrost_flow_secret` browser-binding cookie. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Renders the MCP services connection screen. Shows all per-user OAuth MCP servers available on the user's Virtual Key (or all servers if no VK was selected). Each service shows a "Connect" link or a "Connected ✓" badge. Requires the `__bifrost_flow_secret` browser-binding cookie. --- # Authorization Server Metadata (RFC 8414) URL: /finops-api/per-user-oauth/getOAuthAuthorizationServerMetadata *** title: Authorization Server Metadata (RFC 8414) full: true \_openapi: method: GET route: /.well-known/oauth-authorization-server toc: \[] structuredData: headings: \[] contents: * content: > Returns the OAuth 2.0 Authorization Server Metadata document per RFC 8414\. After fetching the Protected Resource Metadata, MCP clients fetch this endpoint to discover Bifrost's OAuth endpoints (register, authorize, token) and capabilities (PKCE methods, grant types, etc.). Returns `404` when no MCP clients are configured with `auth_type: per_user_oauth`. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the OAuth 2.0 Authorization Server Metadata document per RFC 8414. After fetching the Protected Resource Metadata, MCP clients fetch this endpoint to discover Bifrost's OAuth endpoints (register, authorize, token) and capabilities (PKCE methods, grant types, etc.). Returns `404` when no MCP clients are configured with `auth_type: per_user_oauth`. --- # Protected Resource Metadata (RFC 9728) URL: /finops-api/per-user-oauth/getOAuthProtectedResourceMetadata *** title: Protected Resource Metadata (RFC 9728) full: true \_openapi: method: GET route: /.well-known/oauth-protected-resource toc: \[] structuredData: headings: \[] contents: * content: > Returns the OAuth 2.0 Protected Resource Metadata document per RFC 9728\. MCP clients fetch this after receiving a `401` response from `/mcp` (with a `WWW-Authenticate: Bearer resource_metadata=".../.well-known/oauth-protected-resource"` header). The response tells the client which authorization server(s) protect the `/mcp` resource so it can proceed with discovery. Returns `404` when no MCP clients are configured with `auth_type: per_user_oauth`. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the OAuth 2.0 Protected Resource Metadata document per RFC 9728. MCP clients fetch this after receiving a `401` response from `/mcp` (with a `WWW-Authenticate: Bearer resource_metadata=".../.well-known/oauth-protected-resource"` header). The response tells the client which authorization server(s) protect the `/mcp` resource so it can proceed with discovery. Returns `404` when no MCP clients are configured with `auth_type: per_user_oauth`. --- # Register OAuth client (RFC 7591) URL: /finops-api/per-user-oauth/registerPerUserOAuthClient *** title: Register OAuth client (RFC 7591) full: true \_openapi: method: POST route: /api/oauth/per-user/register toc: \[] structuredData: headings: \[] contents: * content: > Dynamic Client Registration per RFC 7591. MCP clients (Claude Code, Cursor, etc.) call this endpoint to obtain a `client_id` before initiating the authorization flow. This endpoint is only available when at least one MCP client is configured with `auth_type: per_user_oauth`. Returns `404` otherwise. Authentication is not required - this is part of the unauthenticated OAuth bootstrap flow. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Dynamic Client Registration per RFC 7591. MCP clients (Claude Code, Cursor, etc.) call this endpoint to obtain a `client_id` before initiating the authorization flow. This endpoint is only available when at least one MCP client is configured with `auth_type: per_user_oauth`. Returns `404` otherwise. Authentication is not required - this is part of the unauthenticated OAuth bootstrap flow. --- # Skip identity selection URL: /finops-api/per-user-oauth/skipConsentIdentity *** title: Skip identity selection full: true \_openapi: method: POST route: /api/oauth/per-user/consent/skip toc: \[] structuredData: headings: \[] contents: * content: > Skips identity selection and proceeds directly to the MCPs page. Upstream service tokens will be stored against the session token only (not a persistent identity), so they will not carry over to other sessions or the LLM Gateway. Only available when `enforce_auth_on_inference` is `false` in config. Returns a redirect back to the identity page with an error if auth enforcement is enabled. Request body is `application/x-www-form-urlencoded` (browser form submission). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Skips identity selection and proceeds directly to the MCPs page. Upstream service tokens will be stored against the session token only (not a persistent identity), so they will not carry over to other sessions or the LLM Gateway. Only available when `enforce_auth_on_inference` is `false` in config. Returns a redirect back to the identity page with an error if auth enforcement is enabled. Request body is `application/x-www-form-urlencoded` (browser form submission). --- # Finalize consent flow URL: /finops-api/per-user-oauth/submitConsent *** title: Finalize consent flow full: true \_openapi: method: POST route: /api/oauth/per-user/consent/submit toc: \[] structuredData: headings: \[] contents: * content: > Finalizes the consent flow atomically: 1. Creates a `TablePerUserOAuthSession` (24h Bifrost session token) 2. Transfers upstream tokens from the flow proxy to the session 3. Issues a single-use `TablePerUserOAuthCode` (5-minute TTL, PKCE-bound) 4. Deletes the `PendingFlow` 5. Redirects to the MCP client's `redirect_uri` with `code` and `state` The MCP client then exchanges the code at `/api/oauth/per-user/token`. Request body is `application/x-www-form-urlencoded` (browser form submission). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Finalizes the consent flow atomically: 1. Creates a `TablePerUserOAuthSession` (24h Bifrost session token) 2. Transfers upstream tokens from the flow proxy to the session 3. Issues a single-use `TablePerUserOAuthCode` (5-minute TTL, PKCE-bound) 4. Deletes the `PendingFlow` 5. Redirects to the MCP client's `redirect_uri` with `code` and `state` The MCP client then exchanges the code at `/api/oauth/per-user/token`. Request body is `application/x-www-form-urlencoded` (browser form submission). --- # Submit User ID identity URL: /finops-api/per-user-oauth/submitConsentUserID *** title: Submit User ID identity full: true \_openapi: method: POST route: /api/oauth/per-user/consent/user-id toc: \[] structuredData: headings: \[] contents: * content: > Links a self-declared User ID to the pending flow as the user's identity. On success, redirects to the MCPs page. The User ID is self-declared with no server-side verification - it matches the trust model of the `X-Bf-User-Id` header in the LLM Gateway path. Request body is `application/x-www-form-urlencoded` (browser form submission). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Links a self-declared User ID to the pending flow as the user's identity. On success, redirects to the MCPs page. The User ID is self-declared with no server-side verification - it matches the trust model of the `X-Bf-User-Id` header in the LLM Gateway path. Request body is `application/x-www-form-urlencoded` (browser form submission). --- # Submit Virtual Key identity URL: /finops-api/per-user-oauth/submitConsentVirtualKey *** title: Submit Virtual Key identity full: true \_openapi: method: POST route: /api/oauth/per-user/consent/vk toc: \[] structuredData: headings: \[] contents: * content: > Validates the submitted Virtual Key and links it to the pending flow as the user's identity. On success, redirects to the MCPs page. On failure, redirects back to the identity page with an error message. Request body is `application/x-www-form-urlencoded` (browser form submission). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Validates the submitted Virtual Key and links it to the pending flow as the user's identity. On success, redirects to the MCPs page. On failure, redirects back to the identity page with an error message. Request body is `application/x-www-form-urlencoded` (browser form submission). --- # Add a new provider URL: /finops-api/providers/addProvider *** title: Add a new provider full: true \_openapi: method: POST route: /api/providers toc: \[] structuredData: headings: \[] contents: * content: Adds a new provider with the specified configuration. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Adds a new provider with the specified configuration. --- # Create a key for a provider URL: /finops-api/providers/createProviderKey *** title: Create a key for a provider full: true \_openapi: method: POST route: /api/providers/{provider}/keys toc: \[] structuredData: headings: \[] contents: * content: > Creates a new API key for the specified provider. The key `id` is auto-generated if omitted. `enabled` defaults to `true` if omitted. `value` is required and must not be empty. Keys cannot be created on keyless providers. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new API key for the specified provider. The key `id` is auto-generated if omitted. `enabled` defaults to `true` if omitted. `value` is required and must not be empty. Keys cannot be created on keyless providers. --- # Delete a provider URL: /finops-api/providers/deleteProvider *** title: Delete a provider full: true \_openapi: method: DELETE route: /api/providers/{provider} toc: \[] structuredData: headings: \[] contents: * content: Removes a provider from the configuration. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Removes a provider from the configuration. --- # Delete a key from a provider URL: /finops-api/providers/deleteProviderKey *** title: Delete a key from a provider full: true \_openapi: method: DELETE route: /api/providers/{provider}/keys/{key_id} toc: \[] structuredData: headings: \[] contents: * content: Deletes a key from the specified provider. Returns the deleted key. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a key from the specified provider. Returns the deleted key. --- # Get model parameters URL: /finops-api/providers/getModelParameters *** title: Get model parameters full: true \_openapi: method: GET route: /api/models/parameters toc: \[] structuredData: headings: \[] contents: * content: Returns the available parameter definitions for models. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the available parameter definitions for models. --- # Get a specific provider URL: /finops-api/providers/getProvider *** title: Get a specific provider full: true \_openapi: method: GET route: /api/providers/{provider} toc: \[] structuredData: headings: \[] contents: * content: Returns the configuration for a specific provider. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the configuration for a specific provider. --- # Get a specific key for a provider URL: /finops-api/providers/getProviderKey *** title: Get a specific key for a provider full: true \_openapi: method: GET route: /api/providers/{provider}/keys/{key_id} toc: \[] structuredData: headings: \[] contents: * content: Returns a single key for the specified provider. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a single key for the specified provider. --- # List base models URL: /finops-api/providers/listBaseModels *** title: List base models full: true \_openapi: method: GET route: /api/models/base toc: \[] structuredData: headings: \[] contents: * content: Returns a list of base models from the model catalog. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of base models from the model catalog. --- # List all keys URL: /finops-api/providers/listKeys *** title: List all keys full: true \_openapi: method: GET route: /api/keys toc: \[] structuredData: headings: \[] contents: * content: Returns a list of all configured API keys across all providers. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of all configured API keys across all providers. --- # List model details URL: /finops-api/providers/listModelDetailsManagement *** title: List model details full: true \_openapi: method: GET route: /api/models/details toc: \[] structuredData: headings: \[] contents: * content: > Lists available models with capability metadata, when available from the model catalog, with optional filtering by query, provider, or keys. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models with capability metadata, when available from the model catalog, with optional filtering by query, provider, or keys. --- # List models URL: /finops-api/providers/listModelsManagement *** title: List models full: true \_openapi: method: GET route: /api/models toc: \[] structuredData: headings: \[] contents: * content: > Lists available models with optional filtering by query, provider, or keys. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models with optional filtering by query, provider, or keys. --- # List keys for a provider URL: /finops-api/providers/listProviderKeys *** title: List keys for a provider full: true \_openapi: method: GET route: /api/providers/{provider}/keys toc: \[] structuredData: headings: \[] contents: * content: Returns all keys configured for a specific provider. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns all keys configured for a specific provider. --- # List all providers URL: /finops-api/providers/listProviders *** title: List all providers full: true \_openapi: method: GET route: /api/providers toc: \[] structuredData: headings: \[] contents: * content: >- Returns a list of all configured providers with their configurations and status. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a list of all configured providers with their configurations and status. --- # Update a provider URL: /finops-api/providers/updateProvider *** title: Update a provider full: true \_openapi: method: PUT route: /api/providers/{provider} toc: \[] structuredData: headings: \[] contents: * content: > Updates a provider's configuration. Expects ALL fields to be provided, including both edited and non-edited fields. Partial updates are not supported. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates a provider's configuration. Expects ALL fields to be provided, including both edited and non-edited fields. Partial updates are not supported. --- # Update a key for a provider URL: /finops-api/providers/updateProviderKey *** title: Update a key for a provider full: true \_openapi: method: PUT route: /api/providers/{provider}/keys/{key_id} toc: \[] structuredData: headings: \[] contents: * content: > Updates an existing key. Send the full key object. Redacted values sent back unchanged are automatically preserved (the server merges them with the stored raw values). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates an existing key. Send the full key object. Redacted values sent back unchanged are automatically preserved (the server merges them with the stored raw values). --- # Create chat completion (Azure OpenAI) URL: /finops-api/openai-integration/azureCreateChatCompletion *** title: Create chat completion (Azure OpenAI) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/chat/completions toc: \[] structuredData: headings: \[] contents: * content: | Creates a chat completion using Azure OpenAI deployment. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a chat completion using Azure OpenAI deployment. --- # Create embeddings (Azure OpenAI) URL: /finops-api/openai-integration/azureCreateEmbedding *** title: Create embeddings (Azure OpenAI) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/embeddings toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Create image (Azure OpenAI) URL: /finops-api/openai-integration/azureCreateImage *** title: Create image (Azure OpenAI) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/images/generations toc: \[] structuredData: headings: \[] contents: * content: | Generates images from text prompts using Azure OpenAI deployment. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates images from text prompts using Azure OpenAI deployment. --- # Create response (Azure OpenAI) URL: /finops-api/openai-integration/azureCreateResponse *** title: Create response (Azure OpenAI) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/responses toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Create speech (Azure OpenAI TTS) URL: /finops-api/openai-integration/azureCreateSpeech *** title: Create speech (Azure OpenAI TTS) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/audio/speech toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Create text completion (Azure OpenAI) URL: /finops-api/openai-integration/azureCreateTextCompletion *** title: Create text completion (Azure OpenAI) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/completions toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Create transcription (Azure OpenAI) URL: /finops-api/openai-integration/azureCreateTranscription *** title: Create transcription (Azure OpenAI) full: true \_openapi: method: POST route: /openai/openai/deployments/{deployment-id}/audio/transcriptions toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # List models (Azure OpenAI) URL: /finops-api/openai-integration/azureListModels *** title: List models (Azure OpenAI) full: true \_openapi: method: GET route: /openai/openai/deployments/{deployment-id}/models toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # Cancel batch job (OpenAI format) URL: /finops-api/openai-integration/openaiCancelBatch *** title: Cancel batch job (OpenAI format) full: true \_openapi: method: POST route: /openai/v1/batches/{batch_id}/cancel toc: \[] structuredData: headings: \[] contents: * content: > Cancels a batch processing job. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/batches/{batch_id}/cancel`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Cancels a batch processing job. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/batches/{batch_id}/cancel`). --- # Count input tokens URL: /finops-api/openai-integration/openaiCountInputTokens *** title: Count input tokens full: true \_openapi: method: POST route: /openai/v1/responses/input\_tokens toc: \[] structuredData: headings: \[] contents: * content: | Counts the number of tokens in a Responses API request. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Counts the number of tokens in a Responses API request. --- # Create batch job (OpenAI format) URL: /finops-api/openai-integration/openaiCreateBatch *** title: Create batch job (OpenAI format) full: true \_openapi: method: POST route: /openai/v1/batches toc: \[] structuredData: headings: \[] contents: * content: > Creates a batch processing job. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/batches`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a batch processing job. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/batches`). --- # Create chat completion (OpenAI format) URL: /finops-api/openai-integration/openaiCreateChatCompletion *** title: Create chat completion (OpenAI format) full: true \_openapi: method: POST route: /openai/v1/chat/completions toc: \[] structuredData: headings: \[] contents: * content: > Creates a chat completion using OpenAI-compatible format. Supports streaming via SSE. **Async inference:** Send `x-bf-async: true` to submit the request as a background job and receive a job ID immediately. Poll with `x-bf-async-id: ` to retrieve the result. When the job is still processing, the response will have an empty `choices` array. When completed, `choices` will contain the full result. See [Async Inference](/features/async-inference) for details. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/chat/completions`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a chat completion using OpenAI-compatible format. Supports streaming via SSE. **Async inference:** Send `x-bf-async: true` to submit the request as a background job and receive a job ID immediately. Poll with `x-bf-async-id: ` to retrieve the result. When the job is still processing, the response will have an empty `choices` array. When completed, `choices` will contain the full result. See [Async Inference](/features/async-inference) for details. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/chat/completions`). --- # Create container (OpenAI format) URL: /finops-api/openai-integration/openaiCreateContainer *** title: Create container (OpenAI format) full: true \_openapi: method: POST route: /openai/v1/containers toc: \[] structuredData: headings: \[] contents: * content: > Creates a new container for storing files and data. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new container for storing files and data. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers`). --- # Create file in container (OpenAI format) URL: /finops-api/openai-integration/openaiCreateContainerFile *** title: Create file in container (OpenAI format) full: true \_openapi: method: POST route: /openai/v1/containers/{container_id}/files toc: \[] structuredData: headings: \[] contents: * content: > Creates a new file in a container. You can either upload file content directly via multipart/form-data or reference an existing file by its ID. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}/files`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new file in a container. You can either upload file content directly via multipart/form-data or reference an existing file by its ID. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}/files`). --- # Create embeddings (OpenAI format) URL: /finops-api/openai-integration/openaiCreateEmbedding *** title: Create embeddings (OpenAI format) full: true \_openapi: method: POST route: /openai/v1/embeddings toc: \[] structuredData: headings: \[] contents: * content: > Creates embedding vectors for the input text. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/embeddings`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates embedding vectors for the input text. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/embeddings`). --- # Create image URL: /finops-api/openai-integration/openaiCreateImage *** title: Create image full: true \_openapi: method: POST route: /openai/v1/images/generations toc: \[] structuredData: headings: \[] contents: * content: > Generates images from text prompts using OpenAI-compatible format. **Note:** Azure OpenAI deployments are also supported via the Azure integration endpoint. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/images/generations`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates images from text prompts using OpenAI-compatible format. **Note:** Azure OpenAI deployments are also supported via the Azure integration endpoint. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/images/generations`). --- # Create response (OpenAI Responses API) URL: /finops-api/openai-integration/openaiCreateResponse *** title: Create response (OpenAI Responses API) full: true \_openapi: method: POST route: /openai/v1/responses toc: \[] structuredData: headings: \[] contents: * content: > Creates a response using OpenAI Responses API format. Supports streaming via SSE. **Async inference:** Send `x-bf-async: true` to submit the request as a background job and receive a job ID immediately. Poll with `x-bf-async-id: ` to retrieve the result. When the job is still processing, the response `status` will not be `completed`. When completed, the full response with `output_text` will be returned. See [Async Inference](/features/async-inference) for details. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/responses`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a response using OpenAI Responses API format. Supports streaming via SSE. **Async inference:** Send `x-bf-async: true` to submit the request as a background job and receive a job ID immediately. Poll with `x-bf-async-id: ` to retrieve the result. When the job is still processing, the response `status` will not be `completed`. When completed, the full response with `output_text` will be returned. See [Async Inference](/features/async-inference) for details. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/responses`). --- # Create speech (OpenAI TTS) URL: /finops-api/openai-integration/openaiCreateSpeech *** title: Create speech (OpenAI TTS) full: true \_openapi: method: POST route: /openai/v1/audio/speech toc: \[] structuredData: headings: \[] contents: * content: > Generates audio from text using OpenAI TTS. Supports streaming via SSE when stream\_format is set to 'sse'. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/audio/speech`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates audio from text using OpenAI TTS. Supports streaming via SSE when stream\_format is set to 'sse'. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/audio/speech`). --- # Create text completion (OpenAI format) URL: /finops-api/openai-integration/openaiCreateTextCompletion *** title: Create text completion (OpenAI format) full: true \_openapi: method: POST route: /openai/v1/completions toc: \[] structuredData: headings: \[] contents: * content: > Creates a text completion using OpenAI-compatible format. This is the legacy completions API. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/completions`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a text completion using OpenAI-compatible format. This is the legacy completions API. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/completions`). --- # Create transcription (OpenAI Whisper) URL: /finops-api/openai-integration/openaiCreateTranscription *** title: Create transcription (OpenAI Whisper) full: true \_openapi: method: POST route: /openai/v1/audio/transcriptions toc: \[] structuredData: headings: \[] contents: * content: > Transcribes audio into text using OpenAI Whisper. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/audio/transcriptions`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Transcribes audio into text using OpenAI Whisper. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/audio/transcriptions`). --- # Create a video generation URL: /finops-api/openai-integration/openaiCreateVideo *** title: Create a video generation full: true \_openapi: method: POST route: /openai/v1/videos toc: \[] structuredData: headings: \[] contents: * content: | Submits a video generation job using OpenAI's Videos API. The request is multipart/form-data and may include reference images. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Submits a video generation job using OpenAI's Videos API. The request is multipart/form-data and may include reference images. --- # Delete container (OpenAI format) URL: /finops-api/openai-integration/openaiDeleteContainer *** title: Delete container (OpenAI format) full: true \_openapi: method: DELETE route: /openai/v1/containers/{container_id} toc: \[] structuredData: headings: \[] contents: * content: > Deletes a container. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a container. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}`). --- # Delete file from container (OpenAI format) URL: /finops-api/openai-integration/openaiDeleteContainerFile *** title: Delete file from container (OpenAI format) full: true \_openapi: method: DELETE route: /openai/v1/containers/{container_id}/files/{file_id} toc: \[] structuredData: headings: \[] contents: * content: > Deletes a file from a container. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}/files/{file_id}`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a file from a container. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}/files/{file_id}`). --- # Delete file (OpenAI format) URL: /finops-api/openai-integration/openaiDeleteFile *** title: Delete file (OpenAI format) full: true \_openapi: method: DELETE route: /openai/v1/files/{file_id} toc: \[] structuredData: headings: \[] contents: * content: > Deletes an uploaded file. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/files/{file_id}`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes an uploaded file. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/files/{file_id}`). --- # Delete a video generation URL: /finops-api/openai-integration/openaiDeleteVideo *** title: Delete a video generation full: true \_openapi: method: DELETE route: /openai/v1/videos/{video_id} toc: \[] structuredData: headings: \[] contents: * content: Deletes a previously generated video. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a previously generated video. --- # Download generated video content URL: /finops-api/openai-integration/openaiDownloadVideo *** title: Download generated video content full: true \_openapi: method: GET route: /openai/v1/videos/{video_id}/content toc: \[] structuredData: headings: \[] contents: * content: Streams the binary video bytes for a completed generation job. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Streams the binary video bytes for a completed generation job. --- # Get file content from container (OpenAI format) URL: /finops-api/openai-integration/openaiGetContainerFileContent *** title: Get file content from container (OpenAI format) full: true \_openapi: method: GET route: /openai/v1/containers/{container_id}/files/{file_id}/content toc: \[] structuredData: headings: \[] contents: * content: > Downloads the content of a file from a container. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}/files/{file_id}/content`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Downloads the content of a file from a container. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}/files/{file_id}/content`). --- # Get file content (OpenAI format) URL: /finops-api/openai-integration/openaiGetFileContent *** title: Get file content (OpenAI format) full: true \_openapi: method: GET route: /openai/v1/files/{file_id}/content toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the content of an uploaded file. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/files/{file_id}/content`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the content of an uploaded file. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/files/{file_id}/content`). --- # List batch jobs (OpenAI format) URL: /finops-api/openai-integration/openaiListBatches *** title: List batch jobs (OpenAI format) full: true \_openapi: method: GET route: /openai/v1/batches toc: \[] structuredData: headings: \[] contents: * content: > Lists batch processing jobs. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/batches`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists batch processing jobs. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/batches`). --- # List files in container (OpenAI format) URL: /finops-api/openai-integration/openaiListContainerFiles *** title: List files in container (OpenAI format) full: true \_openapi: method: GET route: /openai/v1/containers/{container_id}/files toc: \[] structuredData: headings: \[] contents: * content: > Lists all files in a container. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}/files`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists all files in a container. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}/files`). --- # List containers (OpenAI format) URL: /finops-api/openai-integration/openaiListContainers *** title: List containers (OpenAI format) full: true \_openapi: method: GET route: /openai/v1/containers toc: \[] structuredData: headings: \[] contents: * content: > Lists containers for a provider. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists containers for a provider. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers`). --- # List files (OpenAI format) URL: /finops-api/openai-integration/openaiListFiles *** title: List files (OpenAI format) full: true \_openapi: method: GET route: /openai/v1/files toc: \[] structuredData: headings: \[] contents: * content: > Lists uploaded files. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/files`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists uploaded files. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/files`). --- # List models (OpenAI format) URL: /finops-api/openai-integration/openaiListModels *** title: List models (OpenAI format) full: true \_openapi: method: GET route: /openai/v1/models toc: \[] structuredData: headings: \[] contents: * content: > Lists available models in OpenAI format. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/models`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models in OpenAI format. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/models`). --- # List video generations URL: /finops-api/openai-integration/openaiListVideos *** title: List video generations full: true \_openapi: method: GET route: /openai/v1/videos toc: \[] structuredData: headings: \[] contents: * content: Lists previously submitted video generation jobs. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists previously submitted video generation jobs. --- # WebRTC Realtime SDP exchange (OpenAI alias) URL: /finops-api/openai-integration/openaiRealtimeCall *** title: WebRTC Realtime SDP exchange (OpenAI alias) full: true \_openapi: method: POST route: /openai/v1/realtime/calls toc: \[] structuredData: headings: \[] contents: * content: > OpenAI-prefixed alias of `POST /v1/realtime/calls`. Performs the WebRTC SDP exchange for OpenAI Realtime calls. Accepts either multipart form data with `sdp` + `session` parts (GA) or a raw SDP body (legacy). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} OpenAI-prefixed alias of `POST /v1/realtime/calls`. Performs the WebRTC SDP exchange for OpenAI Realtime calls. Accepts either multipart form data with `sdp` + `session` parts (GA) or a raw SDP body (legacy). --- # Create realtime client secret (OpenAI alias) URL: /finops-api/openai-integration/openaiRealtimeClientSecret *** title: Create realtime client secret (OpenAI alias) full: true \_openapi: method: POST route: /openai/v1/realtime/client\_secrets toc: \[] structuredData: headings: \[] contents: * content: > OpenAI-prefixed alias of `POST /v1/realtime/client_secrets`. Mints an ephemeral client secret used to authorize a downstream Realtime client. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} OpenAI-prefixed alias of `POST /v1/realtime/client_secrets`. Mints an ephemeral client secret used to authorize a downstream Realtime client. --- # Create realtime session (OpenAI alias) URL: /finops-api/openai-integration/openaiRealtimeSession *** title: Create realtime session (OpenAI alias) full: true \_openapi: method: POST route: /openai/v1/realtime/sessions toc: \[] structuredData: headings: \[] contents: * content: | OpenAI-prefixed alias of `POST /v1/realtime/sessions`. Creates a pre-configured realtime session that can be joined by clients. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} OpenAI-prefixed alias of `POST /v1/realtime/sessions`. Creates a pre-configured realtime session that can be joined by clients. --- # WebSocket Realtime (OpenAI alias) URL: /finops-api/openai-integration/openaiRealtimeWebSocket *** title: WebSocket Realtime (OpenAI alias) full: true \_openapi: method: GET route: /openai/v1/realtime toc: \[] structuredData: headings: \[] contents: * content: > OpenAI-prefixed alias of `GET /v1/realtime`. WebSocket upgrade endpoint for OpenAI Realtime; selects the model via the `model` query parameter (Azure GA) or `deployment` (preview). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} OpenAI-prefixed alias of `GET /v1/realtime`. WebSocket upgrade endpoint for OpenAI Realtime; selects the model via the `model` query parameter (Azure GA) or `deployment` (preview). --- # Remix an existing video URL: /finops-api/openai-integration/openaiRemixVideo *** title: Remix an existing video full: true \_openapi: method: POST route: /openai/v1/videos/{video_id}/remix toc: \[] structuredData: headings: \[] contents: * content: >- Creates a new generation by remixing a prior video with new prompt parameters. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new generation by remixing a prior video with new prompt parameters. --- # WebSocket Responses (OpenAI alias) URL: /finops-api/openai-integration/openaiResponsesWebSocket *** title: WebSocket Responses (OpenAI alias) full: true \_openapi: method: GET route: /openai/v1/responses toc: \[] structuredData: headings: \[] contents: * content: > WebSocket upgrade endpoint for the Responses API. Mirrors the canonical `GET /v1/responses` WS endpoint; the OpenAI-prefixed path is selected when the request includes an `Upgrade: websocket` header. Authentication accepts the same headers as the inference HTTP surface plus the `openai-insecure-api-key.` subprotocol fallback. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} WebSocket upgrade endpoint for the Responses API. Mirrors the canonical `GET /v1/responses` WS endpoint; the OpenAI-prefixed path is selected when the request includes an `Upgrade: websocket` header. Authentication accepts the same headers as the inference HTTP surface plus the `openai-insecure-api-key.` subprotocol fallback. --- # Retrieve batch job (OpenAI format) URL: /finops-api/openai-integration/openaiRetrieveBatch *** title: Retrieve batch job (OpenAI format) full: true \_openapi: method: GET route: /openai/v1/batches/{batch_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves details of a batch processing job. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/batches/{batch_id}`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves details of a batch processing job. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/batches/{batch_id}`). --- # Retrieve container (OpenAI format) URL: /finops-api/openai-integration/openaiRetrieveContainer *** title: Retrieve container (OpenAI format) full: true \_openapi: method: GET route: /openai/v1/containers/{container_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves a specific container by ID. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves a specific container by ID. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}`). --- # Retrieve file from container (OpenAI format) URL: /finops-api/openai-integration/openaiRetrieveContainerFile *** title: Retrieve file from container (OpenAI format) full: true \_openapi: method: GET route: /openai/v1/containers/{container_id}/files/{file_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves metadata for a specific file in a container. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}/files/{file_id}`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves metadata for a specific file in a container. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/containers/{container_id}/files/{file_id}`). --- # Retrieve file metadata (OpenAI format) URL: /finops-api/openai-integration/openaiRetrieveFile *** title: Retrieve file metadata (OpenAI format) full: true \_openapi: method: GET route: /openai/v1/files/{file_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves metadata for an uploaded file. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/files/{file_id}`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves metadata for an uploaded file. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/files/{file_id}`). --- # Retrieve a video generation URL: /finops-api/openai-integration/openaiRetrieveVideo *** title: Retrieve a video generation full: true \_openapi: method: GET route: /openai/v1/videos/{video_id} toc: \[] structuredData: headings: \[] contents: * content: Returns metadata for a previously submitted video generation job. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns metadata for a previously submitted video generation job. --- # Upload file (OpenAI format) URL: /finops-api/openai-integration/openaiUploadFile *** title: Upload file (OpenAI format) full: true \_openapi: method: POST route: /openai/v1/files toc: \[] structuredData: headings: \[] contents: * content: > Uploads a file for use with batch processing or other features. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/files`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Uploads a file for use with batch processing or other features. **Note:** This endpoint also works without the `/v1` prefix (e.g., `/openai/files`). --- # Commit session as version URL: /finops-api/prompt-repository/commitPromptSession *** title: Commit session as version full: true \_openapi: method: POST route: /api/prompt-repo/sessions/{id}/commit toc: \[] structuredData: headings: \[] contents: * content: Commits the current session state as a new prompt version. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Commits the current session state as a new prompt version. --- # Create folder URL: /finops-api/prompt-repository/createFolder *** title: Create folder full: true \_openapi: method: POST route: /api/prompt-repo/folders toc: \[] structuredData: headings: \[] contents: * content: Creates a new prompt folder. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new prompt folder. --- # Create prompt URL: /finops-api/prompt-repository/createPrompt *** title: Create prompt full: true \_openapi: method: POST route: /api/prompt-repo/prompts toc: \[] structuredData: headings: \[] contents: * content: Creates a new prompt. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new prompt. --- # Create prompt session URL: /finops-api/prompt-repository/createPromptSession *** title: Create prompt session full: true \_openapi: method: POST route: /api/prompt-repo/prompts/{id}/sessions toc: \[] structuredData: headings: \[] contents: * content: Creates a new playground session for a prompt. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new playground session for a prompt. --- # Create prompt version URL: /finops-api/prompt-repository/createPromptVersion *** title: Create prompt version full: true \_openapi: method: POST route: /api/prompt-repo/prompts/{id}/versions toc: \[] structuredData: headings: \[] contents: * content: Creates a new version for a prompt. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new version for a prompt. --- # Delete folder URL: /finops-api/prompt-repository/deleteFolder *** title: Delete folder full: true \_openapi: method: DELETE route: /api/prompt-repo/folders/{id} toc: \[] structuredData: headings: \[] contents: * content: Deletes a folder and cascades to contained prompts. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a folder and cascades to contained prompts. --- # Delete prompt URL: /finops-api/prompt-repository/deletePrompt *** title: Delete prompt full: true \_openapi: method: DELETE route: /api/prompt-repo/prompts/{id} toc: \[] structuredData: headings: \[] contents: * content: Deletes a prompt and all its versions and sessions. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a prompt and all its versions and sessions. --- # Delete prompt session URL: /finops-api/prompt-repository/deletePromptSession *** title: Delete prompt session full: true \_openapi: method: DELETE route: /api/prompt-repo/sessions/{id} toc: \[] structuredData: headings: \[] contents: * content: Deletes a specific session. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a specific session. --- # Delete prompt version URL: /finops-api/prompt-repository/deletePromptVersion *** title: Delete prompt version full: true \_openapi: method: DELETE route: /api/prompt-repo/versions/{id} toc: \[] structuredData: headings: \[] contents: * content: Deletes a specific version. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a specific version. --- # Get folder URL: /finops-api/prompt-repository/getFolder *** title: Get folder full: true \_openapi: method: GET route: /api/prompt-repo/folders/{id} toc: \[] structuredData: headings: \[] contents: * content: Returns a folder by ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a folder by ID. --- # Get prompt URL: /finops-api/prompt-repository/getPrompt *** title: Get prompt full: true \_openapi: method: GET route: /api/prompt-repo/prompts/{id} toc: \[] structuredData: headings: \[] contents: * content: Returns a prompt by ID with its latest version. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a prompt by ID with its latest version. --- # Get prompt session URL: /finops-api/prompt-repository/getPromptSession *** title: Get prompt session full: true \_openapi: method: GET route: /api/prompt-repo/sessions/{id} toc: \[] structuredData: headings: \[] contents: * content: Returns a specific session by ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a specific session by ID. --- # Get prompt version URL: /finops-api/prompt-repository/getPromptVersion *** title: Get prompt version full: true \_openapi: method: GET route: /api/prompt-repo/versions/{id} toc: \[] structuredData: headings: \[] contents: * content: Returns a specific version by ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a specific version by ID. --- # List folders URL: /finops-api/prompt-repository/listFolders *** title: List folders full: true \_openapi: method: GET route: /api/prompt-repo/folders toc: \[] structuredData: headings: \[] contents: * content: Returns all prompt folders. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns all prompt folders. --- # List prompt sessions URL: /finops-api/prompt-repository/listPromptSessions *** title: List prompt sessions full: true \_openapi: method: GET route: /api/prompt-repo/prompts/{id}/sessions toc: \[] structuredData: headings: \[] contents: * content: Returns all sessions for a prompt. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns all sessions for a prompt. --- # List prompt versions URL: /finops-api/prompt-repository/listPromptVersions *** title: List prompt versions full: true \_openapi: method: GET route: /api/prompt-repo/prompts/{id}/versions toc: \[] structuredData: headings: \[] contents: * content: Returns all versions for a prompt. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns all versions for a prompt. --- # List prompts URL: /finops-api/prompt-repository/listPrompts *** title: List prompts full: true \_openapi: method: GET route: /api/prompt-repo/prompts toc: \[] structuredData: headings: \[] contents: * content: Returns all prompts, optionally filtered by folder. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns all prompts, optionally filtered by folder. --- # Rename prompt session URL: /finops-api/prompt-repository/renamePromptSession *** title: Rename prompt session full: true \_openapi: method: PUT route: /api/prompt-repo/sessions/{id}/rename toc: \[] structuredData: headings: \[] contents: * content: Renames a session. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Renames a session. --- # Update folder URL: /finops-api/prompt-repository/updateFolder *** title: Update folder full: true \_openapi: method: PUT route: /api/prompt-repo/folders/{id} toc: \[] structuredData: headings: \[] contents: * content: Updates a folder's name or description. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates a folder's name or description. --- # Update prompt URL: /finops-api/prompt-repository/updatePrompt *** title: Update prompt full: true \_openapi: method: PUT route: /api/prompt-repo/prompts/{id} toc: \[] structuredData: headings: \[] contents: * content: Updates a prompt's name or folder. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates a prompt's name or folder. --- # Update prompt session URL: /finops-api/prompt-repository/updatePromptSession *** title: Update prompt session full: true \_openapi: method: PUT route: /api/prompt-repo/sessions/{id} toc: \[] structuredData: headings: \[] contents: * content: Updates a session's messages, model params, etc. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates a session's messages, model params, etc. --- # Create role URL: /finops-api/rbac/createRole *** title: Create role full: true \_openapi: method: POST route: /api/roles toc: \[] structuredData: headings: \[] contents: * content: | Creates a custom role with the specified data access control scope. If `dac` is omitted, defaults to `all-data`. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a custom role with the specified data access control scope. If `dac` is omitted, defaults to `all-data`. --- # Delete role URL: /finops-api/rbac/deleteRole *** title: Delete role full: true \_openapi: method: DELETE route: /api/roles/{id} toc: \[] structuredData: headings: \[] contents: * content: > Deletes a custom role. Built-in system roles cannot be deleted and return 403. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a custom role. Built-in system roles cannot be deleted and return 403. --- # Get role by ID URL: /finops-api/rbac/getRole *** title: Get role by ID full: true \_openapi: method: GET route: /api/roles/{id} toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # List permissions assigned to a role URL: /finops-api/rbac/getRolePermissions *** title: List permissions assigned to a role full: true \_openapi: method: GET route: /api/roles/{id}/permissions toc: \[] structuredData: headings: \[] contents: \[] ------------- {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} --- # List RBAC operations URL: /finops-api/rbac/listOperations *** title: List RBAC operations full: true \_openapi: method: GET route: /api/operations toc: \[] structuredData: headings: \[] contents: * content: Returns the set of operation names that permissions can grant. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the set of operation names that permissions can grant. --- # List all RBAC permissions URL: /finops-api/rbac/listPermissions *** title: List all RBAC permissions full: true \_openapi: method: GET route: /api/permissions toc: \[] structuredData: headings: \[] contents: * content: >- Returns every (resource, operation) pair that can be granted to a role. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns every (resource, operation) pair that can be granted to a role. --- # List RBAC resources URL: /finops-api/rbac/listResources *** title: List RBAC resources full: true \_openapi: method: GET route: /api/resources toc: \[] structuredData: headings: \[] contents: * content: Returns the set of resource names that permissions can target. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the set of resource names that permissions can target. --- # List roles URL: /finops-api/rbac/listRoles *** title: List roles full: true \_openapi: method: GET route: /api/roles toc: \[] structuredData: headings: \[] contents: * content: >- Returns all roles visible to the caller, scoped by data access control. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns all roles visible to the caller, scoped by data access control. --- # Update role URL: /finops-api/rbac/updateRole *** title: Update role full: true \_openapi: method: PUT route: /api/roles/{id} toc: \[] structuredData: headings: \[] contents: * content: > Partial update. Omitted fields preserve the current value. Notable: omitting `dac` preserves the current scope (does not default to `all-data`). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Partial update. Omitted fields preserve the current value. Notable: omitting `dac` preserves the current scope (does not default to `all-data`). --- # Replace the permission set on a role URL: /finops-api/rbac/updateRolePermissions *** title: Replace the permission set on a role full: true \_openapi: method: PUT route: /api/roles/{id}/permissions toc: \[] structuredData: headings: \[] contents: * content: > Replaces the permission set assigned to the role. Send the complete list of permission IDs that should be active for the role. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Replaces the permission set assigned to the role. Send the complete list of permission IDs that should be active for the role. --- # Create message (PydanticAI - Anthropic format) URL: /finops-api/pydanticai-integration/pydanticaiAnthropicMessages *** title: Create message (PydanticAI - Anthropic format) full: true \_openapi: method: POST route: /pydanticai/anthropic/v1/messages toc: \[] structuredData: headings: \[] contents: * content: | Creates a message using Anthropic-compatible format via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a message using Anthropic-compatible format via PydanticAI. --- # Converse with model (PydanticAI - Bedrock format) URL: /finops-api/pydanticai-integration/pydanticaiBedrockConverse *** title: Converse with model (PydanticAI - Bedrock format) full: true \_openapi: method: POST route: /pydanticai/bedrock/model/{modelId}/converse toc: \[] structuredData: headings: \[] contents: * content: > Sends messages using AWS Bedrock Converse-compatible format via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Sends messages using AWS Bedrock Converse-compatible format via PydanticAI. --- # Stream converse with model (PydanticAI - Bedrock format) URL: /finops-api/pydanticai-integration/pydanticaiBedrockConverseStream *** title: Stream converse with model (PydanticAI - Bedrock format) full: true \_openapi: method: POST route: /pydanticai/bedrock/model/{modelId}/converse-stream toc: \[] structuredData: headings: \[] contents: * content: > Streams messages using AWS Bedrock Converse-compatible format via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Streams messages using AWS Bedrock Converse-compatible format via PydanticAI. --- # Chat with model (PydanticAI - Cohere format) URL: /finops-api/pydanticai-integration/pydanticaiCohereChat *** title: Chat with model (PydanticAI - Cohere format) full: true \_openapi: method: POST route: /pydanticai/cohere/v2/chat toc: \[] structuredData: headings: \[] contents: * content: | Sends a chat request using Cohere-compatible format via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Sends a chat request using Cohere-compatible format via PydanticAI. --- # Create embeddings (PydanticAI - Cohere format) URL: /finops-api/pydanticai-integration/pydanticaiCohereEmbed *** title: Create embeddings (PydanticAI - Cohere format) full: true \_openapi: method: POST route: /pydanticai/cohere/v2/embed toc: \[] structuredData: headings: \[] contents: * content: | Creates embeddings using Cohere-compatible format via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates embeddings using Cohere-compatible format via PydanticAI. --- # Tokenize text (PydanticAI - Cohere format) URL: /finops-api/pydanticai-integration/pydanticaiCohereTokenize *** title: Tokenize text (PydanticAI - Cohere format) full: true \_openapi: method: POST route: /pydanticai/cohere/v1/tokenize toc: \[] structuredData: headings: \[] contents: * content: | Tokenizes text using Cohere v1 API format via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Tokenizes text using Cohere v1 API format via PydanticAI. --- # Generate content (PydanticAI - Gemini format) URL: /finops-api/pydanticai-integration/pydanticaiGeminiGenerateContent *** title: Generate content (PydanticAI - Gemini format) full: true \_openapi: method: POST route: /pydanticai/genai/v1beta/models/{model}:generateContent toc: \[] structuredData: headings: \[] contents: * content: > Generates content using Google Gemini-compatible format via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates content using Google Gemini-compatible format via PydanticAI. --- # List models (PydanticAI - Gemini format) URL: /finops-api/pydanticai-integration/pydanticaiGeminiListModels *** title: List models (PydanticAI - Gemini format) full: true \_openapi: method: GET route: /pydanticai/genai/v1beta/models toc: \[] structuredData: headings: \[] contents: * content: | Lists available models in Google Gemini API format via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models in Google Gemini API format via PydanticAI. --- # Stream generate content (PydanticAI - Gemini format) URL: /finops-api/pydanticai-integration/pydanticaiGeminiStreamGenerateContent *** title: Stream generate content (PydanticAI - Gemini format) full: true \_openapi: method: POST route: /pydanticai/genai/v1beta/models/{model}:streamGenerateContent toc: \[] structuredData: headings: \[] contents: * content: > Streams content generation using Google Gemini-compatible format via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Streams content generation using Google Gemini-compatible format via PydanticAI. --- # Chat completions (PydanticAI - OpenAI format) URL: /finops-api/pydanticai-integration/pydanticaiOpenAIChatCompletions *** title: Chat completions (PydanticAI - OpenAI format) full: true \_openapi: method: POST route: /pydanticai/v1/chat/completions toc: \[] structuredData: headings: \[] contents: * content: > Creates a chat completion using OpenAI-compatible format via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a chat completion using OpenAI-compatible format via PydanticAI. --- # Count input tokens (PydanticAI - OpenAI format) URL: /finops-api/pydanticai-integration/pydanticaiOpenAICountInputTokens *** title: Count input tokens (PydanticAI - OpenAI format) full: true \_openapi: method: POST route: /pydanticai/v1/responses/input\_tokens toc: \[] structuredData: headings: \[] contents: * content: | Counts the number of tokens in a Responses API request via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Counts the number of tokens in a Responses API request via PydanticAI. --- # Create embeddings (PydanticAI - OpenAI format) URL: /finops-api/pydanticai-integration/pydanticaiOpenAIEmbeddings *** title: Create embeddings (PydanticAI - OpenAI format) full: true \_openapi: method: POST route: /pydanticai/v1/embeddings toc: \[] structuredData: headings: \[] contents: * content: | Creates embeddings using OpenAI-compatible format via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates embeddings using OpenAI-compatible format via PydanticAI. --- # List models (PydanticAI - OpenAI format) URL: /finops-api/pydanticai-integration/pydanticaiOpenAIListModels *** title: List models (PydanticAI - OpenAI format) full: true \_openapi: method: GET route: /pydanticai/v1/models toc: \[] structuredData: headings: \[] contents: * content: | Lists available models using OpenAI-compatible format via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists available models using OpenAI-compatible format via PydanticAI. --- # Create response (PydanticAI - OpenAI Responses API) URL: /finops-api/pydanticai-integration/pydanticaiOpenAIResponses *** title: Create response (PydanticAI - OpenAI Responses API) full: true \_openapi: method: POST route: /pydanticai/v1/responses toc: \[] structuredData: headings: \[] contents: * content: | Creates a response using OpenAI Responses API format via PydanticAI. Supports streaming via SSE. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a response using OpenAI Responses API format via PydanticAI. Supports streaming via SSE. --- # Create speech (PydanticAI - OpenAI TTS) URL: /finops-api/pydanticai-integration/pydanticaiOpenAISpeech *** title: Create speech (PydanticAI - OpenAI TTS) full: true \_openapi: method: POST route: /pydanticai/v1/audio/speech toc: \[] structuredData: headings: \[] contents: * content: | Generates audio from text using OpenAI TTS via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Generates audio from text using OpenAI TTS via PydanticAI. --- # Text completions (PydanticAI - OpenAI format) URL: /finops-api/pydanticai-integration/pydanticaiOpenAITextCompletions *** title: Text completions (PydanticAI - OpenAI format) full: true \_openapi: method: POST route: /pydanticai/v1/completions toc: \[] structuredData: headings: \[] contents: * content: > Creates a text completion using OpenAI-compatible format via PydanticAI. This is the legacy completions API. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a text completion using OpenAI-compatible format via PydanticAI. This is the legacy completions API. --- # Create transcription (PydanticAI - OpenAI Whisper) URL: /finops-api/pydanticai-integration/pydanticaiOpenAITranscriptions *** title: Create transcription (PydanticAI - OpenAI Whisper) full: true \_openapi: method: POST route: /pydanticai/v1/audio/transcriptions toc: \[] structuredData: headings: \[] contents: * content: | Transcribes audio into text using OpenAI Whisper via PydanticAI. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Transcribes audio into text using OpenAI Whisper via PydanticAI. --- # Realtime API WebSocket URL: /finops-api/realtime/connectRealtime *** title: Realtime API WebSocket full: true \_openapi: method: GET route: /v1/realtime toc: \[] structuredData: headings: \[] contents: * content: > Opens a bidirectional WebSocket session to a realtime-capable provider (e.g. OpenAI Realtime, Azure Realtime preview). Bifrost proxies the upstream socket and applies governance, observability, and key selection on connect. The target model is provided via the `model` query parameter (or `deployment` for Azure-style routes). The OpenAI SDK sends the API key over the `openai-insecure-api-key.` WebSocket subprotocol; Bifrost extracts it and treats it the same as a Bearer header. Inference auth applies — Bearer/Basic/Virtual Key/API Key headers are all accepted, plus the subprotocol form above. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Opens a bidirectional WebSocket session to a realtime-capable provider (e.g. OpenAI Realtime, Azure Realtime preview). Bifrost proxies the upstream socket and applies governance, observability, and key selection on connect. The target model is provided via the `model` query parameter (or `deployment` for Azure-style routes). The OpenAI SDK sends the API key over the `openai-insecure-api-key.` WebSocket subprotocol; Bifrost extracts it and treats it the same as a Bearer header. Inference auth applies — Bearer/Basic/Virtual Key/API Key headers are all accepted, plus the subprotocol form above. --- # Realtime WebRTC SDP exchange URL: /finops-api/realtime/createRealtimeCall *** title: Realtime WebRTC SDP exchange full: true \_openapi: method: POST route: /v1/realtime/calls toc: \[] structuredData: headings: \[] contents: * content: > Negotiates a WebRTC peer connection with the realtime provider on behalf of the client. Implements the OpenAI GA `/realtime/calls` contract: the request body is `multipart/form-data` with `sdp` (client SDP offer) and `session` (JSON session description containing `model`). Bifrost forwards the offer to the upstream provider, returns the upstream SDP answer to the client, and pipes RTP media between the two peers for the lifetime of the session. Inference auth applies (Bearer/Basic/Virtual Key/API Key). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Negotiates a WebRTC peer connection with the realtime provider on behalf of the client. Implements the OpenAI GA `/realtime/calls` contract: the request body is `multipart/form-data` with `sdp` (client SDP offer) and `session` (JSON session description containing `model`). Bifrost forwards the offer to the upstream provider, returns the upstream SDP answer to the client, and pipes RTP media between the two peers for the lifetime of the session. Inference auth applies (Bearer/Basic/Virtual Key/API Key). --- # Mint a realtime ephemeral client secret URL: /finops-api/realtime/createRealtimeClientSecret *** title: Mint a realtime ephemeral client secret full: true \_openapi: method: POST route: /v1/realtime/client\_secrets toc: \[] structuredData: headings: \[] contents: * content: > Calls the upstream realtime provider's `client_secrets` endpoint to mint a short-lived ephemeral token (e.g. for browser-based WebRTC clients). Bifrost selects a provider key, evaluates governance, and proxies the response. The returned token is cached and mapped to the originating virtual key for downstream attribution. Request body must be JSON. `session.model` (or top-level `model`) must use `provider/model` form. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Calls the upstream realtime provider's `client_secrets` endpoint to mint a short-lived ephemeral token (e.g. for browser-based WebRTC clients). Bifrost selects a provider key, evaluates governance, and proxies the response. The returned token is cached and mapped to the originating virtual key for downstream attribution. Request body must be JSON. `session.model` (or top-level `model`) must use `provider/model` form. --- # Mint a realtime session (legacy alias) URL: /finops-api/realtime/createRealtimeSession *** title: Mint a realtime session (legacy alias) full: true \_openapi: method: POST route: /v1/realtime/sessions toc: \[] structuredData: headings: \[] contents: * content: > Legacy alias for the realtime client-secret minting endpoint. Behaves identically to `createRealtimeClientSecret` but uses the `sessions` route shape; provided for compatibility with older OpenAI Realtime client libraries. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Legacy alias for the realtime client-secret minting endpoint. Behaves identically to `createRealtimeClientSecret` but uses the `sessions` route shape; provided for compatibility with older OpenAI Realtime client libraries. --- # Rerank documents URL: /finops-api/rerank/rerankDocuments *** title: Rerank documents full: true \_openapi: method: POST route: /v1/rerank toc: \[] structuredData: headings: \[] contents: * content: | Reorders input documents by relevance to a query. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Reorders input documents by relevance to a query. --- # Create a response URL: /finops-api/responses/createResponse *** title: Create a response full: true \_openapi: method: POST route: /v1/responses toc: \[] structuredData: headings: \[] contents: * content: > Creates a response using the OpenAI Responses API format. Supports streaming via SSE. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a response using the OpenAI Responses API format. Supports streaming via SSE. --- # Responses API over WebSocket URL: /finops-api/responses/createResponseWebSocket *** title: Responses API over WebSocket full: true \_openapi: method: GET route: /v1/responses toc: \[] structuredData: headings: \[] contents: * content: > Upgrades the connection to a WebSocket and runs the OpenAI Responses API in WebSocket Mode. Clients send `response.create` events on the socket and receive streamed events through the standard inference pipeline (PreLLMHook, key selection, provider call, PostLLMHook). Auth is identical to the HTTP POST variant — Bearer/Basic/Virtual Key/API Key may be supplied as request headers on the upgrade request. The OpenAI SDK can also pass an API key via the `openai-insecure-api-key.` WebSocket subprotocol. This GET endpoint shares its path with the POST inference endpoint; route selection is based on the `Upgrade: websocket` request header. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Upgrades the connection to a WebSocket and runs the OpenAI Responses API in WebSocket Mode. Clients send `response.create` events on the socket and receive streamed events through the standard inference pipeline (PreLLMHook, key selection, provider call, PostLLMHook). Auth is identical to the HTTP POST variant — Bearer/Basic/Virtual Key/API Key may be supplied as request headers on the upgrade request. The OpenAI SDK can also pass an API key via the `openai-insecure-api-key.` WebSocket subprotocol. This GET endpoint shares its path with the POST inference endpoint; route selection is based on the `Upgrade: websocket` request header. --- # Check if authentication is enabled URL: /finops-api/session/isAuthEnabled *** title: Check if authentication is enabled full: true \_openapi: method: GET route: /api/session/is-auth-enabled toc: \[] structuredData: headings: \[] contents: * content: >- Returns whether authentication is enabled and if the current token is valid. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns whether authentication is enabled and if the current token is valid. --- # Issue WebSocket ticket URL: /finops-api/session/issueWSTicket *** title: Issue WebSocket ticket full: true \_openapi: method: POST route: /api/session/ws-ticket toc: \[] structuredData: headings: \[] contents: * content: > Issues a short-lived ticket for authenticating WebSocket connections. The ticket can be used as a query parameter when upgrading to WebSocket. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Issues a short-lived ticket for authenticating WebSocket connections. The ticket can be used as a query parameter when upgrading to WebSocket. --- # Login URL: /finops-api/session/login *** title: Login full: true \_openapi: method: POST route: /api/session/login toc: \[] structuredData: headings: \[] contents: * content: | Authenticates a user and returns a session token. Sets a cookie with the session token for subsequent requests. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Authenticates a user and returns a session token. Sets a cookie with the session token for subsequent requests. --- # Logout URL: /finops-api/session/logout *** title: Logout full: true \_openapi: method: POST route: /api/session/logout toc: \[] structuredData: headings: \[] contents: * content: Logs out the current user and invalidates the session token. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Logs out the current user and invalidates the session token. --- # Create a text completion URL: /finops-api/text-completions/createTextCompletion *** title: Create a text completion full: true \_openapi: method: POST route: /v1/completions toc: \[] structuredData: headings: \[] contents: * content: > Creates a completion for the provided prompt. Supports streaming via SSE. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a completion for the provided prompt. Supports streaming via SSE. --- # Add team member URL: /finops-api/teams/addTeamMember *** title: Add team member full: true \_openapi: method: POST route: /api/teams/{id}/members toc: \[] structuredData: headings: \[] contents: * content: Adds a user to a team. Both the team and user must exist. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Adds a user to a team. Both the team and user must exist. --- # Create team URL: /finops-api/teams/createTeam *** title: Create team full: true \_openapi: method: POST route: /api/teams toc: \[] structuredData: headings: \[] contents: * content: Creates a new team. The team ID is derived from the name. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new team. The team ID is derived from the name. --- # Delete team URL: /finops-api/teams/deleteTeam *** title: Delete team full: true \_openapi: method: DELETE route: /api/teams/{id} toc: \[] structuredData: headings: \[] contents: * content: Permanently removes a team. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Permanently removes a team. --- # Get team URL: /finops-api/teams/getTeam *** title: Get team full: true \_openapi: method: GET route: /api/teams/{id} toc: \[] structuredData: headings: \[] contents: * content: Returns details of a specific team including member count. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns details of a specific team including member count. --- # List team members URL: /finops-api/teams/getTeamMembers *** title: List team members full: true \_openapi: method: GET route: /api/teams/{id}/members toc: \[] structuredData: headings: \[] contents: * content: >- Returns all members of a team with their user details and membership source. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns all members of a team with their user details and membership source. --- # List teams URL: /finops-api/teams/listTeams *** title: List teams full: true \_openapi: method: GET route: /api/teams toc: \[] structuredData: headings: \[] contents: * content: Returns a paginated list of teams with optional search. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a paginated list of teams with optional search. --- # Remove team member URL: /finops-api/teams/removeTeamMember *** title: Remove team member full: true \_openapi: method: DELETE route: /api/teams/{id}/members/{userId} toc: \[] structuredData: headings: \[] contents: * content: Removes a user from a team. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Removes a user from a team. --- # Update team URL: /finops-api/teams/updateTeam *** title: Update team full: true \_openapi: method: PUT route: /api/teams/{id} toc: \[] structuredData: headings: \[] contents: * content: Updates a team. Note that renaming teams is not allowed. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Updates a team. Note that renaming teams is not allowed. --- # Accounts URL: /revos/api-reference/accounts External CRUD for billing accounts and account addresses. *** title: Accounts description: External CRUD for billing accounts and account addresses. ---------------------------------------------------------------------- # Accounts Prefix: `/api/v1/external/accounts` See [Overview](/revos/api-reference) for authentication, pagination, and errors. These APIs manage the billing **Account** object (`account__m`) and billing **AccountAddress** (`accountaddress__m`). They are distinct from CPQ account-address APIs. ## Endpoint summary | Method | Path | | ------ | --------------------------------------------- | | GET | `/accounts` | | GET | `/accounts/{accountId}` | | GET | `/accounts/{accountId}?isExternal=true` | | GET | `/accounts/by-external-id/{externalId}` | | POST | `/accounts` | | PUT | `/accounts/{accountId}` | | PUT | `/accounts/{accountId}/activate` | | PUT | `/accounts/{accountId}/deactivate` | | PUT | `/accounts/{accountId}/tax-labels` | | DELETE | `/accounts/{accountId}` | | GET | `/accounts/{accountId}/addresses` | | GET | `/accounts/{accountId}/addresses/{addressId}` | | POST | `/accounts/{accountId}/addresses` | | PUT | `/accounts/{accountId}/addresses/{addressId}` | | DELETE | `/accounts/{accountId}/addresses/{addressId}` | *** ## Account CRUD ### List accounts ```http GET /api/v1/external/accounts?page=0&size=20&q=acme Authorization: Bearer YOUR_API_TOKEN ``` | Query | Description | | ------ | ------------------------------------------------- | | `page` | 0-based page index (default `0`) | | `size` | Page size (default 20, max 20) | | `q` | Optional search on `name`, `number`, `externalId` | List rows are account headers only (no nested `addresses`). Envelope, Spring `Page`, PascalCase keys, and `__r` objects are described on [Overview](/revos/api-reference#pagination-and-listget-shape). **Response `200`** ```json { "requestId": "req-1", "success": true, "status": 200, "errors": [], "data": { "content": [ { "__type__": "Account", "Id": "11111111-1111-1111-1111-111111111111", "Name": "Acme Corp", "Number": "ACC-1001", "ExternalId": "CRM-55", "IsMaster": true, "BillingDay": 1, "Status": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "Status__r": { "Name": "Active" }, "ApprovalStatus": "fe07e71d-cba4-4316-9c7c-4935c3adec34", "ApprovalStatus__r": { "Name": "Approved" } } ], "totalElements": 1, "totalPages": 1, "size": 20, "number": 0, "first": true, "last": true, "empty": false } } ``` ### Get account ```http GET /api/v1/external/accounts/{accountId} GET /api/v1/external/accounts/{accountId}?isExternal=true Authorization: Bearer YOUR_API_TOKEN ``` | Query | Description | | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | `isExternal` | `false` (default): `{accountId}` is the M360 account UUID. `true`: `{accountId}` is the account `externalId` (same lookup as `GET /accounts/by-external-id/{externalId}`). | Returns the same PascalCase + `__r` row as list (no nested `addresses`). Use `GET /accounts/{id}/addresses` for addresses. `404` if the account is missing. **Response `200`** ```json { "requestId": "req-1", "success": true, "status": 200, "errors": [], "data": { "__type__": "Account", "Id": "11111111-1111-1111-1111-111111111111", "Name": "Acme Corp", "Number": "ACC-1001", "ExternalId": "CRM-55", "BillingDay": 1, "IsMaster": true, "Status": "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa", "Status__r": { "Name": "Active" }, "ApprovalStatus": "fe07e71d-cba4-4316-9c7c-4935c3adec34", "ApprovalStatus__r": { "Name": "Approved" } } } ``` ### Activate / deactivate / tax labels ```http PUT /api/v1/external/accounts/{accountId}/activate PUT /api/v1/external/accounts/{accountId}/deactivate PUT /api/v1/external/accounts/{accountId}/tax-labels ``` Activate and deactivate set account `status` to Active / Inactive and return the GET row. Tax labels body: `{ "gst": "...", "pan": "...", "cin": "..." }` (`GST`/`PAN`/`CIN` aliases accepted). Nested `contactInfoList` and `accountPaymentProfileList` are accepted on create/update write bodies. ### Create account ```http POST /api/v1/external/accounts Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` `name` is required. Nested `addresses` are optional. **Request** ```json { "name": "Acme Corp", "number": "ACC-1001", "externalId": "CRM-55", "billingDay": 1, "isMaster": true, "netTerm": "Net 30", "defaultCurrency": "USD", "addresses": [ { "line1": "1 Market Street", "line2": "Suite 400", "city": "San Francisco", "state": "CA", "zipCode": "94105", "country": "United States", "taxId": "US-12-3456789" } ] } ``` ```bash curl -sS -X POST "https://YOUR_TENANT_HOST/api/v1/external/accounts" \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "name": "Acme Corp", "number": "ACC-1001", "defaultCurrency": "USD", "addresses": [{ "line1": "1 Market Street", "city": "San Francisco", "state": "CA", "zipCode": "94105", "country": "United States" }] }' ``` **Response `201`** — camelCase account DTO (including nested `addresses` when present). List/GET use the `__r` row shape above. ### Update account ```http PUT /api/v1/external/accounts/{accountId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` Updates scalar fields. If `addresses` is present, the address collection is **replaced**. Omit `addresses` to leave them unchanged. **Request** ```json { "name": "Acme Corporation", "netTerm": "Net 45", "billingDay": 15 } ``` **Response `200`** — camelCase account DTO. ### Delete account ```http DELETE /api/v1/external/accounts/{accountId} Authorization: Bearer YOUR_API_TOKEN ``` Deletes nested addresses first. **Response `204`** — no body. **Response `409`** if the account is still referenced by payments or wallets. ```json { "status": 409, "error": "Conflict", "message": "Account is referenced by one or more payments", "path": "uri=/api/v1/external/accounts/11111111-1111-1111-1111-111111111111" } ``` *** ## Account addresses `accountId` comes from the path; do not send a conflicting `accountId` in the body. ### List addresses ```http GET /api/v1/external/accounts/{accountId}/addresses?page=0&size=20 Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "content": [ { "id": "22222222-2222-2222-2222-222222222222", "accountId": "11111111-1111-1111-1111-111111111111", "line1": "1 Market Street", "city": "San Francisco", "state": "CA", "zipCode": "94105", "country": "United States" } ], "page": 0, "size": 20, "totalElements": 1, "totalPages": 1 } ``` ### Get address ```http GET /api/v1/external/accounts/{accountId}/addresses/{addressId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "id": "22222222-2222-2222-2222-222222222222", "accountId": "11111111-1111-1111-1111-111111111111", "line1": "1 Market Street", "line2": "Suite 400", "city": "San Francisco", "state": "CA", "zipCode": "94105", "country": "United States", "taxId": "US-12-3456789" } ``` ### Create address ```http POST /api/v1/external/accounts/{accountId}/addresses Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` `line1` is required. `country` accepts a country name or ISO alpha-2/alpha-3 code. **Request** ```json { "line1": "500 Boylston Street", "line2": "Floor 12", "city": "Boston", "state": "MA", "zipCode": "02116", "country": "US", "taxId": "US-98-7654321" } ``` **Response `201`** ```json { "id": "33333333-3333-3333-3333-333333333333", "accountId": "11111111-1111-1111-1111-111111111111", "line1": "500 Boylston Street", "line2": "Floor 12", "city": "Boston", "state": "MA", "zipCode": "02116", "country": "United States", "taxId": "US-98-7654321" } ``` ### Update address ```http PUT /api/v1/external/accounts/{accountId}/addresses/{addressId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` **Request** ```json { "line1": "500 Boylston Street", "line2": "Floor 14", "city": "Boston", "state": "MA", "zipCode": "02116", "country": "United States" } ``` **Response `200`** ```json { "id": "33333333-3333-3333-3333-333333333333", "accountId": "11111111-1111-1111-1111-111111111111", "line1": "500 Boylston Street", "line2": "Floor 14", "city": "Boston", "state": "MA", "zipCode": "02116", "country": "United States" } ``` ### Delete address ```http DELETE /api/v1/external/accounts/{accountId}/addresses/{addressId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `204`** — no body. --- # Contracts URL: /revos/api-reference/contracts External CRUD for contracts, contract services, and optional exception rate cards. *** title: Contracts description: External CRUD for contracts, contract services, and optional exception rate cards. ----------------------------------------------------------------------------------------------- # Contracts Prefix: `/api/v1/external/contracts` See [Overview](/revos/api-reference) for authentication, pagination, and errors. Rate-card payload variants are documented on [Services — Rate card write body](/revos/api-reference/services#rate-card-write-body). ## Exception pricing A contract-service rate card is **optional exception pricing** for that line. Rating already falls back to the catalog service rate card when no exception exists. * Omit `rateCards` (or send `[]`) when adding a service — **no** catalog matrix is copied. * If `priceableAttributes` is omitted, catalog **dimensions** (all types) are copied; prices are not. * GET rate cards with empty `content` means no exception (`exceptionPricing: false`). * DELETE an exception to return to catalog rates. ## Endpoint summary | Method | Path | | ------ | ----------------------------------------------------------------------------------------- | | GET | `/contracts` | | GET | `/contracts/{contractId}` | | POST | `/contracts` | | PUT | `/contracts/{contractId}` | | DELETE | `/contracts/{contractId}` | | GET | `/contract-services/{contractServiceId}` | | PUT | `/contract-services/{contractServiceId}` | | PUT | `/contract-services/{contractServiceId}/end` | | PUT | `/contracts/services/by-instance/{serviceInstanceId}/end` | | GET | `/contracts/{contractId}/services` | | GET | `/contracts/{contractId}/services/{contractServiceId}` | | POST | `/contracts/{contractId}/services` | | PUT | `/contracts/{contractId}/services/{contractServiceId}` | | PUT | `/contracts/{contractId}/services/{contractServiceId}/end` | | DELETE | `/contracts/{contractId}/services/{contractServiceId}` | | GET | `/contracts/{contractId}/services/{contractServiceId}/priceable-attributes` | | GET | `/contracts/{contractId}/services/{contractServiceId}/priceable-attributes/{attributeId}` | | POST | `/contracts/{contractId}/services/{contractServiceId}/priceable-attributes` | | PUT | `/contracts/{contractId}/services/{contractServiceId}/priceable-attributes/{attributeId}` | | DELETE | `/contracts/{contractId}/services/{contractServiceId}/priceable-attributes/{attributeId}` | | GET | `/contracts/{contractId}/services/{contractServiceId}/rate-cards` | | GET | `/contracts/{contractId}/services/{contractServiceId}/rate-cards/{currency}` | | GET | `/contracts/{contractId}/services/{contractServiceId}/rate-cards/{currency}/versions` | | POST | `/contracts/{contractId}/services/{contractServiceId}/rate-cards` | | PUT | `/contracts/{contractId}/services/{contractServiceId}/rate-cards/{currency}` | | DELETE | `/contracts/{contractId}/services/{contractServiceId}/rate-cards/{currency}` | *** ## Contract CRUD ### List contracts ```http GET /api/v1/external/contracts?page=0&size=20&q=acme Authorization: Bearer YOUR_API_TOKEN ``` | Query | Description | | ------ | ----------------------------------- | | `page` | 0-based page index (default `0`) | | `size` | Page size (default 20, max 20) | | `q` | Optional search on `name`, `number` | **Response `200`** — `ApiResponse` wrapping a Spring `Page` (see [Overview](/revos/api-reference#pagination-and-listget-shape)). ```json { "requestId": "req-1", "success": true, "status": 200, "errors": [], "data": { "content": [ { "__type__": "Contract", "Id": "3a2f1c5d-9b7e-4c1a-8f36-2d4b6e8a0c11", "Name": "Acme MSA", "Number": "C-1001", "ApprovalStatus": "fe07e71d-cba4-4316-9c7c-4935c3adec34", "ApprovalStatus__r": { "Name": "Approved" }, "MasterAccountId": "11111111-1111-1111-1111-111111111111" } ], "totalElements": 1, "size": 20, "number": 0 } } ``` ### Get contract ```http GET /api/v1/external/contracts/{contractId} Authorization: Bearer YOUR_API_TOKEN ``` Returns the contract header row (`__r` shape). Nested service summaries are not expanded — list `/contracts/{id}/services` or `GET /contract-services/{id}`. `POST /contracts` accepts `accountExtId` when `masterAccountId` is omitted, `templateId` on nested services as `serviceId`, optional `dimensionValues` / `accountMap`, and generates `number` (`C-{timestamp}`) if omitted. End a service with `PUT /contract-services/{contractServiceId}/end`, `PUT .../contracts/{contractId}/services/{contractServiceId}/end`, or `PUT /contracts/services/by-instance/{serviceInstanceId}/end` (`409` if the instance id is not unique). Body: `{ "terminationDate": "2026-09-01", "terminationMessage": "..." }`. Do not use DELETE to end a service. **Response `200`** ```json { "id": "3a2f1c5d-9b7e-4c1a-8f36-2d4b6e8a0c11", "name": "Acme MSA", "number": "C-1001", "startDate": "2026-01-01", "endDate": "2026-12-31", "currency": "USD", "masterAccountId": "11111111-1111-1111-1111-111111111111", "approvalStatus": "Approved", "services": [ { "id": "7c9d2e41-5b83-4f6a-9e21-0a5c7d3b8f42", "serviceId": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "serviceInstanceId": "SI-1", "startDate": "2026-01-01", "endDate": "2026-12-31", "exceptionPricing": false } ] } ``` ### Create contract ```http POST /api/v1/external/contracts Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` `number` is required and must be unique (`409` otherwise). `services` is optional. **Request** ```json { "name": "Acme MSA", "number": "C-1001", "startDate": "2026-01-01", "endDate": "2026-12-31", "currency": "USD", "masterAccountId": "11111111-1111-1111-1111-111111111111", "poNumber": "PO-88213", "totalPrice": 120000, "services": [ { "serviceId": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "serviceInstanceId": "SI-1", "startDate": "2026-01-01", "endDate": "2026-12-31" } ] } ``` **Response `201`** — each nested service without `rateCards` has `exceptionPricing: false`. ```json { "id": "3a2f1c5d-9b7e-4c1a-8f36-2d4b6e8a0c11", "name": "Acme MSA", "number": "C-1001", "startDate": "2026-01-01", "endDate": "2026-12-31", "currency": "USD", "masterAccountId": "11111111-1111-1111-1111-111111111111", "poNumber": "PO-88213", "totalPrice": 120000, "services": [ { "id": "7c9d2e41-5b83-4f6a-9e21-0a5c7d3b8f42", "serviceId": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "serviceInstanceId": "SI-1", "startDate": "2026-01-01", "endDate": "2026-12-31", "exceptionPricing": false } ] } ``` ### Update contract ```http PUT /api/v1/external/contracts/{contractId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` Updates scalars. If `services` is present, existing contract services are **replaced**. Omit `services` to leave lines unchanged. **Request** ```json { "name": "Acme MSA (2026 renewal)", "endDate": "2027-12-31", "totalPrice": 145000 } ``` **Response `200`** — the full contract detail, identical in shape to [Get contract](#get-contract). ### Delete contract ```http DELETE /api/v1/external/contracts/{contractId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `204`** — no body. **Response `409`** if the contract still has services. ```json { "status": 409, "error": "Conflict", "message": "Contract still has services", "path": "uri=/api/v1/external/contracts/3a2f1c5d-9b7e-4c1a-8f36-2d4b6e8a0c11" } ``` *** ## Contract services ### List contract services ```http GET /api/v1/external/contracts/{contractId}/services?page=0&size=20 Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "content": [ { "id": "7c9d2e41-5b83-4f6a-9e21-0a5c7d3b8f42", "serviceId": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "serviceInstanceId": "SI-1", "startDate": "2026-01-01", "endDate": "2026-12-31", "chargeFrequency": "Monthly", "billingFrequency": "Monthly", "exceptionPricing": true } ], "page": 0, "size": 20, "totalElements": 1, "totalPages": 1 } ``` ### Get contract service ```http GET /api/v1/external/contracts/{contractId}/services/{contractServiceId} Authorization: Bearer YOUR_API_TOKEN ``` Returns the line plus its priceable attributes and exception `rateCards` (empty array when no exception). **Response `200`** ```json { "id": "7c9d2e41-5b83-4f6a-9e21-0a5c7d3b8f42", "serviceId": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "serviceInstanceId": "SI-1", "startDate": "2026-01-01", "endDate": "2026-12-31", "chargeFrequency": "Monthly", "billingFrequency": "Monthly", "exceptionPricing": true, "priceableAttributes": [ { "id": "5c1e7a29-3f8b-4d62-90ac-4b6d2f8e1c53", "name": "Input_Tokens", "label": "Input Tokens", "dimensionDataType": "Number", "dimValues": [] } ], "rateCards": [ { "currency": "USD", "versionNo": 1, "isCurrent": true, "fromDate": "2026-01-01", "rows": [ { "id": "6a3c9e17-8d2b-4f50-a91e-7c5b0d4f2a68", "priceDimId": "5c1e7a29-3f8b-4d62-90ac-4b6d2f8e1c53", "label": "Negotiated input token rate", "priceMethod": "QUANTITY", "unitRate": 0.0018, "attributeValues": [] } ] } ] } ``` ### Add a service to a contract ```http POST /api/v1/external/contracts/{contractId}/services Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` `serviceId` is required. Omit `priceableAttributes` to copy catalog dimensions; omit `rateCards` to keep catalog list prices. **Request** — attach at catalog pricing. ```json { "serviceId": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "serviceInstanceId": "SI-1", "startDate": "2026-01-01", "endDate": "2026-12-31", "chargeFrequency": "Monthly", "billingFrequency": "Monthly" } ``` **Request** — attach with exception pricing in the same call. ```json { "serviceId": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "serviceInstanceId": "SI-2", "startDate": "2026-01-01", "endDate": "2026-12-31", "rateCards": [ { "currency": "USD", "rows": [ { "priceMethod": "QUANTITY", "priceDimName": "Input_Tokens", "label": "Negotiated input token rate", "unitRate": 0.0018, "attributeValues": [] } ] } ] } ``` **Response `201`** — the full contract service, identical in shape to [Get contract service](#get-contract-service). ### Update contract service ```http PUT /api/v1/external/contracts/{contractId}/services/{contractServiceId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` **Request** ```json { "endDate": "2027-06-30", "billingFrequency": "Quarterly" } ``` **Response `200`** — the full contract service, identical in shape to [Get contract service](#get-contract-service). The same update (no contract id in the path): ```http PUT /api/v1/external/contract-services/{contractServiceId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` ### End contract service ```http PUT /api/v1/external/contract-services/{contractServiceId}/end PUT /api/v1/external/contracts/{contractId}/services/{contractServiceId}/end Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` **Request** ```json { "terminationDate": "2026-09-01", "terminationMessage": "Offboarded" } ``` **Response `200`** — the ended contract-service row (`ApiResponse` + `__r` shape). ### Delete contract service ```http DELETE /api/v1/external/contracts/{contractId}/services/{contractServiceId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `204`** — no body. *** ## Priceable attributes (contract service) Same body shape as catalog service attributes, plus the optional `dimensionValText` field. ### List contract-service priceable attributes ```http GET /api/v1/external/contracts/{contractId}/services/{contractServiceId}/priceable-attributes?page=0&size=20 Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "content": [ { "id": "5c1e7a29-3f8b-4d62-90ac-4b6d2f8e1c53", "name": "Input_Tokens", "label": "Input Tokens", "dimensionDataType": "Number", "isContractInput": true, "dimValues": [] } ], "page": 0, "size": 20, "totalElements": 1, "totalPages": 1 } ``` ### Get contract-service priceable attribute ```http GET /api/v1/external/contracts/{contractId}/services/{contractServiceId}/priceable-attributes/{attributeId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "id": "5c1e7a29-3f8b-4d62-90ac-4b6d2f8e1c53", "name": "Input_Tokens", "label": "Input Tokens", "dimensionDataType": "Number", "isContractInput": true, "dimensionValText": "1000", "dimValues": [] } ``` ### Create contract-service priceable attribute ```http POST /api/v1/external/contracts/{contractId}/services/{contractServiceId}/priceable-attributes Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` **Request** ```json { "name": "Committed_Tokens", "label": "Committed Tokens", "dimensionDataType": "Number", "isContractInput": true, "dimensionValText": "5000000" } ``` **Response `201`** ```json { "id": "8b4f0d36-9a1c-4e75-b2d8-6f3a5c9e0b21", "name": "Committed_Tokens", "label": "Committed Tokens", "dimensionDataType": "Number", "isContractInput": true, "dimensionValText": "5000000", "dimValues": [] } ``` ### Update contract-service priceable attribute ```http PUT /api/v1/external/contracts/{contractId}/services/{contractServiceId}/priceable-attributes/{attributeId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` **Request** ```json { "name": "Committed_Tokens", "label": "Committed Tokens (revised)", "dimensionDataType": "Number", "dimensionValText": "7500000" } ``` **Response `200`** ```json { "id": "8b4f0d36-9a1c-4e75-b2d8-6f3a5c9e0b21", "name": "Committed_Tokens", "label": "Committed Tokens (revised)", "dimensionDataType": "Number", "dimensionValText": "7500000", "dimValues": [] } ``` ### Delete contract-service priceable attribute ```http DELETE /api/v1/external/contracts/{contractId}/services/{contractServiceId}/priceable-attributes/{attributeId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `204`** — no body. **Response `409`** if a **current** exception rate-card row references the attribute. *** ## Exception rate cards Same body shape as catalog rate cards. See [Rate card write body](/revos/api-reference/services#rate-card-write-body) for every `priceMethod` variant. ### List exception rate cards ```http GET /api/v1/external/contracts/{contractId}/services/{contractServiceId}/rate-cards?page=0&size=20 Authorization: Bearer YOUR_API_TOKEN ``` An empty `content` array means there is no exception and rating uses catalog list price. **Response `200`** ```json { "content": [ { "currency": "USD", "versionNo": 1, "isCurrent": true, "fromDate": "2026-01-01", "rows": [ { "id": "6a3c9e17-8d2b-4f50-a91e-7c5b0d4f2a68", "priceDimId": "5c1e7a29-3f8b-4d62-90ac-4b6d2f8e1c53", "label": "Contract override", "priceMethod": "FLAT_RATE", "flatRate": 75.0, "attributeValues": [] } ] } ], "page": 0, "size": 20, "totalElements": 1, "totalPages": 1 } ``` ### Get exception rate card by currency ```http GET /api/v1/external/contracts/{contractId}/services/{contractServiceId}/rate-cards/USD Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "currency": "USD", "versionNo": 1, "isCurrent": true, "fromDate": "2026-01-01", "rows": [ { "id": "6a3c9e17-8d2b-4f50-a91e-7c5b0d4f2a68", "priceDimId": "5c1e7a29-3f8b-4d62-90ac-4b6d2f8e1c53", "label": "Contract override", "priceMethod": "FLAT_RATE", "flatRate": 75.0, "attributeValues": [] } ] } ``` Returns `404` when there is no exception for that currency. ### List exception rate-card versions ```http GET /api/v1/external/contracts/{contractId}/services/{contractServiceId}/rate-cards/USD/versions?page=0&size=20 Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "content": [ { "currency": "USD", "versionNo": 2, "isCurrent": true, "fromDate": "2026-07-01", "rows": [ { "priceDimId": "5c1e7a29-3f8b-4d62-90ac-4b6d2f8e1c53", "label": "Contract override", "priceMethod": "FLAT_RATE", "flatRate": 70.0, "attributeValues": [] } ] }, { "currency": "USD", "versionNo": 1, "isCurrent": false, "fromDate": "2026-01-01", "toDate": "2026-06-30", "rows": [ { "priceDimId": "5c1e7a29-3f8b-4d62-90ac-4b6d2f8e1c53", "label": "Contract override", "priceMethod": "FLAT_RATE", "flatRate": 75.0, "attributeValues": [] } ] } ], "page": 0, "size": 20, "totalElements": 2, "totalPages": 1 } ``` ### Set exception pricing ```http POST /api/v1/external/contracts/{contractId}/services/{contractServiceId}/rate-cards Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` Returns `409` if that currency already has an exception card. **Request** ```json { "currency": "USD", "rows": [ { "priceMethod": "FLAT_RATE", "priceDimName": "Usage", "label": "Contract override", "flatRate": 75.0, "attributeValues": [] } ] } ``` ```bash curl -sS -X POST \ "https://YOUR_TENANT_HOST/api/v1/external/contracts/3a2f1c5d-9b7e-4c1a-8f36-2d4b6e8a0c11/services/7c9d2e41-5b83-4f6a-9e21-0a5c7d3b8f42/rate-cards" \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "currency": "USD", "rows": [{ "priceMethod": "FLAT_RATE", "priceDimName": "Usage", "label": "Contract override", "flatRate": 75.0, "attributeValues": [] }] }' ``` **Response `201`** ```json { "currency": "USD", "versionNo": 1, "isCurrent": true, "fromDate": "2026-08-31", "rows": [ { "id": "6a3c9e17-8d2b-4f50-a91e-7c5b0d4f2a68", "priceDimId": "5c1e7a29-3f8b-4d62-90ac-4b6d2f8e1c53", "label": "Contract override", "priceMethod": "FLAT_RATE", "flatRate": 75.0, "attributeValues": [] } ] } ``` ### Update exception pricing ```http PUT /api/v1/external/contracts/{contractId}/services/{contractServiceId}/rate-cards/USD Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` The `currency` in the body must match the path segment. **Request** ```json { "currency": "USD", "rows": [ { "priceMethod": "FLAT_RATE", "priceDimName": "Usage", "label": "Contract override", "flatRate": 70.0, "attributeValues": [] } ] } ``` **Response `200`** ```json { "currency": "USD", "versionNo": 2, "isCurrent": true, "fromDate": "2026-08-31", "rows": [ { "id": "9c5e1a48-0b7d-4386-c3f1-8a2d6e0b4f79", "priceDimId": "5c1e7a29-3f8b-4d62-90ac-4b6d2f8e1c53", "label": "Contract override", "priceMethod": "FLAT_RATE", "flatRate": 70.0, "attributeValues": [] } ] } ``` ### Remove exception pricing ```http DELETE /api/v1/external/contracts/{contractId}/services/{contractServiceId}/rate-cards/USD Authorization: Bearer YOUR_API_TOKEN ``` Drops the exception; rating falls back to the catalog service rate card. **Response `204`** — no body. --- # Overview URL: /revos/api-reference Revos APIs for billing accounts, contracts, services, pricing, payments, wallets, realtime rating, invoices, and rated transactions. *** title: Overview description: Revos APIs for billing accounts, contracts, services, pricing, payments, wallets, realtime rating, invoices, and rated transactions. ------------------------------------------------------------------------------------------------------------------------------------------------- import { Download } from 'lucide-react' # Overview The Revos APIs let you manage **accounts**, **contracts**, **catalog services**, **priceable attributes**, **rate cards**, **pricing logic**, **payments**, and **wallets**, submit usage for **realtime rating**, and read **invoices** (JSON and PDF) and **rated transactions**. Download Postman collection A common pattern is to model an **LLM model as a service** (for example `gpt-4o`), with priceable attributes `Input_Tokens` and `Output_Tokens`, list-price rate cards per token type, and pricing logic formulas that call `Price(Input_Tokens, …)`. See [Services](/revos/api-reference/services). ## Base URL ``` https://{your-tenant-host}/api/v1/external ``` Use your Monetize360 tenant API host — the same host used for Mbrix workflow and MObject APIs. ## Authentication All requests require a Bearer token (JWT or access key) **and** the tenant-wide **`ADMIN`** role. Users who are only `TENANTADMIN` are authenticated but receive `403` on these catalog endpoints. Assign `ADMIN` to the caller in Users & Roles, then request a new token so the JWT `roles` claim includes `ADMIN`. ```bash curl -H "Authorization: Bearer YOUR_API_TOKEN" \ "https://YOUR_TENANT_HOST/api/v1/external/services?page=0&size=20" ``` ## Concepts | Term | Meaning | | ----------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | | **Service** | Catalog product (`Service` object). Its rate cards are the **list price**. Example: model `gpt-4o`. | | **Priceable attribute** | A `ServiceDimension` / `ContractDimension` with type PRICEABLE — the charge line being priced (for example `Input_Tokens`, `Output_Tokens`). Nested create always stamps `dimType` PRICEABLE. | | **Input attribute** | An INPUT dimension used as a formula quantity (for example `Prompt_Tokens`). Optional on composite service create/update as `inputAttributes`. | | **Rate card** | One currency's current price matrix: rows, optional tiers, and row `attributeValues`. | | **Pricing logic** | Ordered formula steps (a rate computation) that turn rate-card values into a final charge. Same concept as Computations in the UI. | | **Contract service** | A line on a contract (`ContractServices`). Rate cards hang off this line, not the contract header. | | **Exception price** | Optional `ContractServicePriceMatrix`. If omitted, rating uses the catalog service rate card. The catalog matrix is **not** copied onto the contract. | | **Account** | Billing customer account. Nested **addresses** use billing `AccountAddress` (`accountaddress__m`), not the CPQ address object. | | **Payment** | Flat payment CRUD under `/payments`. Create validates via the payment manager. | | **Wallet** | Flat wallet CRUD under `/wallets` (record management; operational top-up/drawdown stays on wallet ops APIs). | | **Invoice** | Read-only under `/invoices`: list/get header + line items, and download the stored PDF. | | **Rated transaction** | Read-only under `/rated-transactions`: list/get header + rating dimensions. | | **Realtime rating** | Asynchronous usage-event submission through `POST /v1/ingest/usage`. | ``` Service ──► priceable attributes (PRICEABLE) e.g. Input_Tokens, Output_Tokens ├──► input attributes (INPUT) e.g. Prompt_Tokens ├──► rate cards (list price, one per currency) └──► pricing logic (Price(Input_Tokens, Qty) steps) Contract ──► contract services ├──► priceable attributes (copied from catalog if omitted) └──► rate cards (optional exception; empty = catalog fallback) Account ──► addresses (billing AccountAddress) Payment ──► accountId → Account Wallet ──► accountId → Account Invoice ──► accountId → Account; items; stored PDF UsageEvent ──► realtime rating ──► RatedTransaction RatedTransaction ──► accountId → Account; dimensions ``` ## Endpoint groups | Group | Prefix | Docs | | ------------------------ | ----------------------------------------------------------- | ------------------------------------------------------------- | | Services | `/api/v1/external/services` | [Services](/revos/api-reference/services) | | Contracts | `/api/v1/external/contracts` | [Contracts](/revos/api-reference/contracts) | | Accounts | `/api/v1/external/accounts` | [Accounts](/revos/api-reference/accounts) | | Payments | `/api/v1/external/payments` | [Payments](/revos/api-reference/payments) | | Wallets | `/api/v1/external/wallets` | [Wallets](/revos/api-reference/wallets) | | Invoices | `/api/v1/external/invoices` | [Invoices](/revos/api-reference/invoices) | | Rated transactions | `/api/v1/external/rated-transactions` | [Rated transactions](/revos/api-reference/rated-transactions) | | Realtime rating | `/v1/ingest/usage` | [Realtime rating](/revos/api-reference/realtime-rating) | | Countries and currencies | `/api/v1/external/countries`, `/api/v1/external/currencies` | [Reference data](/revos/api-reference/reference) | ## Pagination and list/GET shape List endpoints accept `page` (0-based) and `size`. Default size is **20**; the server caps `size` at **20** on billing lists. Reference-data lists (countries, currencies) default to **100**. Every **list** and **GET-by-id** (except nested rate cards and pricing logic) is wrapped in `ApiResponse`. List `data` is a Spring `Page`. Rows keep lookup UUIDs on the field and a sibling `__r` object with the display name. Keys are PascalCase. There are no `{k,v,fv}` cells and no `*Obj` companions. ```json { "requestId": "8f1c2a3b-4d5e-6f70-8192-a3b4c5d6e7f8", "success": true, "status": 200, "errors": [], "data": { "content": [ { "__type__": "Contract", "Id": "68cc8e84-cf43-423b-888b-a76af162e2e0", "Name": "Test Contract A", "ApprovalStatus": "fe07e71d-cba4-4316-9c7c-4935c3adec34", "ApprovalStatus__r": { "Name": "Approved" } } ], "pageable": { "pageNumber": 0, "pageSize": 20, "sort": { "empty": true, "sorted": false, "unsorted": true }, "offset": 0, "paged": true, "unpaged": false }, "last": true, "totalElements": 1, "totalPages": 1, "first": true, "size": 20, "number": 0, "sort": { "empty": true, "sorted": false, "unsorted": true }, "numberOfElements": 1, "empty": false } } ``` GET-by-id uses the same row object inside `data` (no `content` page). Create/update still return camelCase DTO bodies. Optional `q` on a list endpoint does a case-insensitive contains match. The fields it searches differ per resource and are documented on each page. ## Priceable attribute body ```json { "name": "Usage", "label": "Usage", "dimensionDataType": "Number", "isContractInput": false, "isMeterDimension": false, "isProration": null, "meterResetFrequency": null, "dimValues": [{ "label": "US", "value": "US" }] } ``` `name` and `dimensionDataType` are required. Contract-service attributes may also include `dimensionValText`. ## Composite create order 1. Persist the parent (service, or contract / contract service). 2. Persist priceable attributes. 3. Persist rate cards (resolve `priceDimName` to id). On PUT, omit a nested array to leave that collection unchanged. If both `priceableAttributes` and `rateCards` are sent, existing rate cards are removed first so new attributes can be referenced. ## Errors ```json { "status": 400, "error": "Validation Error", "message": "Service name is required", "path": "uri=/api/v1/external/services" } ``` | Status | When | | ------ | -------------------------------------------------------------------------------------- | | `200` | Successful read or update | | `201` | Successful create | | `204` | Successful delete | | `400` | Validation (missing fields, unresolved name, wrong rate-card fields for `priceMethod`) | | `401` | Missing or invalid token | | `403` | Authenticated but missing the `ADMIN` role | | `404` | Parent or nested resource not found | | `409` | Duplicate name/number, duplicate currency rate card, or delete blocked by references | --- # Invoices URL: /revos/api-reference/invoices External read API for billing invoices and invoice PDFs. *** title: Invoices description: External read API for billing invoices and invoice PDFs. --------------------------------------------------------------------- # Invoices Prefix: `/api/v1/external/invoices` See [Overview](/revos/api-reference) for authentication, pagination, and errors. Read-only access to billing **Invoice** records (header plus line items) and the stored invoice **PDF**. Invoices are produced by billing runs; this API does not create or edit them. Picklists (`invoiceStatus`, `invoiceType`, `paymentStatus`, `approvalStatus`, and similar) and `currency` are returned as **names** / ISO codes, not UUIDs. ## Endpoint summary | Method | Path | | ------ | --------------------------- | | GET | `/invoices` | | GET | `/invoices/{invoiceId}` | | GET | `/invoices/{invoiceId}/pdf` | *** ### List invoices ```http GET /api/v1/external/invoices?page=0&size=20&q=INV-10&accountId=11111111-1111-1111-1111-111111111111&fromDate=2026-08-01&toDate=2026-08-31 Authorization: Bearer YOUR_API_TOKEN ``` | Query | Description | | ----------- | ------------------------------------------------------- | | `page` | 0-based page index (default `0`) | | `size` | Page size (default 20, max 20) | | `q` | Optional search on `invoiceNo` | | `accountId` | Optional billing account UUID | | `fromDate` | Optional inclusive start of invoice date (`YYYY-MM-DD`) | | `toDate` | Optional inclusive end of invoice date (`YYYY-MM-DD`) | Either date bound may be omitted. If both are sent, `fromDate` must be on or before `toDate` (`400` otherwise). List rows are invoice headers only (no `items`). Envelope: [Overview](/revos/api-reference#pagination-and-listget-shape). **Response `200`** ```json { "requestId": "req-1", "success": true, "status": 200, "errors": [], "data": { "content": [ { "__type__": "Invoice", "Id": "55555555-5555-5555-5555-555555555555", "InvoiceNo": "INV-1001", "AccountId": "11111111-1111-1111-1111-111111111111", "ApprovalStatus": "fe07e71d-cba4-4316-9c7c-4935c3adec34", "ApprovalStatus__r": { "Name": "Approved" } } ], "totalElements": 1, "size": 20, "number": 0 } } ``` **Response `400`** when the date range is inverted. ```json { "status": 400, "error": "Validation Error", "message": "fromDate must be on or before toDate", "path": "uri=/api/v1/external/invoices" } ``` ### Get invoice ```http GET /api/v1/external/invoices/{invoiceId} Authorization: Bearer YOUR_API_TOKEN ``` Returns the same PascalCase + `__r` header row as list (no nested `items`). **Response `200`** ```json { "id": "55555555-5555-5555-5555-555555555555", "invoiceNo": "INV-1001", "invoiceDate": "2026-08-01", "accountId": "11111111-1111-1111-1111-111111111111", "invoiceStatus": "Posted", "invoiceType": "Generated", "amount": 40.0, "taxAmount": 4.0, "balance": 44.0, "currency": "USD", "dueDate": "2026-08-31", "periodStart": "2026-08-01", "periodEnd": "2026-08-31", "paymentStatus": "Unpaid", "approvalStatus": "Approved", "contractId": "3a2f1c5d-9b7e-4c1a-8f36-2d4b6e8a0c11", "invoiceFileName": "INV-1001.pdf", "items": [ { "id": "66666666-6666-6666-6666-666666666666", "invoiceId": "55555555-5555-5555-5555-555555555555", "serviceId": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "description": "Usage", "volume": 16000, "ratePerUnit": 0.0025, "amount": 40.0, "tax": 4.0, "balance": 44.0, "chargeType": "Usage", "priceMethodType": "QUANTITY", "billStartDate": "2026-08-01", "billEndDate": "2026-08-31", "serviceName": "gpt-4o", "serviceCode": "MODEL-GPT-4O", "currency": "USD" } ] } ``` **Response `404`** when the invoice does not exist. ```json { "status": 404, "error": "Not Found", "message": "Invoice not found", "path": "uri=/api/v1/external/invoices/55555555-5555-5555-5555-555555555555" } ``` ### Download invoice PDF ```http GET /api/v1/external/invoices/{invoiceId}/pdf Authorization: Bearer YOUR_API_TOKEN ``` ```bash curl -sS -L \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -o INV-1001.pdf \ "https://YOUR_TENANT_HOST/api/v1/external/invoices/55555555-5555-5555-5555-555555555555/pdf" ``` **Response `200`** — binary body with PDF headers. ```http HTTP/1.1 200 OK Content-Type: application/pdf Content-Disposition: attachment; filename="INV-1001.pdf" ``` The PDF is the file already stored for that invoice (from invoice PDF generation). **Response `404`** when no PDF has been generated yet. ```json { "status": 404, "error": "Not Found", "message": "Invoice PDF has not been generated", "path": "uri=/api/v1/external/invoices/55555555-5555-5555-5555-555555555555/pdf" } ``` --- # Payments URL: /revos/api-reference/payments External CRUD for billing payments. *** title: Payments description: External CRUD for billing payments. ------------------------------------------------ # Payments Prefix: `/api/v1/external/payments` See [Overview](/revos/api-reference) for authentication, pagination, and errors. Flat CRUD for the billing **Payment** object. Create goes through the platform payment manager (required-field validation and default approval / GL status). ## Endpoint summary | Method | Path | | ------ | ----------------------- | | GET | `/payments` | | GET | `/payments/{paymentId}` | | POST | `/payments` | | PUT | `/payments/{paymentId}` | | DELETE | `/payments/{paymentId}` | *** ### List payments ```http GET /api/v1/external/payments?page=0&size=20&q=PAY-2026 Authorization: Bearer YOUR_API_TOKEN ``` | Query | Description | | ------ | -------------------------------------------------------------------- | | `page` | 0-based page index (default `0`) | | `size` | Page size (default 20, max 20) | | `q` | Optional search on `paymentReference`, `comments`, `participantName` | **Response `200`** — `ApiResponse` + Spring `Page`. See [Overview](/revos/api-reference#pagination-and-listget-shape). ```json { "requestId": "req-1", "success": true, "status": 200, "errors": [], "data": { "content": [ { "__type__": "Payment", "Id": "4b6a8d20-1c3e-4f79-a5b2-8e0d7c6f9a31", "AccountId": "11111111-1111-1111-1111-111111111111", "PaymentReference": "PAY-2026-0001", "Amount": 250.0 } ], "totalElements": 1, "size": 20, "number": 0 } } ``` ### Get payment ```http GET /api/v1/external/payments/{paymentId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "id": "4b6a8d20-1c3e-4f79-a5b2-8e0d7c6f9a31", "accountId": "11111111-1111-1111-1111-111111111111", "currency": "USD", "amount": 250.0, "paymentReference": "PAY-2026-0001", "paymentMethod": "Wire Transfer", "paymentType": "Pay In", "paymentDate": "2026-08-29", "paymentStatus": "Completed", "balanceStatus": "Unapplied", "balance": 250.0, "glPaymentDate": "2026-08-29", "paymentGlStatus": "Pending", "approvalStatus": "Approved", "isManualPayment": true, "comments": "Wire received" } ``` ### Create payment ```http POST /api/v1/external/payments Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` Required fields: `accountId`, `currency`, `paymentReference`, `paymentMethod`, `paymentDate`, `paymentType`. **Request** ```json { "accountId": "11111111-1111-1111-1111-111111111111", "currency": "USD", "amount": 250.0, "paymentReference": "PAY-2026-0001", "paymentMethod": "Wire Transfer", "paymentType": "Pay In", "paymentDate": "2026-08-29", "isManualPayment": true, "comments": "Wire received" } ``` ```bash curl -sS -X POST "https://YOUR_TENANT_HOST/api/v1/external/payments" \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "accountId": "11111111-1111-1111-1111-111111111111", "currency": "USD", "amount": 250.0, "paymentReference": "PAY-2026-0001", "paymentMethod": "Wire Transfer", "paymentType": "Pay In", "paymentDate": "2026-08-29" }' ``` **Response `201`** — the full payment, identical in shape to [Get payment](#get-payment). **Response `409`** on a duplicate `paymentReference`. ```json { "status": 409, "error": "Conflict", "message": "Payment paymentReference already exists", "path": "uri=/api/v1/external/payments" } ``` ### Update payment ```http PUT /api/v1/external/payments/{paymentId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` **Request** ```json { "amount": 275.0, "comments": "Adjusted for FX difference", "paymentStatus": "Completed" } ``` **Response `200`** ```json { "id": "4b6a8d20-1c3e-4f79-a5b2-8e0d7c6f9a31", "accountId": "11111111-1111-1111-1111-111111111111", "currency": "USD", "amount": 275.0, "paymentReference": "PAY-2026-0001", "paymentMethod": "Wire Transfer", "paymentType": "Pay In", "paymentDate": "2026-08-29", "paymentStatus": "Completed", "comments": "Adjusted for FX difference" } ``` ### Delete payment ```http DELETE /api/v1/external/payments/{paymentId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `204`** — no body. --- # Rated transactions URL: /revos/api-reference/rated-transactions External read API for rated transactions and their rating dimensions. *** title: Rated transactions description: External read API for rated transactions and their rating dimensions. ---------------------------------------------------------------------------------- # Rated transactions Prefix: `/api/v1/external/rated-transactions` See [Overview](/revos/api-reference) for authentication, pagination, and errors. Read-only access to billing **RatedTransaction** records (header plus rating dimensions). These rows are produced by rating; this API does not create or edit them. Picklists (`usageType`, `chargeType`) and `currency` / `convCurrency` are returned as **names** / ISO codes, not UUIDs. ## Endpoint summary | Method | Path | | ------ | ------------------------------------- | | GET | `/rated-transactions` | | GET | `/rated-transactions/{transactionId}` | *** ### List rated transactions ```http GET /api/v1/external/rated-transactions?page=0&size=20&q=evt-10&accountId=11111111-1111-1111-1111-111111111111&fromDate=2026-08-01&toDate=2026-08-31 Authorization: Bearer YOUR_API_TOKEN ``` | Query | Description | | ----------- | ----------------------------------------------------------- | | `page` | 0-based page index (default `0`) | | `size` | Page size (default 20, max 20) | | `q` | Optional search on `externalTranId` | | `accountId` | Optional billing account UUID | | `fromDate` | Optional inclusive start of transaction date (`YYYY-MM-DD`) | | `toDate` | Optional inclusive end of transaction date (`YYYY-MM-DD`) | Either date bound may be omitted. If both are sent, `fromDate` must be on or before `toDate` (`400` otherwise). List rows are transaction headers only (no `dimensions`), sorted by transaction date descending. Envelope: [Overview](/revos/api-reference#pagination-and-listget-shape). **Response `200`** ```json { "requestId": "req-1", "success": true, "status": 200, "errors": [], "data": { "content": [ { "__type__": "RatedTransaction", "Id": "88888888-8888-8888-8888-888888888888", "ExternalTranId": "evt-1001", "AccountId": "11111111-1111-1111-1111-111111111111", "ServiceId": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "Amount": 2.5 } ], "totalElements": 1, "size": 20, "number": 0 } } ``` **Response `400`** when the date range is inverted. ```json { "status": 400, "error": "Validation Error", "message": "fromDate must be on or before toDate", "path": "uri=/api/v1/external/rated-transactions" } ``` ### Get rated transaction ```http GET /api/v1/external/rated-transactions/{transactionId} Authorization: Bearer YOUR_API_TOKEN ``` Returns the same PascalCase + `__r` header row as list (no nested `dimensions`). **Response `200`** ```json { "id": "88888888-8888-8888-8888-888888888888", "externalTranId": "evt-1001", "transactionDate": "2026-08-15", "accountId": "11111111-1111-1111-1111-111111111111", "accountNumber": "ACC-1001", "masterAccountId": "11111111-1111-1111-1111-111111111111", "serviceId": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "serviceInstanceId": "SI-1", "contractId": "3a2f1c5d-9b7e-4c1a-8f36-2d4b6e8a0c11", "amount": 2.5, "discount": 0.0, "taxAmount": 0.0, "quantity": 1000, "currency": "USD", "usageType": "Charge", "chargeType": "Usage", "billed": false, "dimensions": [ { "id": "99999999-9999-9999-9999-999999999999", "transactionId": "88888888-8888-8888-8888-888888888888", "dimensionId": "2f8b4c16-7d39-4a52-b1e8-6c0f9a3d5e77", "dimensionName": "Input_Tokens", "volume": 1000, "rate": 0.0025, "calcAmount": 2.5, "currency": "USD", "priceMethodType": "QUANTITY", "billStartDate": "2026-08-01", "billEndDate": "2026-08-31", "isProrated": false, "itemType": "Usage" } ] } ``` **Response `404`** when the transaction does not exist. ```json { "status": 404, "error": "Not Found", "message": "Rated transaction not found", "path": "uri=/api/v1/external/rated-transactions/88888888-8888-8888-8888-888888888888" } ``` --- # Realtime rating URL: /revos/api-reference/realtime-rating Submit usage events to the realtime billing rating pipeline. *** title: Realtime rating description: Submit usage events to the realtime billing rating pipeline. ------------------------------------------------------------------------- # Realtime rating Endpoint: `POST /v1/ingest/usage` The realtime rating API accepts a usage event and publishes it to the tenant's billing pipeline. The event is ingested as a **UsageEvent** and rated asynchronously. Use [Rated transactions](/revos/api-reference/rated-transactions) to read the resulting transaction. ## Authentication Send a valid MPilot Bearer token. The token must contain: * `tenantId` — selects the tenant-specific usage topic. * `morgId` — used as the organization context for the usage event. ## Submit a usage event ```http POST /v1/ingest/usage Authorization: Bearer YOUR_API_TOKEN Content-Type: application/json ``` ```bash curl -sS -X POST "https://YOUR_AI_GATEWAY_HOST/v1/ingest/usage" \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "key": "usage-event-001", "message": { "externalTransactionId": "usage-event-001", "serviceId": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "eventTimestamp": "2026-09-10T12:30:00Z", "billingAccountRef": "ACC-1001", "dimensions": { "Input_Tokens": "1000", "Output_Tokens": "250", "Model": "gpt-4o" }, "quantity": 1250, "serviceInstanceId": "service-instance-001", "priceUnitLabel": "tokens" } }' ``` ### Request body | Field | Required | Description | | ------------------------------- | -------- | --------------------------------------------------------------------------------------------------------------- | | `key` | No | Kafka record key. Using the external transaction ID is recommended. | | `message` | Yes | Usage event submitted to the rating pipeline. Must be a JSON object. | | `message.externalTransactionId` | Yes | Unique producer identifier for the usage event. | | `message.serviceId` | Yes | UUID of the billing service to rate. | | `message.eventTimestamp` | Yes | Time the usage occurred, in ISO 8601 format. | | `message.billingAccountRef` | Yes | External ID of the billing account. | | `message.dimensions` | Yes | Non-empty map of rating dimension names to string values. Names must match the service's configured dimensions. | | `message.quantity` | No | Usage volume supplied to rating. | | `message.serviceInstanceId` | No | External service-instance identifier. | | `message.priceUnitLabel` | No | Price unit label associated with the usage. | `externalTransactionId`, `serviceId`, `eventTimestamp`, `billingAccountRef`, and a non-empty `dimensions` map are required by the downstream billing pipeline. Organization context comes from `morgId` in the token. ## Response **Response `200`** ```json { "status": "published", "topic": "inference-usage_7d2f6c90-4b0a-4cf7-9c58-8f9e18f83a11", "partition": 3, "offset": 1842 } ``` A successful response confirms that Kafka accepted the event. Rating and persistence happen asynchronously; it does not confirm that the event was successfully rated. ## Errors ```json { "status_code": 400, "error": { "message": "organizationId is required in the message or as morgId in the token" }, "extra_fields": {} } ``` | Status | When | | ------ | -------------------------------------------------------------------------------------------------------------- | | `400` | Invalid JSON, missing `message`, missing `morgId` in the token, or gateway Kafka configuration is unavailable. | | `401` | Bearer token is missing, invalid, expired, or lacks `tenantId`. | | `413` | Request body exceeds 1 MiB. | | `502` | The gateway could not publish the event to Kafka. | | `504` | Kafka publishing exceeded the request timeout. | Payload validation and account/service resolution happen downstream. Invalid events may be accepted by this endpoint and then skipped by the billing pipeline; use a unique `externalTransactionId` for tracking and retries. --- # Reference data URL: /revos/api-reference/reference External read API for the countries and currencies accepted on billing catalog writes. *** title: Reference data description: External read API for the countries and currencies accepted on billing catalog writes. --------------------------------------------------------------------------------------------------- # Reference data Prefix: `/api/v1/external` See [Overview](/revos/api-reference) for authentication, pagination, and errors. Billing catalog writes take **names**, not UUIDs, for currency and country. Use these two read endpoints to discover the values your tenant accepts before sending an account address or a rate card. Unlike the billing lists, these default to a page `size` of **100**. ## Endpoint summary | Method | Path | | ------ | ------------- | | GET | `/countries` | | GET | `/currencies` | *** ### List countries ```http GET /api/v1/external/countries?page=0&size=100&q=united Authorization: Bearer YOUR_API_TOKEN ``` | Query | Description | | ------ | --------------------------------------------- | | `page` | 0-based page index (default `0`) | | `size` | Page size (default `100`) | | `q` | Optional search on country name and ISO codes | Any of `name`, `alpha2Code`, or `alpha3Code` is accepted as the `country` value on an [account address](/revos/api-reference/accounts#create-address). **Response `200`** — `ApiResponse` + Spring `Page`. See [Overview](/revos/api-reference#pagination-and-listget-shape). ```json { "requestId": "req-1", "success": true, "status": 200, "errors": [], "data": { "content": [ { "__type__": "Country", "Id": "aaaaaaa1-0000-4000-8000-000000000001", "Name": "United States", "Code": "840", "Alpha2Code": "US", "Alpha3Code": "USA" } ], "totalElements": 2, "size": 100, "number": 0 } } ``` ### List currencies ```http GET /api/v1/external/currencies?page=0&size=100&q=usd Authorization: Bearer YOUR_API_TOKEN ``` | Query | Description | | ------ | ----------------------------------------- | | `page` | 0-based page index (default `0`) | | `size` | Page size (default `100`) | | `q` | Optional search on currency code and name | Either `code` or `name` is accepted wherever a `currency` value is expected — service and contract headers, rate-card bodies, the `{currency}` path segment on rate-card routes, payments, and wallets. ```bash curl -sS "https://YOUR_TENANT_HOST/api/v1/external/currencies?q=usd" \ -H "Authorization: Bearer YOUR_API_TOKEN" ``` **Response `200`** ```json { "content": [ { "id": "bbbbbbb1-0000-4000-8000-000000000001", "code": "USD", "name": "US Dollar", "symbol": "$" } ], "page": 0, "size": 100, "totalElements": 1, "totalPages": 1 } ``` --- # Services URL: /revos/api-reference/services External CRUD for catalog services, priceable attributes, list-price rate cards, and pricing logic. *** title: Services description: External CRUD for catalog services, priceable attributes, list-price rate cards, and pricing logic. ---------------------------------------------------------------------------------------------------------------- # Services Prefix: `/api/v1/external/services` See [Overview](/revos/api-reference) for authentication, pagination, and errors. The examples below treat an **LLM model as a service** (`gpt-4o`). Token charges use **priceable attributes** named `Input_Tokens` and `Output_Tokens`. Raw token counts arrive as **input attributes** (`Prompt_Tokens`, `Completion_Tokens`). **Pricing logic** turns rate-card unit rates into a final charge (the same concept as Computations in the product UI). ## Endpoint summary | Method | Path | | ------ | ---------------------------------------------------------- | | GET | `/services` | | GET | `/services/{serviceId}` | | POST | `/services` | | PUT | `/services/{serviceId}` | | DELETE | `/services/{serviceId}` | | GET | `/services/{serviceId}/priceable-attributes` | | GET | `/services/{serviceId}/priceable-attributes/{attributeId}` | | POST | `/services/{serviceId}/priceable-attributes` | | PUT | `/services/{serviceId}/priceable-attributes/{attributeId}` | | DELETE | `/services/{serviceId}/priceable-attributes/{attributeId}` | | GET | `/services/{serviceId}/rate-cards` | | GET | `/services/{serviceId}/rate-cards/{currency}` | | GET | `/services/{serviceId}/rate-cards/{currency}/versions` | | POST | `/services/{serviceId}/rate-cards` | | PUT | `/services/{serviceId}/rate-cards/{currency}` | | DELETE | `/services/{serviceId}/rate-cards/{currency}` | | GET | `/services/{serviceId}/pricing-logic` | | GET | `/services/{serviceId}/pricing-logic/{pricingLogicId}` | | POST | `/services/{serviceId}/pricing-logic` | | PUT | `/services/{serviceId}/pricing-logic/{pricingLogicId}` | | DELETE | `/services/{serviceId}/pricing-logic/{pricingLogicId}` | *** ## Service CRUD ### List services ```http GET /api/v1/external/services?page=0&size=20&q=gpt Authorization: Bearer YOUR_API_TOKEN ``` | Query | Description | | ------ | ------------------------------------------ | | `page` | 0-based page index (default `0`) | | `size` | Page size (default 20, max 20) | | `q` | Optional search on `name`, `code`, `label` | List rows are service headers only — nested attributes, rate cards, and pricing logic are omitted. Envelope and `__r` objects: [Overview](/revos/api-reference#pagination-and-listget-shape). **Response `200`** ```json { "requestId": "req-1", "success": true, "status": 200, "errors": [], "data": { "content": [ { "__type__": "Service", "Id": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "Name": "gpt-4o", "Label": "GPT-4o", "Code": "MODEL-GPT-4O", "ApprovalStatus": "fe07e71d-cba4-4316-9c7c-4935c3adec34", "ApprovalStatus__r": { "Name": "Approved" } } ], "totalElements": 1, "size": 20, "number": 0 } } ``` ### Get service ```http GET /api/v1/external/services/{serviceId} Authorization: Bearer YOUR_API_TOKEN ``` Returns scalar fields plus current `priceableAttributes[]`, `inputAttributes[]`, `rateCards[]` (one current card per currency), and `pricingLogic[]`. **Response `200`** ```json { "id": "e6cbd28a-f34c-482e-8da5-34e21dbd5eb7", "name": "gpt-4o", "label": "GPT-4o", "code": "MODEL-GPT-4O", "serviceType": "Usage", "serviceStatus": "Active", "currency": "USD", "priceableAttributes": [ { "id": "2f8b4c16-7d39-4a52-b1e8-6c0f9a3d5e77", "name": "Input_Tokens", "label": "Input Tokens", "dimensionDataType": "Number", "isMeterDimension": false, "dimValues": [] }, { "id": "3a9c5d27-8e4a-4b63-c2f9-7d1e0b4c6f88", "name": "Output_Tokens", "label": "Output Tokens", "dimensionDataType": "Number", "isMeterDimension": false, "dimValues": [] } ], "inputAttributes": [ { "id": "4b0d6e38-9f5b-4c74-d3a0-8e2f1c5d7a99", "name": "Prompt_Tokens", "label": "Prompt Tokens", "dimensionDataType": "Number", "dimValues": [] } ], "rateCards": [ { "currency": "USD", "versionNo": 1, "isCurrent": true, "fromDate": "2026-01-01", "rows": [ { "id": "6d2f8a5a-1b7d-4e96-f5c2-0a4b3e7f9c11", "priceDimId": "2f8b4c16-7d39-4a52-b1e8-6c0f9a3d5e77", "label": "Input token unit rate", "usageType": "Charge", "priceMethod": "QUANTITY", "unitRate": 0.0025, "attributeValues": [] } ] } ], "pricingLogic": [ { "id": "9d1e7f23-4a6b-4c85-8e30-1b7d5f2a9c64", "name": "Input token pricing", "seqNo": 1, "priceOutput": "Price_for_Input_Tokens", "transactionDimension": "Customer", "usageType": "Charge", "chargeType": "Usage", "steps": [ { "name": "Input_Tokens_Converted", "label": "Input Tokens Converted", "formula": "(Prompt_Tokens / 1000)" }, { "name": "Input_Tokens_Qty", "label": "Input Tokens Qty", "formula": "Ceil(Input_Tokens_Converted)" }, { "name": "Price_for_Input_Tokens", "label": "Price for Input Tokens", "formula": "Price(Input_Tokens, Input_Tokens_Qty)" } ] } ] } ``` ### Create service ```http POST /api/v1/external/services Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` `name` is required and must be unique (`409` otherwise). Nested `priceableAttributes`, `inputAttributes`, `rateCards`, and `pricingLogic` are optional and persisted in that order. **Request** — catalog a model with input/output token priceables, quantity inputs, list-price rate cards, and pricing logic for input tokens. ```json { "name": "gpt-4o", "label": "GPT-4o", "code": "MODEL-GPT-4O", "currency": "USD", "serviceType": "Usage", "priceableAttributes": [ { "name": "Input_Tokens", "label": "Input Tokens", "dimensionDataType": "Number" }, { "name": "Output_Tokens", "label": "Output Tokens", "dimensionDataType": "Number" } ], "inputAttributes": [ { "name": "Prompt_Tokens", "label": "Prompt Tokens", "dimensionDataType": "Number" }, { "name": "Completion_Tokens", "label": "Completion Tokens", "dimensionDataType": "Number" } ], "rateCards": [ { "currency": "USD", "rows": [ { "priceMethod": "QUANTITY", "priceDimName": "Input_Tokens", "label": "Input token unit rate", "unitRate": 0.0025, "usageType": "Charge", "attributeValues": [] }, { "priceMethod": "QUANTITY", "priceDimName": "Output_Tokens", "label": "Output token unit rate", "unitRate": 0.01, "usageType": "Charge", "attributeValues": [] } ] } ], "pricingLogic": [ { "name": "Input token pricing", "priceOutput": "Price_for_Input_Tokens", "transactionDimension": "Customer", "usageType": "Charge", "chargeType": "Usage", "steps": [ { "name": "Input_Tokens_Converted", "label": "Input Tokens Converted", "formula": "Prompt_Tokens / 1000" }, { "name": "Input_Tokens_Qty", "label": "Input Tokens Qty", "formula": "Ceil(Input_Tokens_Converted)" }, { "name": "Price_for_Input_Tokens", "label": "Price for Input Tokens", "formula": "Price(Input_Tokens, Input_Tokens_Qty)" } ] } ] } ``` **Response `201`** — the full service detail, identical in shape to [Get service](#get-service). Notes: * `Input_Tokens` / `Output_Tokens` are **priceable** attributes: each owns rate-card rows and is the first argument to `Price(...)`. * `Prompt_Tokens` / `Completion_Tokens` are **input** attributes: rating supplies their numeric values. * `transactionDimension` (`Customer` above) is a TRANSACTION dimension. If it does not exist yet, create pricing logic creates it. * Step names and `priceOutput` must match `[A-Za-z_][A-Za-z0-9_]*` (use underscores, not spaces). ### Update service ```http PUT /api/v1/external/services/{serviceId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` Updates scalar fields. If `priceableAttributes`, `inputAttributes`, `rateCards`, or `pricingLogic` are present, those collections are **replaced**. Omit an array to leave it unchanged. **Request** — rename the display label and description only. ```json { "label": "GPT-4o (Nov 2026)", "description": "OpenAI GPT-4o, November 2026 snapshot", "serviceStatus": "Active" } ``` **Response `200`** — the full service detail, identical in shape to [Get service](#get-service). ### Delete service ```http DELETE /api/v1/external/services/{serviceId} Authorization: Bearer YOUR_API_TOKEN ``` Deletes nested pricing logic, rate cards, and dimensions. **Response `204`** — no body. **Response `409`** if any contract service still references the catalog service. ```json { "status": 409, "error": "Conflict", "message": "Service is referenced by one or more contract services", "path": "uri=/api/v1/external/services/e6cbd28a-f34c-482e-8da5-34e21dbd5eb7" } ``` *** ## Priceable attributes Priceable attributes are the **charge lines** on the model (for example `Input_Tokens`, `Output_Tokens`). Rate-card rows attach to them via `priceDimName` / `priceDimId`. Input attributes use the same body shape under `inputAttributes` on composite service create/update (type INPUT). They are returned on GET service; there is no separate nested CRUD path for them. ### List priceable attributes ```http GET /api/v1/external/services/{serviceId}/priceable-attributes?page=0&size=20 Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "content": [ { "id": "2f8b4c16-7d39-4a52-b1e8-6c0f9a3d5e77", "name": "Input_Tokens", "label": "Input Tokens", "dimensionDataType": "Number", "isContractInput": false, "isMeterDimension": false, "dimValues": [] } ], "page": 0, "size": 20, "totalElements": 1, "totalPages": 1 } ``` ### Get priceable attribute ```http GET /api/v1/external/services/{serviceId}/priceable-attributes/{attributeId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "id": "2f8b4c16-7d39-4a52-b1e8-6c0f9a3d5e77", "name": "Input_Tokens", "label": "Input Tokens", "dimensionDataType": "Number", "isContractInput": false, "isMeterDimension": false, "dimValues": [] } ``` ### Create priceable attribute ```http POST /api/v1/external/services/{serviceId}/priceable-attributes Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` `name` and `dimensionDataType` are required. **Request** ```json { "name": "Output_Tokens", "label": "Output Tokens", "dimensionDataType": "Number", "isContractInput": false, "isMeterDimension": false, "dimValues": [] } ``` **Response `201`** ```json { "id": "3a9c5d27-8e4a-4b63-c2f9-7d1e0b4c6f88", "name": "Output_Tokens", "label": "Output Tokens", "dimensionDataType": "Number", "isContractInput": false, "isMeterDimension": false, "dimValues": [] } ``` ### Update priceable attribute ```http PUT /api/v1/external/services/{serviceId}/priceable-attributes/{attributeId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` **Request** ```json { "name": "Output_Tokens", "label": "Completion Tokens", "dimensionDataType": "Number", "dimValues": [{ "label": "US", "value": "US" }] } ``` **Response `200`** ```json { "id": "3a9c5d27-8e4a-4b63-c2f9-7d1e0b4c6f88", "name": "Output_Tokens", "label": "Completion Tokens", "dimensionDataType": "Number", "dimValues": [{ "label": "US", "value": "US" }] } ``` ### Delete priceable attribute ```http DELETE /api/v1/external/services/{serviceId}/priceable-attributes/{attributeId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `204`** — no body. **Response `409`** if a **current** rate-card row still uses that `priceDimId`. ```json { "status": 409, "error": "Conflict", "message": "Priceable attribute is referenced by a current rate card", "path": "uri=/api/v1/external/services/e6cbd28a-f34c-482e-8da5-34e21dbd5eb7/priceable-attributes/2f8b4c16-7d39-4a52-b1e8-6c0f9a3d5e77" } ``` ### Metered attributes (usage counters) Set `isMeterDimension: true` when rating must **accumulate usage across transactions** and price against that running counter — not just the quantity on a single event. Typical use case: **first N units free per period**, then charge the rest. For example, the first **1,000 API calls per month** are free; anything above that is billed. | Field | Role | | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | | `isMeterDimension` | When `true`, the platform keeps a **dimension meter** (counter + optional limit) for this priceable attribute per contract service / account. Rating loads the previous counter, applies the new usage, and writes the updated meter back. | | `meterResetFrequency` | Picklist **name** that defines when the counter resets: `Daily`, `Weekly`, `Fortnightly`, `Monthly`, `Quarterly`, `Half Yearly`, `Yearly`. Required for a meaningful free-allowance period. | Without a metered attribute, each rating run only sees the current request's quantity — it cannot know that 800 of the free 1,000 were already used earlier in the month. **Request** — metered API usage with a monthly free allowance: ```json { "name": "API_Calls", "label": "API Calls", "dimensionDataType": "Number", "isMeterDimension": true, "meterResetFrequency": "Monthly" } ``` **Response `201`** ```json { "id": "7e3a9b64-2c5d-4f81-a70b-3d6e8f1c4a25", "name": "API_Calls", "label": "API Calls", "dimensionDataType": "Number", "isMeterDimension": true, "meterResetFrequency": "Monthly", "dimValues": [] } ``` Pair a metered priceable with a **TIERED** rate-card row: tier 1 covers the free band (unit rate `0`), later tiers charge overage. You can also set `resetFrequency` on the rate-card row (same picklist names); if omitted, rating falls back to the attribute's `meterResetFrequency`. ```json { "priceMethod": "TIERED", "priceDimName": "API_Calls", "label": "Monthly API calls (first 1000 free)", "usageType": "Charge", "resetFrequency": "Monthly", "rateCardTiers": [ { "tierNum": 1, "tierMinVal": 0, "tierMaxVal": 1000, "tierUnitRate": 0, "flatRate": false }, { "tierNum": 2, "tierMinVal": 1000, "tierMaxVal": null, "tierUnitRate": 0.01, "flatRate": false } ], "attributeValues": [] } ``` How it behaves at rating time: 1. Meter for `API_Calls` is loaded for the current **Monthly** window (or created at 0 if new). 2. New usage is added to the counter; tiered pricing applies across the filled volume (free band first, then paid). 3. Updated counter is persisted so the next call in the same month continues from where the last left off. 4. When the period rolls, the counter starts over. *** ## Rate cards (list price) A rate card is one currency's current price matrix for the service. ### Rate card write body Rate cards are written on both catalog services and contract-service exceptions with the same body: ```json { "currency": "USD", "rows": [ { "priceMethod": "FLAT_RATE", "priceDimName": "Usage", "label": "Monthly subscription", "flatRate": 99.0, "attributeValues": [] } ] } ``` **Common row fields:** `label` (required), `priceDimId` or `priceDimName`, `description`, `dynamicDescription`, `taxCode`, `usageType` (`Charge` or `Payout`), `billingAccountId`, `priceMethod` (required), `attributeValues`. `attributeValues` may be omitted (treated as `[]`) or empty. Each entry is `{ "attributeName", "attributeValue" }`. `rows` must contain at least one row. Send **only** the rate fields for that `priceMethod`. Extra fields return `400`. #### FLAT\_RATE ```json { "priceMethod": "FLAT_RATE", "priceDimName": "Usage", "label": "Monthly subscription", "flatRate": 99.0, "attributeValues": [] } ``` #### TIERED ```json { "priceMethod": "TIERED", "priceDimName": "Usage", "label": "Volume tiers", "resetFrequency": "Monthly", "rateCardTiers": [ { "tierNum": 1, "tierMinVal": 0, "tierMaxVal": 100, "tierUnitRate": 1.5, "flatRate": false } ], "attributeValues": [{ "attributeName": "Region", "attributeValue": "US" }] } ``` `rateCardTiers` is required and non-empty. `flatRate` on a **tier** is a band-level flag, not the row-level `flatRate`. `resetFrequency` is a **Meter Reset Frequency** picklist name (`Daily`, `Weekly`, `Monthly`, …). Use it with a metered priceable attribute when tiers depend on a period counter (for example first N free per month). See [Metered attributes](#metered-attributes-usage-counters). #### QUANTITY ```json { "priceMethod": "QUANTITY", "priceDimName": "Usage", "label": "Per unit", "unitRate": 0.25, "attributeValues": [] } ``` #### AMOUNT ```json { "priceMethod": "AMOUNT", "priceDimName": "Usage", "label": "Percent of amount", "percentageRate": 2.5, "attributeValues": [] } ``` #### NO\_PRICE ```json { "priceMethod": "NO_PRICE", "priceDimName": "Usage", "label": "Included", "attributeValues": [] } ``` Rate-card **responses** echo the resolved `priceDimId` rather than `priceDimName`, and add `versionNo`, `isCurrent`, `fromDate`, and `toDate`. ### List rate cards ```http GET /api/v1/external/services/{serviceId}/rate-cards?page=0&size=20 Authorization: Bearer YOUR_API_TOKEN ``` Returns the current card per currency. **Response `200`** ```json { "content": [ { "currency": "USD", "versionNo": 1, "isCurrent": true, "fromDate": "2026-01-01", "rows": [ { "id": "6d2f8a5a-1b7d-4e96-f5c2-0a4b3e7f9c11", "priceDimId": "2f8b4c16-7d39-4a52-b1e8-6c0f9a3d5e77", "label": "Input token unit rate", "usageType": "Charge", "priceMethod": "QUANTITY", "unitRate": 0.0025, "attributeValues": [] } ] } ], "page": 0, "size": 20, "totalElements": 1, "totalPages": 1 } ``` ### Get rate card by currency ```http GET /api/v1/external/services/{serviceId}/rate-cards/USD Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "currency": "USD", "versionNo": 2, "isCurrent": true, "fromDate": "2026-07-01", "rows": [ { "id": "6d2f8a5a-1b7d-4e96-f5c2-0a4b3e7f9c11", "priceDimId": "2f8b4c16-7d39-4a52-b1e8-6c0f9a3d5e77", "label": "Input token unit rate", "usageType": "Charge", "priceMethod": "QUANTITY", "unitRate": 0.003, "attributeValues": [] } ] } ``` Returns `404` when that currency has no current card. ### List rate-card versions ```http GET /api/v1/external/services/{serviceId}/rate-cards/USD/versions?page=0&size=20 Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "content": [ { "currency": "USD", "versionNo": 2, "isCurrent": true, "fromDate": "2026-07-01", "rows": [ { "priceDimId": "2f8b4c16-7d39-4a52-b1e8-6c0f9a3d5e77", "label": "Input token unit rate", "priceMethod": "QUANTITY", "unitRate": 0.003, "attributeValues": [] } ] }, { "currency": "USD", "versionNo": 1, "isCurrent": false, "fromDate": "2026-01-01", "toDate": "2026-06-30", "rows": [ { "priceDimId": "2f8b4c16-7d39-4a52-b1e8-6c0f9a3d5e77", "label": "Input token unit rate", "priceMethod": "QUANTITY", "unitRate": 0.0025, "attributeValues": [] } ] } ], "page": 0, "size": 20, "totalElements": 2, "totalPages": 1 } ``` ### Create rate card ```http POST /api/v1/external/services/{serviceId}/rate-cards Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` Adds a card for a **new** currency. Returns `409` if that currency already has a current card. **Request** ```json { "currency": "EUR", "rows": [ { "priceMethod": "QUANTITY", "priceDimName": "Input_Tokens", "label": "Per 1K input tokens", "usageType": "Charge", "unitRate": 0.0023, "attributeValues": [] } ] } ``` ```bash curl -sS -X POST "https://YOUR_TENANT_HOST/api/v1/external/services/e6cbd28a-f34c-482e-8da5-34e21dbd5eb7/rate-cards" \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "currency": "EUR", "rows": [{ "priceMethod": "QUANTITY", "priceDimName": "Input_Tokens", "label": "Per 1K input tokens", "unitRate": 0.0023, "attributeValues": [] }] }' ``` **Response `201`** ```json { "currency": "EUR", "versionNo": 1, "isCurrent": true, "fromDate": "2026-08-31", "rows": [ { "id": "8f4a0c76-3d9f-4a18-b82d-5f7c1e9b0a33", "priceDimId": "2f8b4c16-7d39-4a52-b1e8-6c0f9a3d5e77", "label": "Per 1K input tokens", "usageType": "Charge", "priceMethod": "QUANTITY", "unitRate": 0.0023, "attributeValues": [] } ] } ``` ### Update rate card ```http PUT /api/v1/external/services/{serviceId}/rate-cards/USD Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` Replaces the card on a draft service, or creates a new version on an approved service. The `currency` in the body must match the path segment. **Request** ```json { "currency": "USD", "rows": [ { "priceMethod": "QUANTITY", "priceDimName": "Input_Tokens", "label": "Input token unit rate", "unitRate": 0.003, "attributeValues": [] }, { "priceMethod": "QUANTITY", "priceDimName": "Output_Tokens", "label": "Output token unit rate", "unitRate": 0.012, "attributeValues": [] } ] } ``` **Response `200`** ```json { "currency": "USD", "versionNo": 2, "isCurrent": true, "fromDate": "2026-08-31", "rows": [ { "id": "1c7e5b90-6a2d-4f43-9b1c-7e0d4a8f2b56", "priceDimId": "2f8b4c16-7d39-4a52-b1e8-6c0f9a3d5e77", "label": "Input token unit rate", "priceMethod": "QUANTITY", "unitRate": 0.003, "attributeValues": [] }, { "id": "2d8f6c01-7b3e-4054-ac2d-8f1e5b9a3c67", "priceDimId": "3a9c5d27-8e4a-4b63-c2f9-7d1e0b4c6f88", "label": "Output token unit rate", "priceMethod": "QUANTITY", "unitRate": 0.012, "attributeValues": [] } ] } ``` ### Delete rate card ```http DELETE /api/v1/external/services/{serviceId}/rate-cards/USD Authorization: Bearer YOUR_API_TOKEN ``` Soft-deletes rows, tiers, and attribute values for that currency. **Response `204`** — no body. *** ## Pricing logic Pricing logic is the external name for a **service rate computation**: ordered formula steps that compute a charge from rate cards and inputs (the same idea as Computation steps in the UI). ### Body shape | Field | Required | Description | | ---------------------- | -------- | ------------------------------------------------------------------- | | `name` | Yes | Computation name | | `priceOutput` | Yes | Step `name` that holds the final numeric price | | `transactionDimension` | Yes | TRANSACTION dimension name (who is billed). Auto-created if missing | | `usageType` | No | `Charge` (default) or `Payout` | | `chargeType` | No | Picklist name: `Usage`, `Subscription`, `All`, or `OTC` | | `steps` | Yes | Ordered steps; each has `name`, optional `label`, and `formula` | ### Supported formulas | Pattern | Example | | ----------------- | ------------------------------------------------------------------------------------- | | Binary arithmetic | `Prompt_Tokens / 1000`, `A + B`, `A - B`, `A * B` | | Unary math | `Ceil(Input_Tokens_Converted)`, `Floor(X)`, `Round(X)` | | Rate-card lookup | `Price(Input_Tokens, Input_Tokens_Qty)` — first arg is a **priceable** attribute name | | Literals | `"LLM_Usage"`, `1000` | ### List pricing logic ```http GET /api/v1/external/services/{serviceId}/pricing-logic?page=0&size=20 Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "content": [ { "id": "9d1e7f23-4a6b-4c85-8e30-1b7d5f2a9c64", "name": "Input token pricing", "seqNo": 1, "priceOutput": "Price_for_Input_Tokens", "transactionDimension": "Customer", "usageType": "Charge", "chargeType": "Usage", "steps": [ { "name": "Input_Tokens_Converted", "label": "Input Tokens Converted", "formula": "(Prompt_Tokens / 1000)" }, { "name": "Input_Tokens_Qty", "label": "Input Tokens Qty", "formula": "Ceil(Input_Tokens_Converted)" }, { "name": "Price_for_Input_Tokens", "label": "Price for Input Tokens", "formula": "Price(Input_Tokens, Input_Tokens_Qty)" } ] } ], "page": 0, "size": 20, "totalElements": 1, "totalPages": 1 } ``` ### Get pricing logic ```http GET /api/v1/external/services/{serviceId}/pricing-logic/{pricingLogicId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "id": "9d1e7f23-4a6b-4c85-8e30-1b7d5f2a9c64", "name": "Input token pricing", "seqNo": 1, "priceOutput": "Price_for_Input_Tokens", "transactionDimension": "Customer", "usageType": "Charge", "chargeType": "Usage", "steps": [ { "name": "Input_Tokens_Converted", "label": "Input Tokens Converted", "formula": "(Prompt_Tokens / 1000)" }, { "name": "Input_Tokens_Qty", "label": "Input Tokens Qty", "formula": "Ceil(Input_Tokens_Converted)" }, { "name": "Price_for_Input_Tokens", "label": "Price for Input Tokens", "formula": "Price(Input_Tokens, Input_Tokens_Qty)" } ] } ``` ### Create pricing logic ```http POST /api/v1/external/services/{serviceId}/pricing-logic Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` **Request** — price output tokens. ```json { "name": "Output token pricing", "priceOutput": "Price_for_Output_Tokens", "transactionDimension": "Customer", "usageType": "Charge", "chargeType": "Usage", "steps": [ { "name": "Output_Tokens_Converted", "label": "Output Tokens Converted", "formula": "Completion_Tokens / 1000" }, { "name": "Output_Tokens_Qty", "label": "Output Tokens Qty", "formula": "Ceil(Output_Tokens_Converted)" }, { "name": "Price_for_Output_Tokens", "label": "Price for Output Tokens", "formula": "Price(Output_Tokens, Output_Tokens_Qty)" } ] } ``` **Response `201`** — formulas may come back normalized (for example with parentheses around arithmetic). ```json { "id": "0e2f8a34-5b7c-4d96-af41-2c8e6b0d3f75", "name": "Output token pricing", "seqNo": 2, "priceOutput": "Price_for_Output_Tokens", "transactionDimension": "Customer", "usageType": "Charge", "chargeType": "Usage", "steps": [ { "name": "Output_Tokens_Converted", "label": "Output Tokens Converted", "formula": "(Completion_Tokens / 1000)" }, { "name": "Output_Tokens_Qty", "label": "Output Tokens Qty", "formula": "Ceil(Output_Tokens_Converted)" }, { "name": "Price_for_Output_Tokens", "label": "Price for Output Tokens", "formula": "Price(Output_Tokens, Output_Tokens_Qty)" } ] } ``` ### Update pricing logic ```http PUT /api/v1/external/services/{serviceId}/pricing-logic/{pricingLogicId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` The body replaces the whole computation, so send the full step list. **Request** ```json { "name": "Output token pricing", "priceOutput": "Price_for_Output_Tokens", "transactionDimension": "Customer", "usageType": "Charge", "chargeType": "Usage", "steps": [ { "name": "Output_Tokens_Qty", "label": "Output Tokens Qty", "formula": "Ceil(Completion_Tokens / 1000)" }, { "name": "Price_for_Output_Tokens", "label": "Price for Output Tokens", "formula": "Price(Output_Tokens, Output_Tokens_Qty)" } ] } ``` **Response `200`** ```json { "id": "0e2f8a34-5b7c-4d96-af41-2c8e6b0d3f75", "name": "Output token pricing", "seqNo": 2, "priceOutput": "Price_for_Output_Tokens", "transactionDimension": "Customer", "usageType": "Charge", "chargeType": "Usage", "steps": [ { "name": "Output_Tokens_Qty", "label": "Output Tokens Qty", "formula": "Ceil((Completion_Tokens / 1000))" }, { "name": "Price_for_Output_Tokens", "label": "Price for Output Tokens", "formula": "Price(Output_Tokens, Output_Tokens_Qty)" } ] } ``` ### Delete pricing logic ```http DELETE /api/v1/external/services/{serviceId}/pricing-logic/{pricingLogicId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `204`** — no body. --- # Wallets URL: /revos/api-reference/wallets External CRUD for billing wallets. *** title: Wallets description: External CRUD for billing wallets. ----------------------------------------------- # Wallets Prefix: `/api/v1/external/wallets` See [Overview](/revos/api-reference) for authentication, pagination, and errors. Flat CRUD for the billing **Wallet** object. Top-up and drawdown operations remain on the existing wallet operational APIs; this API manages wallet records. ## Endpoint summary | Method | Path | | ------ | --------------------- | | GET | `/wallets` | | GET | `/wallets/{walletId}` | | POST | `/wallets` | | PUT | `/wallets/{walletId}` | | DELETE | `/wallets/{walletId}` | *** ### List wallets ```http GET /api/v1/external/wallets?page=0&size=20&q=acme Authorization: Bearer YOUR_API_TOKEN ``` | Query | Description | | ------ | ---------------------------------------------------------------- | | `page` | 0-based page index (default `0`) | | `size` | Page size (default 20, max 20) | | `q` | Optional search on `title` and `customerId` (Stripe Customer ID) | **Response `200`** — `ApiResponse` + Spring `Page`. See [Overview](/revos/api-reference#pagination-and-listget-shape). ```json { "requestId": "req-1", "success": true, "status": 200, "errors": [], "data": { "content": [ { "__type__": "Wallet", "Id": "5c7b9e31-2d4f-4a80-b6c3-9f1e8d0a7b52", "Title": "Acme prepaid wallet", "AccountId": "11111111-1111-1111-1111-111111111111", "CustomerId": "cus_NffrFeUfNV2Hib" } ], "totalElements": 1, "size": 20, "number": 0 } } ``` ### Get wallet ```http GET /api/v1/external/wallets/{walletId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `200`** ```json { "id": "5c7b9e31-2d4f-4a80-b6c3-9f1e8d0a7b52", "title": "Acme prepaid wallet", "accountId": "11111111-1111-1111-1111-111111111111", "currency": "USD", "unit": "USD", "balance": 1500.0, "availableBalance": 1450.0, "reservedBalance": 50.0, "frozenAmount": 0, "isActive": true, "approvalStatus": "Approved", "customerId": "cus_NffrFeUfNV2Hib", "enableDisableTopUp": true, "thresholdTopUpAmount": 100.0, "autoTopUpAmount": 500.0 } ``` ### Create wallet ```http POST /api/v1/external/wallets Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` Required fields: `title`, `accountId`. `accountId` must reference an existing billing account. `customerId` is the **Stripe Customer ID** (stored as Wallet `customer_id`). It is optional; when sent it must be a non-blank string (for example `cus_NffrFeUfNV2Hib`). A blank value returns `400`. **Request** ```json { "title": "Acme prepaid wallet", "accountId": "11111111-1111-1111-1111-111111111111", "customerId": "cus_NffrFeUfNV2Hib", "currency": "USD", "unit": "USD", "isActive": true, "balance": 0, "availableBalance": 0 } ``` ```bash curl -sS -X POST "https://YOUR_TENANT_HOST/api/v1/external/wallets" \ -H "Authorization: Bearer YOUR_API_TOKEN" \ -H "Content-Type: application/json" \ -d '{ "title": "Acme prepaid wallet", "accountId": "11111111-1111-1111-1111-111111111111", "currency": "USD", "isActive": true }' ``` **Response `201`** ```json { "id": "5c7b9e31-2d4f-4a80-b6c3-9f1e8d0a7b52", "title": "Acme prepaid wallet", "accountId": "11111111-1111-1111-1111-111111111111", "customerId": "cus_NffrFeUfNV2Hib", "currency": "USD", "unit": "USD", "isActive": true, "balance": 0, "availableBalance": 0 } ``` **Response `409`** on a duplicate `title`. ```json { "status": 409, "error": "Conflict", "message": "Wallet title already exists", "path": "uri=/api/v1/external/wallets" } ``` ### Update wallet ```http PUT /api/v1/external/wallets/{walletId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN ``` **Request** — turn on auto top-up. ```json { "title": "Acme prepaid wallet", "enableDisableTopUp": true, "thresholdTopUpAmount": 100.0, "autoTopUpAmount": 500.0 } ``` **Response `200`** ```json { "id": "5c7b9e31-2d4f-4a80-b6c3-9f1e8d0a7b52", "title": "Acme prepaid wallet", "accountId": "11111111-1111-1111-1111-111111111111", "currency": "USD", "isActive": true, "enableDisableTopUp": true, "thresholdTopUpAmount": 100.0, "autoTopUpAmount": 500.0 } ``` ### Delete wallet ```http DELETE /api/v1/external/wallets/{walletId} Authorization: Bearer YOUR_API_TOKEN ``` **Response `204`** — no body. --- # Assign role to user URL: /finops-api/users/assignUserRole *** title: Assign role to user full: true \_openapi: method: PUT route: /api/users/{id}/role toc: \[] structuredData: headings: \[] contents: * content: > Assigns an RBAC role to a user. This also auto-assigns the default access profile for the new role and reloads the RBAC permission cache. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Assigns an RBAC role to a user. This also auto-assigns the default access profile for the new role and reloads the RBAC permission cache. --- # Create user URL: /finops-api/users/createUser *** title: Create user full: true \_openapi: method: POST route: /api/users toc: \[] structuredData: headings: \[] contents: * content: Manually creates a new user in the organization. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Manually creates a new user in the organization. --- # Delete user URL: /finops-api/users/deleteUser *** title: Delete user full: true \_openapi: method: DELETE route: /api/users/{id} toc: \[] structuredData: headings: \[] contents: * content: > Permanently removes a user from the organization. This cascades to delete the user's governance settings (budget/rate limits), team memberships, access profiles, and OIDC sessions. Cannot delete yourself. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Permanently removes a user from the organization. This cascades to delete the user's governance settings (budget/rate limits), team memberships, access profiles, and OIDC sessions. Cannot delete yourself. --- # Get current user permissions URL: /finops-api/users/getCurrentUserPermissions *** title: Get current user permissions full: true \_openapi: method: GET route: /api/users/me/permissions toc: \[] structuredData: headings: \[] contents: * content: > Returns the RBAC permissions for the authenticated user. When SCIM is not enabled, returns full permissions for all resources. Otherwise returns the permissions associated with the user's assigned role. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the RBAC permissions for the authenticated user. When SCIM is not enabled, returns full permissions for all resources. Otherwise returns the permissions associated with the user's assigned role. --- # Get user's teams URL: /finops-api/users/getUserTeams *** title: Get user's teams full: true \_openapi: method: GET route: /api/users/{id}/teams toc: \[] structuredData: headings: \[] contents: * content: >- Returns the list of teams a user belongs to, including the membership source. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns the list of teams a user belongs to, including the membership source. --- # Get user's virtual keys by email URL: /finops-api/users/getUserVirtualKeysByEmail *** title: Get user's virtual keys by email full: true \_openapi: method: GET route: /api/users/email/{email}/virtual-keys toc: \[] structuredData: headings: \[] contents: * content: > **Enterprise only.** Returns all virtual keys associated with a user, looked up by email address. Returns an empty `virtual_keys` array when the user exists but has no virtual keys assigned. Intended for MDM and credential-helper integrations that need to resolve a user's keys without knowing their internal ID. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} **Enterprise only.** Returns all virtual keys associated with a user, looked up by email address. Returns an empty `virtual_keys` array when the user exists but has no virtual keys assigned. Intended for MDM and credential-helper integrations that need to resolve a user's keys without knowing their internal ID. --- # List users URL: /finops-api/users/listUsers *** title: List users full: true \_openapi: method: GET route: /api/users toc: \[] structuredData: headings: \[] contents: * content: Returns a paginated list of users with optional search. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Returns a paginated list of users with optional search. --- # Update user's team assignments URL: /finops-api/users/updateUserTeams *** title: Update user's team assignments full: true \_openapi: method: PUT route: /api/users/{id}/teams toc: \[] structuredData: headings: \[] contents: * content: > Replaces the user's manual team assignments. Synced team memberships (from SCIM providers) are preserved and cannot be removed via this endpoint. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Replaces the user's manual team assignments. Synced team memberships (from SCIM providers) are preserved and cannot be removed via this endpoint. --- # Delete a video generation job URL: /finops-api/videos/videoDelete *** title: Delete a video generation job full: true \_openapi: method: DELETE route: /v1/videos/{video_id} toc: \[] structuredData: headings: \[] contents: * content: | Deletes a video generation job and its associated assets. This operation cannot be undone. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Deletes a video generation job and its associated assets. This operation cannot be undone. --- # Download video content URL: /finops-api/videos/videoDownload *** title: Download video content full: true \_openapi: method: GET route: /v1/videos/{video_id}/content toc: \[] structuredData: headings: \[] contents: * content: | Downloads the binary content of a generated video. The video must have a status of "completed" to be downloadable. Returns the raw video file (typically MP4 format). *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Downloads the binary content of a generated video. The video must have a status of "completed" to be downloadable. Returns the raw video file (typically MP4 format). --- # Generate a video URL: /finops-api/videos/videoGeneration *** title: Generate a video full: true \_openapi: method: POST route: /v1/videos toc: \[] structuredData: headings: \[] contents: * content: > Creates a video generation job from a text prompt. This is an asynchronous operation that returns immediately with a job ID. Use the retrieve endpoint to check the status and get the video URL when generation is complete. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a video generation job from a text prompt. This is an asynchronous operation that returns immediately with a job ID. Use the retrieve endpoint to check the status and get the video URL when generation is complete. --- # List video generation jobs URL: /finops-api/videos/videoList *** title: List video generation jobs full: true \_openapi: method: GET route: /v1/videos toc: \[] structuredData: headings: \[] contents: * content: > Lists video generation jobs for a specific provider. Results are paginated and can be filtered using query parameters. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Lists video generation jobs for a specific provider. Results are paginated and can be filtered using query parameters. --- # Remix a video URL: /finops-api/videos/videoRemix *** title: Remix a video full: true \_openapi: method: POST route: /v1/videos/{video_id}/remix toc: \[] structuredData: headings: \[] contents: * content: > Creates a new video generation job by remixing an existing video with a new prompt. The source video must have a status of "completed" to be remixed. Returns a new video generation job that can be polled for completion. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Creates a new video generation job by remixing an existing video with a new prompt. The source video must have a status of "completed" to be remixed. Returns a new video generation job that can be polled for completion. --- # Retrieve a video generation job URL: /finops-api/videos/videoRetrieve *** title: Retrieve a video generation job full: true \_openapi: method: GET route: /v1/videos/{video_id} toc: \[] structuredData: headings: \[] contents: * content: > Retrieves the status and metadata for a video generation job. Use this endpoint to poll for completion status after creating a video generation job. When the status is "completed", the response will include a URL to download the video. *** {/* Generated from ai-gateway\/docs\/openapi — run: npm run generate-finops-api-docs */} Retrieves the status and metadata for a video generation job. Use this endpoint to poll for completion status after creating a video generation job. When the status is "completed", the response will include a URL to download the video. --- # Files and Batch API URL: /finops/integrations/anthropic-sdk/files-and-batch Upload files and create batch jobs for asynchronous processing using the Anthropic SDK through FinOps across multiple providers. *** title: "Files and Batch API" tag: "Beta" description: "Upload files and create batch jobs for asynchronous processing using the Anthropic SDK through FinOps across multiple providers." ----------------------------------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' ## Overview FinOps supports the Anthropic Files API and Batch API (via the `beta` namespace) with **cross-provider routing**. This means you can use the Anthropic SDK to manage files and batch jobs across multiple providers including Anthropic, OpenAI, and Gemini. The provider is specified using the `x-model-provider` header in `default_headers`. **Bedrock Limitation:** Bedrock batch operations require file-based input with S3 storage, which is not supported via the Anthropic SDK's inline batch API. For Bedrock batch operations, use the [Bedrock SDK](../bedrock-sdk/files-and-batch) directly. *** ## Client Setup In API Key section, you can either send virtual key or a dummy key to escape client side validation. ### Anthropic Provider (Default) ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key" ) ``` ### Cross-Provider Client To route requests to a different provider, set the `x-model-provider` header: ### OpenAI Provider ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "openai"} ) ``` ### Bedrock Provider ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "bedrock"} ) ``` Bedrock can be used for chat completions via the Anthropic SDK, but **batch operations are not supported**. Bedrock requires file-based batch input with S3 storage. Use the [Bedrock SDK](../bedrock-sdk/files-and-batch) for batch operations. ### Gemini Provider ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "gemini"} ) ``` *** ## Files API The Files API is accessed through the `beta.files` namespace. Note that file support varies by provider. ### Upload a File ### Anthropic Provider Upload a text file for use with Anthropic: ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key" ) # Upload a text file text_content = b"This is a test file for Files API integration." response = client.beta.files.upload( file=("test_upload.txt", text_content, "text/plain"), ) print(f"File ID: {response.id}") print(f"Filename: {response.filename}") ``` ### OpenAI Provider Upload a JSONL file for OpenAI batch processing: ```python import anthropic # Client configured for OpenAI provider client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "openai"} ) # Create JSONL content in OpenAI batch format jsonl_content = b'''{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Hello!"}], "max_tokens": 100}} {"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "How are you?"}], "max_tokens": 100}}''' response = client.beta.files.upload( file=("batch_input.jsonl", jsonl_content, "application/jsonl"), ) print(f"File ID: {response.id}") ``` ### List Files ### Anthropic Provider ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key" ) # List all files response = client.beta.files.list for file in response.data: print(f"File ID: {file.id}") print(f"Filename: {file.filename}") print(f"Size: {file.size} bytes") print("---") ``` ### OpenAI Provider ```python import anthropic # Client configured for OpenAI provider client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "openai"} ) # List all files from OpenAI response = client.beta.files.list for file in response.data: print(f"File ID: {file.id}, Name: {file.filename}") ``` ### Delete a File ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "openai"} # or omit for anthropic ) # Delete a file file_id = "file-abc123" response = client.beta.files.delete(file_id) print(f"Deleted file: {file_id}") ``` ### Download File Content Note: Anthropic only allows downloading files created by certain tools (like code execution). OpenAI allows downloading batch output files. ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "openai"} ) # Download file content file_id = "file-abc123" response = client.beta.files.download(file_id) content = response.text print(f"File content:\n{content}") ``` *** ## Batch API The Anthropic Batch API is accessed through `beta.messages.batches`. Anthropic's batch API uses **inline requests** rather than file uploads. ### Create a Batch with Inline Requests ### Anthropic Provider ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key" ) # Create batch with inline requests batch_requests = [ { "custom_id": "request-1", "params": { "model": "claude-3-sonnet-20240229", "max_tokens": 100, "messages": [ {"role": "user", "content": "What is 2+2?"} ] } }, { "custom_id": "request-2", "params": { "model": "claude-3-sonnet-20240229", "max_tokens": 100, "messages": [ {"role": "user", "content": "What is the capital of France?"} ] } } ] batch = client.beta.messages.batches.create(requests=batch_requests) print(f"Batch ID: {batch.id}") print(f"Status: {batch.processing_status}") ``` ### OpenAI Provider When routing to OpenAI, use OpenAI-compatible models: ```python import anthropic # Client configured for OpenAI provider client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "openai"} ) # Create batch with inline requests (using OpenAI models) batch_requests = [ { "custom_id": "request-1", "params": { "model": "gpt-4o-mini", "max_tokens": 100, "messages": [ {"role": "user", "content": "What is 2+2?"} ] } }, { "custom_id": "request-2", "params": { "model": "gpt-4o-mini", "max_tokens": 100, "messages": [ {"role": "user", "content": "What is the capital of France?"} ] } } ] batch = client.beta.messages.batches.create(requests=batch_requests) print(f"Batch ID: {batch.id}") print(f"Status: {batch.processing_status}") ``` ### Gemini Provider When routing to Gemini: ```python import anthropic # Client configured for Gemini provider client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "gemini"} ) # Create batch with inline requests (using Gemini models) batch_requests = [ { "custom_id": "request-1", "params": { "model": "gemini-1.5-flash", "max_tokens": 100, "messages": [ {"role": "user", "content": "What is 2+2?"} ] } }, { "custom_id": "request-2", "params": { "model": "gemini-1.5-flash", "max_tokens": 100, "messages": [ {"role": "user", "content": "What is the capital of France?"} ] } } ] batch = client.beta.messages.batches.create(requests=batch_requests) print(f"Batch ID: {batch.id}") print(f"Status: {batch.processing_status}") ``` **Bedrock Note:** Bedrock requires file-based batch creation with S3 storage. When routing to Bedrock from the Anthropic SDK, you'll need to use the Bedrock SDK directly for batch operations. See the [Bedrock SDK documentation](../bedrock-sdk/files-and-batch) for details. ### List Batches ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "anthropic"} # or "openai", "gemini" ) # List batches response = client.beta.messages.batches.list(limit=10) for batch in response.data: print(f"Batch ID: {batch.id}") print(f"Status: {batch.processing_status}") if batch.request_counts: print(f"Processing: {batch.request_counts.processing}") print(f"Succeeded: {batch.request_counts.succeeded}") print(f"Errored: {batch.request_counts.errored}") print("---") ``` ### Retrieve Batch Status ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "anthropic"} # or "openai", "gemini" ) # Retrieve batch status batch_id = "batch-abc123" batch = client.beta.messages.batches.retrieve(batch_id) print(f"Batch ID: {batch.id}") print(f"Status: {batch.processing_status}") if batch.request_counts: print(f"Processing: {batch.request_counts.processing}") print(f"Succeeded: {batch.request_counts.succeeded}") print(f"Errored: {batch.request_counts.errored}") ``` ### Cancel a Batch ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "anthropic"} # or "openai", "gemini" ) # Cancel batch batch_id = "batch-abc123" batch = client.beta.messages.batches.cancel(batch_id) print(f"Batch ID: {batch.id}") print(f"Status: {batch.processing_status}") # "canceling" or "ended" ``` ### Get Batch Results ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key" ) # Get batch results (only available after batch is completed) batch_id = "batch-abc123" results = client.beta.messages.batches.results(batch_id) # Iterate over results for result in results: print(f"Custom ID: {result.custom_id}") if result.result.type == "succeeded": message = result.result.message print(f"Response: {message.content[0].text}") elif result.result.type == "errored": print(f"Error: {result.result.error}") print("---") ``` *** ## End-to-End Workflows ### Anthropic Batch Workflow ```python import time import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key" ) # Step 1: Create batch with inline requests print("Step 1: Creating batch...") batch_requests = [ { "custom_id": "math-question", "params": { "model": "claude-3-sonnet-20240229", "max_tokens": 100, "messages": [{"role": "user", "content": "What is 15 * 7?"}] } }, { "custom_id": "geography-question", "params": { "model": "claude-3-sonnet-20240229", "max_tokens": 100, "messages": [{"role": "user", "content": "What is the largest ocean?"}] } } ] batch = client.beta.messages.batches.create(requests=batch_requests) print(f" Created batch: {batch.id}, status: {batch.processing_status}") # Step 2: Poll for completion print("Step 2: Polling batch status...") for i in range(20): batch = client.beta.messages.batches.retrieve(batch.id) print(f" Poll {i+1}: status = {batch.processing_status}") if batch.processing_status == "ended": print(" Batch completed!") break if batch.request_counts: print(f" Processing: {batch.request_counts.processing}") print(f" Succeeded: {batch.request_counts.succeeded}") time.sleep(5) # Step 3: Verify batch is in list print("Step 3: Verifying batch in list...") batch_list = client.beta.messages.batches.list(limit=20) batch_ids = [b.id for b in batch_list.data] assert batch.id in batch_ids, f"Batch {batch.id} should be in list" print(f" Verified batch {batch.id} is in list") # Step 4: Get results (if completed) if batch.processing_status == "ended": print("Step 4: Getting results...") try: results = client.beta.messages.batches.results(batch.id) for result in results: print(f" {result.custom_id}: ", end="") if result.result.type == "succeeded": print(result.result.message.content[0].text[:50] + "...") else: print(f"Error: {result.result.error}") except Exception as e: print(f" Results not yet available: {e}") print(f"\nSuccess! Batch {batch.id} workflow completed.") ``` ### Cross-Provider Batch Workflow (OpenAI via Anthropic SDK) ```python import time import anthropic # Create client with OpenAI provider header client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="virtual-key-or-dummy-key", default_headers={"x-model-provider": "openai"} ) # Step 1: Create batch with OpenAI models print("Step 1: Creating batch for OpenAI provider...") batch_requests = [ { "custom_id": "openai-request-1", "params": { "model": "gpt-4o-mini", "max_tokens": 100, "messages": [{"role": "user", "content": "Explain AI in one sentence."}] } }, { "custom_id": "openai-request-2", "params": { "model": "gpt-4o-mini", "max_tokens": 100, "messages": [{"role": "user", "content": "What is machine learning?"}] } } ] batch = client.beta.messages.batches.create(requests=batch_requests) print(f" Created batch: {batch.id}, status: {batch.processing_status}") # Step 2: Poll for completion print("Step 2: Polling batch status...") for i in range(10): batch = client.beta.messages.batches.retrieve(batch.id) print(f" Poll {i+1}: status = {batch.processing_status}") if batch.processing_status in ["ended", "completed"]: break time.sleep(5) print(f"\nSuccess! Cross-provider batch {batch.id} completed via Anthropic SDK.") ``` *** ## Provider-Specific Notes | Provider | Header Value | File Upload | Batch Type | Models | | ------------- | ------------------- | ----------------- | --------------- | --------------------- | | **Anthropic** | `anthropic` or omit | ✅ Beta API | Inline requests | `claude-3-*` | | **OpenAI** | `openai` | ✅ Beta API | Inline requests | `gpt-4o-*`, `gpt-4-*` | | **Gemini** | `gemini` | ✅ Beta API | Inline requests | `gemini-1.5-*` | | **Bedrock** | `bedrock` | ❌ Use Bedrock SDK | File-based (S3) | `anthropic.claude-*` | *** ## Next Steps * **[Overview](/finops/integrations/overview)** - Anthropic SDK integration basics * **[Configuration](../../finops/model-provider)** - FinOps setup and configuration * **[Core Features](../../features/)** - Governance, semantic caching, and more --- # Overview URL: /finops/integrations/anthropic-sdk Use FinOps as a drop-in replacement for Anthropic API with full compatibility and enhanced features. *** title: "Overview" description: "Use FinOps as a drop-in replacement for Anthropic API with full compatibility and enhanced features." ------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' ## Overview FinOps provides complete Anthropic API compatibility through protocol adaptation. The integration handles request transformation, response normalization, and error mapping between Anthropic's Messages API specification and FinOps's internal processing pipeline. This integration enables you to utilize FinOps's features like governance, load balancing, semantic caching, multi-provider support, and more, all while preserving your existing Anthropic SDK-based architecture. **Endpoint:** `/anthropic` **Enabling the beta header**: Anthropic frequently uses the `anthropic-beta` header to gate access to new features. Clients like Vercels AI SDK use these. FinOps will block unrecognized headers by default for security purposes. To enable the beta header for full compatability, add `anthropic-beta` to the AllowList under Settings -> Client Settings in the UI. *** ## Setup ### Python ```python {5} import anthropic # Configure client to use FinOps client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="dummy-key" # Keys handled by FinOps ) # Make requests as usual response = client.messages.create( model="claude-3-sonnet-20240229", max_tokens=1000, messages=[{"role": "user", "content": "Hello!"}] ) print(response.content[0].text) ``` ### JavaScript ```javascript {5} import Anthropic from "@anthropic-ai/sdk"; // Configure client to use FinOps const anthropic = new Anthropic({ baseURL: "{AI_GATEWAY_URL}/anthropic", apiKey: "dummy-key", // Keys handled by FinOps }); // Make requests as usual const response = await anthropic.messages.create({ model: "claude-3-sonnet-20240229", max_tokens: 1000, messages: [{ role: "user", content: "Hello!" }], }); console.log(response.content[0].text); ``` *** ## Provider/Model Usage Examples Use multiple providers through the same Anthropic SDK format by prefixing model names with the provider: ### Python ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="dummy-key" ) # Anthropic models (default) anthropic_response = client.messages.create( model="claude-3-sonnet-20240229", max_tokens=1000, messages=[{"role": "user", "content": "Hello from Claude!"}] ) # OpenAI models via Anthropic SDK format openai_response = client.messages.create( model="openai/gpt-4o-mini", max_tokens=1000, messages=[{"role": "user", "content": "Hello from OpenAI!"}] ) # Google Vertex models via Anthropic SDK format vertex_response = client.messages.create( model="vertex/gemini-pro", max_tokens=1000, messages=[{"role": "user", "content": "Hello from Gemini!"}] ) # Azure models azure_response = client.messages.create( model="azure/gpt-4o", max_tokens=1000, messages=[{"role": "user", "content": "Hello from Azure!"}] ) # Local Ollama models ollama_response = client.messages.create( model="ollama/llama3.1:8b", max_tokens=1000, messages=[{"role": "user", "content": "Hello from Ollama!"}] ) ``` ### JavaScript ```javascript import Anthropic from "@anthropic-ai/sdk"; const anthropic = new Anthropic({ baseURL: "{AI_GATEWAY_URL}/anthropic", apiKey: "dummy-key", }); // Anthropic models (default) const anthropicResponse = await anthropic.messages.create({ model: "claude-3-sonnet-20240229", max_tokens: 1000, messages: [{ role: "user", content: "Hello from Claude!" }], }); // OpenAI models via Anthropic SDK format const openaiResponse = await anthropic.messages.create({ model: "openai/gpt-4o-mini", max_tokens: 1000, messages: [{ role: "user", content: "Hello from OpenAI!" }], }); // Google Vertex models via Anthropic SDK format const vertexResponse = await anthropic.messages.create({ model: "vertex/gemini-pro", max_tokens: 1000, messages: [{ role: "user", content: "Hello from Gemini!" }], }); // Azure models const azureResponse = await anthropic.messages.create({ model: "azure/gpt-4o", max_tokens: 1000, messages: [{ role: "user", content: "Hello from Azure!" }], }); // Local Ollama models const ollamaResponse = await anthropic.messages.create({ model: "ollama/llama3.1:8b", max_tokens: 1000, messages: [{ role: "user", content: "Hello from Ollama!" }], }); ``` *** ## Adding Custom Headers Pass custom headers required by FinOps plugins (like governance, telemetry, etc.): ### Python ```python import anthropic client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="dummy-key", default_headers={ "x-bf-vk": "vk_12345", # Virtual key for governance } ) response = client.messages.create( model="claude-3-sonnet-20240229", max_tokens=1000, messages=[{"role": "user", "content": "Hello with custom headers!"}] ) ``` ### JavaScript ```javascript import Anthropic from "@anthropic-ai/sdk"; const anthropic = new Anthropic({ baseURL: "{AI_GATEWAY_URL}/anthropic", apiKey: "dummy-key", defaultHeaders: { "x-bf-vk": "vk_12345", // Virtual key for governance }, }); const response = await anthropic.messages.create({ model: "claude-3-sonnet-20240229", max_tokens: 1000, messages: [{ role: "user", content: "Hello with custom headers!" }], }); ``` *** ## Async Inference Submit inference requests asynchronously and poll for results later using the `x-bf-async` header. This is useful for long-running requests where you don't want to hold a connection open. See [Async Inference](../../features/async-inference) for full details. Async inference requires a [Logs Store](../../finops/telemetry) to be configured and is not compatible with streaming. ### Messages ### Python ```python import anthropic import time client = anthropic.Anthropic( base_url="{AI_GATEWAY_URL}/anthropic", api_key="dummy-key" ) # Submit async request initial = client.messages.create( model="anthropic/claude-sonnet-4-20250514", max_tokens=256, messages=[{"role": "user", "content": "Tell me a short story."}], extra_headers={"x-bf-async": "true"} ) # If content is present, the request completed synchronously if initial.content: print(initial.content[0].text) else: # Poll until completed while True: time.sleep(2) poll = client.messages.create( model="anthropic/claude-sonnet-4-20250514", max_tokens=256, messages=[{"role": "user", "content": "Tell me a short story."}], extra_headers={"x-bf-async-id": initial.id} ) if poll.content: print(poll.content[0].text) break ``` ### JavaScript ```javascript import Anthropic from "@anthropic-ai/sdk"; const anthropic = new Anthropic({ baseURL: "{AI_GATEWAY_URL}/anthropic", apiKey: "dummy-key", }); // Submit async request const initial = await anthropic.messages.create( { model: "anthropic/claude-sonnet-4-20250514", max_tokens: 256, messages: [{ role: "user", content: "Tell me a short story." }], }, { headers: { "x-bf-async": "true" } } ); // If content is present, the request completed synchronously if (initial.content?.length > 0) { console.log(initial.content[0].text); } else { // Poll until completed while (true) { await new Promise((r) => setTimeout(r, 2000)); const poll = await anthropic.messages.create( { model: "anthropic/claude-sonnet-4-20250514", max_tokens: 256, messages: [{ role: "user", content: "Tell me a short story." }], }, { headers: { "x-bf-async-id": initial.id } } ); if (poll.content?.length > 0) { console.log(poll.content[0].text); break; } } } ``` ### Async Headers | Header | Description | | -------------------------------------- | ---------------------------------------------------------------------- | | `x-bf-async: true` | Submit the request as an async job. Returns immediately with a job ID. | | `x-bf-async-id: ` | Poll for results of a previously submitted async job. | | `x-bf-async-job-result-ttl: ` | Override the default result TTL (default: 3600s). | *** ## Supported Features The Anthropic integration supports all features that are available in both the Anthropic SDK and FinOps core functionality. If the Anthropic SDK supports a feature and FinOps supports it, the integration will work seamlessly. *** ## Next Steps * **[Files and Batch API](/finops/integrations/files-and-batch)** - File uploads and batch processing * **[OpenAI SDK](../openai-sdk/overview)** - GPT integration patterns * **[Google GenAI SDK](../genai-sdk)** - Gemini integration patterns * **[Configuration](../../finops/getting-started)** - FinOps setup and configuration * **[Core Features](../../features/)** - Advanced FinOps capabilities --- # Files and Batch API URL: /finops/integrations/bedrock-sdk/files-and-batch Manage S3-based files and batch inference jobs using the AWS Bedrock SDK (boto3) through FinOps across multiple providers. *** title: "Files and Batch API" description: "Manage S3-based files and batch inference jobs using the AWS Bedrock SDK (boto3) through FinOps across multiple providers." tag: "Beta" ----------- import { Callout } from 'fumadocs-ui/components/callout' ## Overview FinOps supports AWS Bedrock's Files and Batch APIs with **cross-provider routing**. This means you can use boto3 to manage files and batch jobs across multiple providers including Bedrock, OpenAI, and Gemini. For Bedrock SDK: * **Files** are managed through an S3-compatible API * **Batches** are managed through the Bedrock service API * **Provider routing** is done via the `x-model-provider` header **Anthropic Limitation:** Anthropic does not support file upload via the S3-compatible API. For Anthropic batch operations, use the [Anthropic SDK](../anthropic-sdk/files-and-batch) with inline requests instead. *** ## Client Setup ### Default Bedrock Client ```python import boto3 # S3 client for file operations s3_client = boto3.client( "s3", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) # Bedrock client for batch operations bedrock_client = boto3.client( "bedrock", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock", ) ``` ### Cross-Provider Client Setup To route requests to different providers, add the `x-model-provider` header using boto3 events: ### Bedrock Provider (Default) ```python import boto3 def add_bedrock_header(request, **kwargs): request.headers["x-model-provider"] = "bedrock" # S3 client for Bedrock files s3_client = boto3.client( "s3", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_bedrock_header) # Bedrock client for batches bedrock_client = boto3.client( "bedrock", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_bedrock_header) ``` ### OpenAI Provider ```python import boto3 def add_openai_header(request, **kwargs): request.headers["x-model-provider"] = "openai" # S3 client for OpenAI files s3_client = boto3.client( "s3", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_openai_header) # Bedrock client for OpenAI batches bedrock_client = boto3.client( "bedrock", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_openai_header) ``` ### Anthropic Provider Anthropic does not support S3-based file uploads. For Anthropic operations, use the [Anthropic SDK](../anthropic-sdk/files-and-batch) with inline batch requests instead. ```python import boto3 def add_anthropic_header(request, **kwargs): request.headers["x-model-provider"] = "anthropic" # Note: File operations are NOT supported for Anthropic # Use Anthropic SDK with inline requests instead # Bedrock client for Anthropic (limited to non-batch operations) bedrock_client = boto3.client( "bedrock", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_anthropic_header) ``` ### Gemini Provider ```python import boto3 def add_gemini_header(request, **kwargs): request.headers["x-model-provider"] = "gemini" # S3 client for Gemini files s3_client = boto3.client( "s3", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_gemini_header) # Bedrock client for Gemini batches bedrock_client = boto3.client( "bedrock", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_gemini_header) ``` ### Helper Function for Provider-Specific Clients ```python import boto3 def create_provider_header_handler(provider: str): """Create a header handler function for a specific provider""" def add_provider_header(request, **kwargs): request.headers["x-model-provider"] = provider return add_provider_header def get_provider_s3_client(provider: str): """Create S3 client with x-model-provider header""" client = boto3.client( "s3", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) client.meta.events.register("before-send", create_provider_header_handler(provider)) return client def get_provider_bedrock_client(provider: str): """Create Bedrock batch client with x-model-provider header""" client = boto3.client( "bedrock", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock", ) client.meta.events.register("before-send", create_provider_header_handler(provider)) return client ``` *** ## Files API (S3-Compatible) Files are managed through FinOps's S3-compatible endpoint. ### Upload a File ### Bedrock Provider ```python import boto3 import json import time def add_bedrock_header(request, **kwargs): request.headers["x-model-provider"] = "bedrock" s3_client = boto3.client( "s3", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_bedrock_header) # Create JSONL content for Bedrock batch format def create_bedrock_batch_jsonl(model_id: str, num_requests: int = 2) -> str: lines = [] for i in range(num_requests): record = { "recordId": f"request-{i+1}", "modelInput": { "messages": [ { "role": "user", "content": [ {"text": f"Hello, this is test message {i+1}. Say hi back briefly."} ], } ], "inferenceConfig": {"maxTokens": 100}, }, } lines.append(json.dumps(record)) return "\n".join(lines) # Create content jsonl_content = create_bedrock_batch_jsonl("anthropic.claude-3-sonnet-20240229-v1:0") # Upload to S3 s3_bucket = "your-s3-bucket" s3_key = f"finops-batch-input/batch_input_{int(time.time)}.jsonl" response = s3_client.put_object( Bucket=s3_bucket, Key=s3_key, Body=jsonl_content.encode, ContentType="application/jsonl", ) # Extract file ID from ETag header file_id = response.get("ETag", "").strip('"') print(f"Uploaded file ID: {file_id}") print(f"S3 URI: s3://{s3_bucket}/{s3_key}") ``` ### OpenAI Provider **No S3 configuration required.** Files are stored in OpenAI's native storage. The bucket/key values are identifiers used by FinOps for routing. ```python import boto3 import json import time def add_openai_header(request, **kwargs): request.headers["x-model-provider"] = "openai" s3_client = boto3.client( "s3", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_openai_header) # Create JSONL content for OpenAI batch format def create_openai_batch_jsonl(model_id: str, num_requests: int = 2) -> str: lines = [] for i in range(num_requests): record = { "custom_id": f"request-{i+1}", "method": "POST", "url": "/v1/chat/completions", "body": { "model": model_id, "messages": [ {"role": "user", "content": f"Hello, this is test message {i+1}. Say hi back briefly."} ], "max_tokens": 100, }, } lines.append(json.dumps(record)) return "\n".join(lines) # Create content jsonl_content = create_openai_batch_jsonl("gpt-4o-mini") # Upload file (bucket/key are routing identifiers, not actual S3 paths) response = s3_client.put_object( Bucket="openai-files", Key=f"batch_input_{int(time.time)}.jsonl", Body=jsonl_content.encode, ContentType="application/jsonl", ) # Extract file ID from ETag header file_id = response.get("ETag", "").strip('"') print(f"Uploaded file ID: {file_id}") ``` ### Gemini Provider **No S3 configuration required.** Files are stored in Google Cloud Storage. The bucket/key values are identifiers used by FinOps for routing. ```python import boto3 import json import time def add_gemini_header(request, **kwargs): request.headers["x-model-provider"] = "gemini" s3_client = boto3.client( "s3", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_gemini_header) # Create JSONL content for Gemini batch format def create_gemini_batch_jsonl(model_id: str, num_requests: int = 2) -> str: lines = [] for i in range(num_requests): record = { "request": { "contents": [ { "role": "user", "parts": [ {"text": f"Hello, this is test message {i+1}. Say hi back briefly."} ], } ], "generationConfig": {"maxOutputTokens": 100}, }, "metadata": {"key": f"request-{i+1}"}, } lines.append(json.dumps(record)) return "\n".join(lines) # Create content jsonl_content = create_gemini_batch_jsonl("gemini-1.5-flash") # Upload file (bucket/key are routing identifiers, not actual S3 paths) response = s3_client.put_object( Bucket="gemini-files", Key=f"batch_input_{int(time.time)}.jsonl", Body=jsonl_content.encode, ContentType="application/jsonl", ) file_id = response.get("ETag", "").strip('"') print(f"Uploaded file ID: {file_id}") ``` ### List Files For **OpenAI** and **Gemini**, use any bucket name as an identifier-files are stored in the provider's native storage and listed by file ID. ```python import boto3 def add_provider_header(request, **kwargs): request.headers["x-model-provider"] = "bedrock" s3_client = boto3.client( "s3", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_provider_header) # List files (S3 bucket required for Bedrock only) s3_bucket = "your-s3-bucket" response = s3_client.list_objects_v2( Bucket=s3_bucket, Prefix="finops-batch-input/" ) if "Contents" in response: for obj in response["Contents"]: print(f"Key: {obj['Key']}") print(f"Size: {obj['Size']} bytes") print(f"Last Modified: {obj['LastModified']}") print("---") ``` ### Retrieve File Metadata ```python import boto3 def add_provider_header(request, **kwargs): request.headers["x-model-provider"] = "bedrock" s3_client = boto3.client( "s3", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_provider_header) # Retrieve file metadata (HEAD request) # For OpenAI/Gemini: use any bucket name, file_id from upload s3_bucket = "your-s3-bucket" s3_key = "finops-batch-input/batch_input.jsonl" file_id = "abc123" # ETag from upload response = s3_client.head_object( Bucket=s3_bucket, Key=s3_key, IfMatch=file_id ) print(f"Content Length: {response['ContentLength']} bytes") print(f"Content Type: {response['ContentType']}") print(f"ETag (File ID): {response['ETag']}") ``` ### Delete a File ```python import boto3 def add_provider_header(request, **kwargs): request.headers["x-model-provider"] = "bedrock" s3_client = boto3.client( "s3", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_provider_header) # Delete file # For OpenAI/Gemini: use any bucket name, file_id from upload s3_bucket = "your-s3-bucket" s3_key = "finops-batch-input/batch_input.jsonl" file_id = "abc123" s3_client.delete_object( Bucket=s3_bucket, Key=s3_key, IfMatch=file_id ) print(f"Deleted file: {s3_key}") ``` ### Download File Content File content download is **only supported for Bedrock**. For OpenAI and Gemini, use their native SDKs to download file content. ```python import boto3 def add_provider_header(request, **kwargs): request.headers["x-model-provider"] = "bedrock" s3_client = boto3.client( "s3", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_provider_header) # Download file content (Bedrock only) s3_bucket = "your-s3-bucket" s3_key = "finops-batch-input/batch_input.jsonl" file_id = "abc123" response = s3_client.get_object( Bucket=s3_bucket, Key=s3_key, IfMatch=file_id ) content = response["Body"].read.decode("utf-8") print(f"File content:\n{content}") ``` *** ## Batch API The Bedrock Batch API uses `create_model_invocation_job` and related methods. ### Create a Batch Job ### Bedrock Provider ```python import boto3 import time def add_bedrock_header(request, **kwargs): request.headers["x-model-provider"] = "bedrock" bedrock_client = boto3.client( "bedrock", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_bedrock_header) # Configuration s3_bucket = "your-s3-bucket" model_id = "anthropic.claude-3-sonnet-20240229-v1:0" # Input/output URIs (file should already be uploaded) input_uri = f"s3://{s3_bucket}/finops-batch-input/batch_input.jsonl" output_uri = f"s3://{s3_bucket}/finops-batch-output/" # Create batch job response = bedrock_client.create_model_invocation_job( jobName=f"finops-batch-{int(time.time)}", modelId=model_id, inputDataConfig={ "s3InputDataConfig": { "s3Uri": input_uri, "s3InputFormat": "JSONL" } }, outputDataConfig={ "s3OutputDataConfig": { "s3Uri": output_uri } }, tags=[ {"key": "endpoint", "value": "/v1/chat/completions"}, {"key": "source", "value": "finops-docs"}, ], ) job_arn = response["jobArn"] print(f"Created batch job: {job_arn}") ``` ### OpenAI Provider **No S3 or IAM configuration required.** Files are stored in OpenAI's native storage. The S3 URIs are routing identifiers used by FinOps. ```python import boto3 import time def add_openai_header(request, **kwargs): request.headers["x-model-provider"] = "openai" bedrock_client = boto3.client( "bedrock", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_openai_header) # Configuration (no S3 bucket or IAM role needed) model_id = "gpt-4o-mini" file_id = "file-abc123" # File ID from upload step # Create batch job response = bedrock_client.create_model_invocation_job( jobName=f"openai-batch-{int(time.time)}", modelId=model_id, roleArn="not-required-for-openai", inputDataConfig={ "s3InputDataConfig": { "s3Uri": f"s3://openai-files/{file_id}", # Routing identifier "s3InputFormat": "JSONL" } }, outputDataConfig={ "s3OutputDataConfig": { "s3Uri": "s3://openai-output/" } }, tags=[ {"key": "endpoint", "value": "/v1/chat/completions"}, {"key": "file_id", "value": file_id}, ], ) job_arn = response["jobArn"] print(f"Created OpenAI batch job: {job_arn}") ``` ### Gemini Provider **No S3 or IAM configuration required.** Files are stored in Google Cloud Storage. The S3 URIs are routing identifiers used by FinOps. ```python import boto3 import time def add_gemini_header(request, **kwargs): request.headers["x-model-provider"] = "gemini" bedrock_client = boto3.client( "bedrock", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_gemini_header) # Configuration (no S3 bucket or IAM role needed) model_id = "gemini-1.5-flash" file_id = "file-xyz789" # File ID from upload step # Create batch job response = bedrock_client.create_model_invocation_job( jobName=f"gemini-batch-{int(time.time)}", modelId=model_id, roleArn="not-required-for-gemini", inputDataConfig={ "s3InputDataConfig": { "s3Uri": f"s3://gemini-files/{file_id}", # Routing identifier "s3InputFormat": "JSONL" } }, outputDataConfig={ "s3OutputDataConfig": { "s3Uri": "s3://gemini-output/" } }, ) job_arn = response["jobArn"] print(f"Created Gemini batch job: {job_arn}") ``` **Anthropic Note:** Anthropic prefers inline batch requests rather than file-based batching. When targeting Anthropic from the Bedrock SDK, consider using the [Anthropic SDK](../anthropic-sdk/files-and-batch) directly for better compatibility. ### List Batch Jobs ```python import boto3 def add_provider_header(request, **kwargs): request.headers["x-model-provider"] = "bedrock" # or "gemini" bedrock_client = boto3.client( "bedrock", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_provider_header) # List batch jobs response = bedrock_client.list_model_invocation_jobs(maxResults=10) if "invocationJobSummaries" in response: for job in response["invocationJobSummaries"]: print(f"Job ARN: {job['jobArn']}") print(f"Job Name: {job['jobName']}") print(f"Status: {job['status']}") print(f"Model ID: {job.get('modelId', 'N/A')}") print("---") ``` ### Retrieve Batch Job Status ```python import boto3 def add_provider_header(request, **kwargs): request.headers["x-model-provider"] = "bedrock" bedrock_client = boto3.client( "bedrock", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_provider_header) # Get batch job status job_arn = "arn:aws:bedrock:us-west-2:123456789:model-invocation-job/abc123" response = bedrock_client.get_model_invocation_job(jobIdentifier=job_arn) print(f"Job ARN: {response['jobArn']}") print(f"Job Name: {response['jobName']}") print(f"Status: {response['status']}") print(f"Model ID: {response['modelId']}") if response["status"] == "Completed" and "statistics" in response: stats = response["statistics"] print(f"Total Records: {stats.get('totalRecordCount', 'N/A')}") print(f"Successful: {stats.get('successfulRecordCount', 'N/A')}") print(f"Failed: {stats.get('failedRecordCount', 'N/A')}") ``` ### Stop a Batch Job ```python import boto3 def add_provider_header(request, **kwargs): request.headers["x-model-provider"] = "bedrock" bedrock_client = boto3.client( "bedrock", region_name="us-west-2", endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_provider_header) # Stop batch job job_arn = "arn:aws:bedrock:us-west-2:123456789:model-invocation-job/abc123" bedrock_client.stop_model_invocation_job(jobIdentifier=job_arn) print(f"Stopped job: {job_arn}") ``` *** ## End-to-End Batch Workflow ### Bedrock Provider ```python import boto3 import json import time # Configuration region = "us-west-2" s3_bucket = "your-s3-bucket" model_id = "anthropic.claude-3-sonnet-20240229-v1:0" provider = "bedrock" # Provider header handler def add_provider_header(request, **kwargs): request.headers["x-model-provider"] = provider # Setup clients s3_client = boto3.client( "s3", region_name=region, endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_provider_header) bedrock_client = boto3.client( "bedrock", region_name=region, endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_provider_header) # Step 1: Create JSONL content print("Step 1: Creating batch input file...") def create_batch_jsonl(num_requests: int) -> str: lines = [] for i in range(num_requests): record = { "recordId": f"request-{i+1}", "modelInput": { "messages": [ { "role": "user", "content": [{"text": f"What is {i+1} + {i+1}? Answer briefly."}], } ], "inferenceConfig": {"maxTokens": 100}, }, } lines.append(json.dumps(record)) return "\n".join(lines) jsonl_content = create_batch_jsonl(num_requests=3) # Step 2: Upload input file to S3 print("Step 2: Uploading input file to S3...") timestamp = int(time.time) s3_key = f"finops-batch-input/batch_{timestamp}.jsonl" upload_response = s3_client.put_object( Bucket=s3_bucket, Key=s3_key, Body=jsonl_content.encode, ContentType="application/jsonl", ) file_id = upload_response.get("ETag", "").strip('"') input_uri = f"s3://{s3_bucket}/{s3_key}" print(f" Uploaded: {input_uri}") # Step 3: Create batch job print("Step 3: Creating batch job...") output_uri = f"s3://{s3_bucket}/finops-batch-output/" job_response = bedrock_client.create_model_invocation_job( jobName=f"finops-e2e-{timestamp}", modelId=model_id, inputDataConfig={ "s3InputDataConfig": {"s3Uri": input_uri, "s3InputFormat": "JSONL"} }, outputDataConfig={ "s3OutputDataConfig": {"s3Uri": output_uri} }, tags=[ {"key": "endpoint", "value": "/v1/chat/completions"}, {"key": "file_id", "value": file_id}, ], ) job_arn = job_response["jobArn"] print(f" Created job: {job_arn}") # Step 4: Poll for completion print("Step 4: Polling job status...") for i in range(20): status_response = bedrock_client.get_model_invocation_job(jobIdentifier=job_arn) status = status_response["status"] print(f" Poll {i+1}: status = {status}") if status in ["Completed", "Failed", "Stopped"]: print(f" Job reached terminal state: {status}") if status == "Completed" and "statistics" in status_response: stats = status_response["statistics"] print(f" Total: {stats.get('totalRecordCount')}") print(f" Successful: {stats.get('successfulRecordCount')}") print(f" Failed: {stats.get('failedRecordCount')}") break time.sleep(10) # Step 5: Verify job is in list print("Step 5: Verifying job in list...") list_response = bedrock_client.list_model_invocation_jobs(maxResults=20) job_arns = [job["jobArn"] for job in list_response.get("invocationJobSummaries", [])] assert job_arn in job_arns, f"Job {job_arn} should be in list" print(f" Verified job is in list") print(f"\nSuccess! Batch workflow completed for job {job_arn}") ``` ### OpenAI Provider **No S3 configuration required.** Files are stored in OpenAI's native storage. The bucket/key values are routing identifiers used by FinOps. ```python import boto3 import json import time # Configuration (no S3 bucket needed for OpenAI) region = "us-west-2" model_id = "gpt-4o-mini" provider = "openai" # Provider header handler def add_provider_header(request, **kwargs): request.headers["x-model-provider"] = provider # Setup clients s3_client = boto3.client( "s3", region_name=region, endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_provider_header) bedrock_client = boto3.client( "bedrock", region_name=region, endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_provider_header) # Step 1: Create OpenAI JSONL content print("Step 1: Creating OpenAI batch input file...") def create_openai_jsonl(num_requests: int) -> str: lines = [] for i in range(num_requests): record = { "custom_id": f"request-{i+1}", "method": "POST", "url": "/v1/chat/completions", "body": { "model": model_id, "messages": [ {"role": "user", "content": f"What is {i+1} + {i+1}? Answer briefly."} ], "max_tokens": 100, }, } lines.append(json.dumps(record)) return "\n".join(lines) jsonl_content = create_openai_jsonl(num_requests=3) # Step 2: Upload input file (bucket/key are routing identifiers) print("Step 2: Uploading input file...") timestamp = int(time.time) upload_response = s3_client.put_object( Bucket="openai-files", # Routing identifier, not actual S3 Key=f"batch_{timestamp}.jsonl", Body=jsonl_content.encode, ContentType="application/jsonl", ) file_id = upload_response.get("ETag", "").strip('"') print(f" Uploaded file ID: {file_id}") # Step 3: Create batch job print("Step 3: Creating OpenAI batch job...") job_response = bedrock_client.create_model_invocation_job( jobName=f"openai-e2e-{timestamp}", modelId=model_id, roleArn="not-required-for-openai", # Not used for OpenAI inputDataConfig={ "s3InputDataConfig": {"s3Uri": f"s3://openai-files/{file_id}", "s3InputFormat": "JSONL"} }, outputDataConfig={ "s3OutputDataConfig": {"s3Uri": "s3://openai-output/"} }, tags=[ {"key": "endpoint", "value": "/v1/chat/completions"}, {"key": "file_id", "value": file_id}, ], ) job_arn = job_response["jobArn"] print(f" Created job: {job_arn}") # Step 4: Poll for completion print("Step 4: Polling job status...") for i in range(20): status_response = bedrock_client.get_model_invocation_job(jobIdentifier=job_arn) status = status_response["status"] print(f" Poll {i+1}: status = {status}") if status in ["Completed", "Failed", "Stopped"]: print(f" Job reached terminal state: {status}") break time.sleep(10) print(f"\nSuccess! OpenAI batch workflow completed for job {job_arn}") ``` ### Gemini Provider **No S3 configuration required.** Files are stored in Google Cloud Storage. The bucket/key values are routing identifiers used by FinOps. ```python import boto3 import json import time # Configuration (no S3 bucket needed for Gemini) region = "us-west-2" model_id = "gemini-1.5-flash" provider = "gemini" # Provider header handler def add_provider_header(request, **kwargs): request.headers["x-model-provider"] = provider # Setup clients s3_client = boto3.client( "s3", region_name=region, endpoint_url="{AI_GATEWAY_URL}/bedrock/files", ) s3_client.meta.events.register("before-send", add_provider_header) bedrock_client = boto3.client( "bedrock", region_name=region, endpoint_url="{AI_GATEWAY_URL}/bedrock", ) bedrock_client.meta.events.register("before-send", add_provider_header) # Step 1: Create Gemini JSONL content print("Step 1: Creating Gemini batch input file...") def create_gemini_jsonl(num_requests: int) -> str: lines = [] for i in range(num_requests): record = { "request": { "contents": [ { "role": "user", "parts": [{"text": f"What is {i+1} + {i+1}? Answer briefly."}], } ], "generationConfig": {"maxOutputTokens": 100}, }, "metadata": {"key": f"request-{i+1}"}, } lines.append(json.dumps(record)) return "\n".join(lines) jsonl_content = create_gemini_jsonl(num_requests=3) # Step 2: Upload input file (bucket/key are routing identifiers) print("Step 2: Uploading input file...") timestamp = int(time.time) upload_response = s3_client.put_object( Bucket="gemini-files", # Routing identifier, not actual S3 Key=f"batch_{timestamp}.jsonl", Body=jsonl_content.encode, ContentType="application/jsonl", ) file_id = upload_response.get("ETag", "").strip('"') print(f" Uploaded file ID: {file_id}") # Step 3: Create batch job print("Step 3: Creating Gemini batch job...") job_response = bedrock_client.create_model_invocation_job( jobName=f"gemini-e2e-{timestamp}", modelId=model_id, roleArn="not-required-for-gemini", # Not used for Gemini inputDataConfig={ "s3InputDataConfig": {"s3Uri": f"s3://gemini-files/{file_id}", "s3InputFormat": "JSONL"} }, outputDataConfig={ "s3OutputDataConfig": {"s3Uri": "s3://gemini-output/"} }, ) job_arn = job_response["jobArn"] print(f" Created job: {job_arn}") # Step 4: Poll for completion (same as Bedrock) # ... (same polling logic as above) print(f"\nSuccess! Gemini batch workflow completed.") ``` *** ## JSONL Format Reference ### Bedrock Format ```json {"recordId": "request-1", "modelInput": {"messages": [{"role": "user", "content": [{"text": "Hello!"}]}], "inferenceConfig": {"maxTokens": 100}}} ``` ### OpenAI Format ```json {"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Hello!"}], "max_tokens": 100}} ``` ### Gemini Format ```json {"request": {"contents": [{"role": "user", "parts": [{"text": "Hello!"}]}], "generationConfig": {"maxOutputTokens": 100}}, "metadata": {"key": "request-1"}} ``` *** ## Provider-Specific Notes | Provider | Header Value | File Storage | S3 Config Required | | ------------- | ------------ | -------------------- | ------------------ | | **Bedrock** | `bedrock` | AWS S3 | ✅ Yes | | **OpenAI** | `openai` | OpenAI storage | ❌ No | | **Gemini** | `gemini` | Google Cloud Storage | ❌ No | | **Anthropic** | `anthropic` | N/A | N/A | **Bedrock Provider:** Requires S3 bucket configuration. The IAM role for batch operations is configured server-side in FinOps. You can use Anthropic models deployed on Bedrock for batch and files APIs. **OpenAI & Gemini Providers:** No AWS infrastructure needed. Files are stored in the provider's native storage. The S3 bucket/key values in the examples are routing identifiers used by FinOps. **Anthropic Provider:** Does not support S3-based file uploads. Use the [Anthropic SDK](../anthropic-sdk/files-and-batch) with inline batch requests instead. *** ## Next Steps * **[Overview](/finops/integrations/overview)** - Bedrock SDK integration basics * **[Configuration](../../finops/model-provider)** - FinOps setup and configuration * **[Core Features](../../features/)** - Governance, semantic caching, and more --- # Overview URL: /finops/integrations/bedrock-sdk Use FinOps as a Bedrock-compatible gateway for the Converse and Invoke APIs, with FinOps features on top. *** title: "Overview" description: "Use FinOps as a Bedrock-compatible gateway for the Converse and Invoke APIs, with FinOps features on top." ------------------------------------------------------------------------------------------------------------------------ ## Overview FinOps provides a Bedrock-compatible endpoint for the **Converse** and **Invoke** APIs via protocol adaptation. The integration handles request transformation, response normalization, and error mapping between AWS Bedrock's API specification and FinOps's internal processing pipeline. This integration enables you to utilize FinOps's features like governance, load balancing, semantic caching, multi-provider support, and more, all while preserving your existing Bedrock SDK-based architecture. **Endpoint:** `/bedrock` ## Setup ### Python ```python {6} import boto3 # Configure boto3 Bedrock client to use FinOps # Note: When using FinOps keys, dummy credentials are required # because boto3 needs credentials to sign requests, even though # FinOps will use its own configured keys. client = boto3.client( service_name="bedrock-runtime", endpoint_url="{AI_GATEWAY_URL}/bedrock", region_name="us-west-2", aws_access_key_id="finops-dummy-key", # Required when using FinOps keys aws_secret_access_key="finops-dummy-secret" # Required when using FinOps keys ) # Make requests as usual response = client.converse( modelId="anthropic.claude-3-5-sonnet-20240620-v1:0", messages=[ { "role": "user", "content": [{"text": "Hello!"}] } ] ) print(response) ``` ## Provider/Model Usage Examples Because Bedrock itself is a multi-provider platform, you can use any Bedrock-supported model ID and still route through FinOps. FinOps will handle governance, observability, and other cross-cutting concerns. ```python import boto3 import json client = boto3.client( service_name="bedrock-runtime", endpoint_url="{AI_GATEWAY_URL}/bedrock", region_name="us-west-2", aws_access_key_id="finops-dummy-key", aws_secret_access_key="finops-dummy-secret" ) # Anthropic via Bedrock (Converse API) anthropic_response = client.converse( modelId="anthropic.claude-3-sonnet-20240229", messages=[{"role": "user", "content": [{"text": "Hello from Claude!"}]}] ) # Mistral via Bedrock (Converse API) mistral_response = client.converse( modelId="mistral.mistral-large-2407", messages=[{"role": "user", "content": [{"text": "Hello from Mistral!"}]}] ) # Mistral via Bedrock (Invoke API) mistral_invoke_response = client.invoke_model( modelId="mistral.mistral-large-2407", contentType="application/json", accept="application/json", body=json.dumps({ "prompt": "Say hello from Mistral using Invoke API.", "max_tokens": 50, "temperature": 0.7 }), ) ``` *** ## Adding Custom Headers Pass custom headers required by FinOps plugins (like governance, telemetry, etc.) using boto3's event system: ### Python ```python import boto3 def add_bifrost_headers(request, **kwargs): """Add custom FinOps headers to the request before signing.""" request.headers.add_header("x-bf-vk", "vk_12345") # Virtual key for governance request.headers.add_header("x-bf-env", "production") # Environment tag client = boto3.client( service_name="bedrock-runtime", endpoint_url="{AI_GATEWAY_URL}/bedrock", region_name="us-west-2", aws_access_key_id="finops-dummy-key", aws_secret_access_key="finops-dummy-secret" ) # Register the header injection for all Bedrock API calls client.meta.events.register_first( "before-sign.bedrock-runtime.*", add_bifrost_headers, ) # Now make requests with custom headers response = client.converse( modelId="anthropic.claude-3-5-sonnet-20240620-v1:0", messages=[{"role": "user", "content": [{"text": "Hello with custom headers!"}]}] ) ``` > **Note:** Use `register_first` to ensure headers are added before request signing. The event name format is `before-sign..`. You need to register for each API operation you plan to use (Converse, ConverseStream, InvokeModel, etc.). *** ## Streaming Examples ### Converse Stream Use `converse_stream` for chat-based streaming with a unified interface across models. ```python import boto3 client = boto3.client( service_name="bedrock-runtime", endpoint_url="{AI_GATEWAY_URL}/bedrock", region_name="us-west-2", aws_access_key_id="finops-dummy-key", aws_secret_access_key="finops-dummy-secret" ) response = client.converse_stream( modelId="anthropic.claude-3-5-sonnet-20240620-v1:0", messages=[{"role": "user", "content": [{"text": "Tell me a story about a brave knight."}]}], inferenceConfig={"maxTokens": 512, "temperature": 0.5} ) print("Response:") for chunk in response["stream"]: if "contentBlockDelta" in chunk: text = chunk["contentBlockDelta"]["delta"]["text"] print(text, end="", flush=True) ``` ### Invoke Stream Use `invoke_model_with_response_stream` for model-specific streaming payloads. ```python import boto3 import json client = boto3.client( service_name="bedrock-runtime", endpoint_url="{AI_GATEWAY_URL}/bedrock", region_name="us-west-2", aws_access_key_id="finops-dummy-key", aws_secret_access_key="finops-dummy-secret" ) # Example for Claude 3 (Messages API format) body = json.dumps({ "anthropic_version": "bedrock-2023-05-31", "max_tokens": 1024, "messages": [ {"role": "user", "content": "Write a haiku about coding."} ] }) response = client.invoke_model_with_response_stream( modelId="anthropic.claude-3-haiku-20240307-v1:0", body=body, contentType="application/json", accept="application/json" ) print("Response:") for event in response.get("body"): if "chunk" in event: chunk = event["chunk"] if "bytes" in chunk: # The chunk bytes contain the model-specific JSON response result = json.loads(chunk["bytes"].decode("utf-8")) # Extract content based on model (e.g., Claude) if "delta" in result and "text" in result["delta"]: print(result["delta"]["text"], end="", flush=True) elif "completion" in result: print(result["completion"], end="", flush=True) ``` ## Supported Features The Bedrock integration currently supports: * **Converse** API (`/bedrock/model/{modelId}/converse`) for text/chat-style workloads * **Invoke** API (`/bedrock/model/{modelId}/invoke`) for model-specific text completion workloads * **Streaming** via `converse_stream` and `invoke_model_with_response_stream` * **Tools** via `toolConfig`, `toolUse`, and `toolResult` inside Converse requests * **Image and multimodal** responses where supported by the underlying Bedrock model * All FinOps core features that apply to these flows (governance, load balancing, semantic cache, observability, etc.) *** ## Next Steps * **[Files and Batch API](/finops/integrations/files-and-batch)** - S3-based file operations and batch processing * **[What is an integration?](../what-is-an-integration)** - Core integration concepts * **[Configuration](../../finops/model-provider)** - Bedrock provider setup and API key management * **[Core Features](../../features/)** - Governance, semantic caching, and more --- # Files and Batch API URL: /finops/integrations/genai-sdk/files-and-batch Upload files and create batch jobs for asynchronous processing using the Google GenAI SDK through FinOps across multiple providers. *** title: "Files and Batch API" description: "Upload files and create batch jobs for asynchronous processing using the Google GenAI SDK through FinOps across multiple providers." -------------------------------------------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' ## Overview FinOps supports the Google GenAI Files API and Batch API with **cross-provider routing**. This means you can use the Google GenAI SDK to manage files and batch jobs across multiple providers including Gemini, OpenAI, Anthropic, and Bedrock. The provider is specified using the `x-model-provider` header in `HttpOptions`. **Bedrock Limitation:** Bedrock batch operations require file-based input with S3 storage, which is not fully supported via the GenAI SDK's batch API. For Bedrock batch operations, use the [Bedrock SDK](../bedrock-sdk/files-and-batch) directly. *** ## Client Setup ### Gemini Provider (Default) ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-gemini-api-key", http_options=HttpOptions(base_url="{AI_GATEWAY_URL}/genai") ) ``` ### Cross-Provider Client Setup To route requests to different providers, add the `x-model-provider` header: ### Gemini Provider (Default) ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-gemini-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "gemini"} ) ) ``` ### OpenAI Provider ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-openai-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "openai"} ) ) ``` ### Anthropic Provider ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-anthropic-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "anthropic"} ) ) ``` Anthropic batch operations use inline requests. File uploads for batch processing are not supported for Anthropic. ### Bedrock Provider ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "bedrock"} ) ) ``` Bedrock requires S3-based file storage for batch operations. Use the [Bedrock SDK](../bedrock-sdk/files-and-batch) for full batch support. ### Helper Function for Provider-Specific Clients ```python from google import genai from google.genai.types import HttpOptions def get_provider_client(provider: str, api_key: str): """Create GenAI client with x-model-provider header""" return genai.Client( api_key=api_key, http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": provider} ) ) # Usage gemini_client = get_provider_client("gemini", "your-gemini-key") openai_client = get_provider_client("openai", "your-openai-key") ``` *** ## Files API Files are managed through the `client.files` namespace. ### Upload a File ### Gemini Provider ```python from google import genai from google.genai.types import HttpOptions, UploadFileConfig import json import tempfile def add_gemini_header: return {"x-model-provider": "gemini"} client = genai.Client( api_key="your-gemini-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers=add_gemini_header ) ) # Create JSON content for Gemini batch format def create_gemini_batch_json(num_requests: int = 2) -> str: requests_list = [] for i in range(num_requests): request = { "key": f"request_{i+1}", "request": { "contents": [ { "parts": [{"text": f"Hello, this is test message {i+1}. Say hi back briefly."}], "role": "user" } ] } } requests_list.append(json.dumps(request)) return "\n".join(requests_list) # Write content to a temporary file json_content = create_gemini_batch_json(num_requests=2) with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f: f.write(json_content) temp_file_path = f.name # Upload the file response = client.files.upload( file=temp_file_path, config=UploadFileConfig(display_name='batch_input_gemini') ) print(f"File name: {response.name}") print(f"Display name: {response.display_name}") ``` ### OpenAI Provider ```python from google import genai from google.genai.types import HttpOptions, UploadFileConfig import json import tempfile client = genai.Client( api_key="your-openai-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "openai"} ) ) # Create JSONL content for OpenAI batch format def create_openai_batch_jsonl(model_id: str, num_requests: int = 2) -> str: lines = [] for i in range(num_requests): record = { "custom_id": f"request-{i+1}", "method": "POST", "url": "/v1/chat/completions", "body": { "model": model_id, "messages": [ {"role": "user", "content": f"Hello, this is test message {i+1}. Say hi back briefly."} ], "max_tokens": 100, }, } lines.append(json.dumps(record)) return "\n".join(lines) # Write content to a temporary file jsonl_content = create_openai_batch_jsonl("gpt-4o-mini") with tempfile.NamedTemporaryFile(mode='w', suffix='.jsonl', delete=False) as f: f.write(jsonl_content) temp_file_path = f.name # Upload the file response = client.files.upload( file=temp_file_path, config=UploadFileConfig(display_name='batch_input_openai') ) print(f"File name: {response.name}") ``` ### Anthropic Provider Anthropic does not support file uploads for batch processing via this API. Use inline batch requests instead (see Batch API section). ### Bedrock Provider Bedrock requires S3-based file storage. Use the [Bedrock SDK](../bedrock-sdk/files-and-batch) for file operations. ### List Files ### Gemini Provider ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-gemini-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "gemini"} ) ) # List files for file in client.files.list(config={'page_size': 50}): print(f"File name: {file.name}") print(f"Display name: {file.display_name}") if hasattr(file, 'size_bytes'): print(f"Size: {file.size_bytes} bytes") print("---") ``` ### OpenAI Provider ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-openai-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "openai"} ) ) # List files from OpenAI for file in client.files.list(config={'page_size': 50}): print(f"File name: {file.name}") print(f"Display name: {file.display_name}") print("---") ``` ### Anthropic Provider File listing is not supported for Anthropic via this API. ### Bedrock Provider Use the [Bedrock SDK](../bedrock-sdk/files-and-batch) for file listing with S3 storage. ### Retrieve File Metadata ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "gemini"} # or "openai" ) ) # Retrieve file metadata by name file_name = "files/abc123" response = client.files.get(name=file_name) print(f"File name: {response.name}") print(f"Display name: {response.display_name}") if hasattr(response, 'size_bytes'): print(f"Size: {response.size_bytes} bytes") ``` ### Delete a File ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "gemini"} # or "openai" ) ) # Delete a file file_name = "files/abc123" client.files.delete(name=file_name) print(f"Deleted file: {file_name}") ``` *** ## Batch API Batches are managed through the `client.batches` namespace. The GenAI SDK supports both file-based and inline batch creation. ### Create a Batch with File ### Gemini Provider ```python from google import genai from google.genai.types import HttpOptions, UploadFileConfig import json import tempfile client = genai.Client( api_key="your-gemini-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "gemini"} ) ) # Create batch input JSON content (Gemini format) batch_request = json.dumps({ "key": "request_1", "request": { "contents": [ {"parts": [{"text": "Hello! Say hi back briefly."}], "role": "user"} ] } }) # Write to temporary file and upload with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f: f.write(batch_request) temp_file_path = f.name uploaded_file = client.files.upload( file=temp_file_path, config=UploadFileConfig(display_name='batch_input_gemini') ) # Create batch job using file reference batch_job = client.batches.create( model="gemini-1.5-flash", src=uploaded_file.name, ) print(f"Batch name: {batch_job.name}") print(f"State: {batch_job.state}") ``` ### OpenAI Provider ```python from google import genai from google.genai.types import HttpOptions, UploadFileConfig import json import tempfile client = genai.Client( api_key="your-openai-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "openai"} ) ) # Create batch input JSONL content (OpenAI format) batch_request = json.dumps({ "custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": { "model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Hello! Say hi back briefly."}], "max_tokens": 100 } }) # Write to temporary file and upload with tempfile.NamedTemporaryFile(mode='w', suffix='.jsonl', delete=False) as f: f.write(batch_request) temp_file_path = f.name uploaded_file = client.files.upload( file=temp_file_path, config=UploadFileConfig(display_name='batch_input_openai') ) # Create batch job using file reference batch_job = client.batches.create( model="gpt-4o-mini", src=uploaded_file.name, ) print(f"Batch name: {batch_job.name}") print(f"State: {batch_job.state}") ``` ### Anthropic Provider Anthropic does not support file-based batch creation. Use inline requests instead. ### Bedrock Provider Use the [Bedrock SDK](../bedrock-sdk/files-and-batch) for Bedrock batch operations with S3 storage. ### Create a Batch with Inline Requests ### Gemini Provider ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-gemini-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "gemini"} ) ) # Create inline requests inline_requests = [ { "contents": [ { "parts": [{"text": "What is 2+2?"}], "role": "user" } ], "config": {"response_modalities": ["TEXT"]} }, { "contents": [ { "parts": [{"text": "What is the capital of France?"}], "role": "user" } ], "config": {"response_modalities": ["TEXT"]} } ] # Create batch job with inline requests batch_job = client.batches.create( model="gemini-1.5-flash", src=inline_requests, ) print(f"Batch name: {batch_job.name}") print(f"State: {batch_job.state}") ``` ### OpenAI Provider ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-openai-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "openai"} ) ) # Create inline requests (OpenAI format via FinOps translation) inline_requests = [ { "contents": [ { "parts": [{"text": "What is 2+2?"}], "role": "user" } ], "config": {"response_modalities": ["TEXT"]} }, { "contents": [ { "parts": [{"text": "What is the capital of France?"}], "role": "user" } ], "config": {"response_modalities": ["TEXT"]} } ] batch_job = client.batches.create( model="gpt-4o-mini", src=inline_requests, ) print(f"Batch name: {batch_job.name}") print(f"State: {batch_job.state}") ``` ### Anthropic Provider ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-anthropic-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "anthropic"} ) ) # Create inline requests for Anthropic inline_requests = [ { "contents": [ { "parts": [{"text": "What is 2+2?"}], "role": "user" } ], "config": {"response_modalities": ["TEXT"]} }, { "contents": [ { "parts": [{"text": "What is the capital of France?"}], "role": "user" } ], "config": {"response_modalities": ["TEXT"]} } ] batch_job = client.batches.create( model="claude-3-sonnet-20240229", src=inline_requests, ) print(f"Batch name: {batch_job.name}") print(f"State: {batch_job.state}") ``` ### Bedrock Provider Use the [Bedrock SDK](../bedrock-sdk/files-and-batch) for Bedrock batch operations. ### List Batches ```python from google import genai from google.genai.types import HttpOptions, ListBatchJobsConfig client = genai.Client( api_key="your-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "gemini"} # or "openai", "anthropic" ) ) # List batch jobs for job in client.batches.list(config=ListBatchJobsConfig(page_size=10)): print(f"Batch name: {job.name}") print(f"State: {job.state}") print("---") ``` ### Retrieve Batch Status ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "gemini"} # or "openai", "anthropic" ) ) # Get batch job status batch_name = "batches/abc123" batch_job = client.batches.get(name=batch_name) print(f"Batch name: {batch_job.name}") print(f"State: {batch_job.state}") ``` ### Cancel a Batch ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "gemini"} # or "openai", "anthropic" ) ) # Cancel batch job batch_name = "batches/abc123" cancelled_job = client.batches.cancel(name=batch_name) print(f"Batch name: {cancelled_job.name}") print(f"State: {cancelled_job.state}") # JOB_STATE_CANCELLING or JOB_STATE_CANCELLED ``` ### Delete a Batch ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="your-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": "gemini"} # or "openai", "anthropic" ) ) # Delete batch job batch_name = "batches/abc123" client.batches.delete(name=batch_name) print(f"Deleted batch: {batch_name}") ``` *** ## End-to-End Workflows ### Gemini Batch Workflow ```python import time from google import genai from google.genai.types import HttpOptions, UploadFileConfig, ListBatchJobsConfig import json import tempfile import os # Configuration provider = "gemini" model = "gemini-1.5-flash" client = genai.Client( api_key="your-gemini-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": provider} ) ) # Step 1: Create batch input file print("Step 1: Creating batch input file...") def create_gemini_batch_json(num_requests: int) -> str: requests_list = [] for i in range(num_requests): request = { "key": f"request_{i+1}", "request": { "contents": [ { "parts": [{"text": f"What is {i+1} + {i+1}? Answer briefly."}], "role": "user" } ] } } requests_list.append(json.dumps(request)) return "\n".join(requests_list) json_content = create_gemini_batch_json(num_requests=3) with tempfile.NamedTemporaryFile(mode='w', suffix='.json', delete=False) as f: f.write(json_content) temp_file_path = f.name # Step 2: Upload batch input file print("Step 2: Uploading batch input file...") uploaded_file = client.files.upload( file=temp_file_path, config=UploadFileConfig(display_name='batch_e2e_gemini') ) print(f" Uploaded file: {uploaded_file.name}") # Step 3: Create batch job print("Step 3: Creating batch job...") batch_job = client.batches.create( model=model, src=uploaded_file.name, ) print(f" Created batch: {batch_job.name}, state: {batch_job.state}") # Step 4: Poll for completion print("Step 4: Polling batch status...") terminal_states = ["JOB_STATE_SUCCEEDED", "JOB_STATE_FAILED", "JOB_STATE_CANCELLED"] for i in range(20): batch_job = client.batches.get(name=batch_job.name) print(f" Poll {i+1}: state = {batch_job.state}") if batch_job.state in terminal_states: print(f" Batch reached terminal state: {batch_job.state}") break time.sleep(5) # Step 5: Verify batch is in list print("Step 5: Verifying batch in list...") found = False for job in client.batches.list(config=ListBatchJobsConfig(page_size=20)): if job.name == batch_job.name: found = True break assert found, f"Batch {batch_job.name} should be in list" print(f" Verified batch {batch_job.name} is in list") # Cleanup os.remove(temp_file_path) try: client.files.delete(name=uploaded_file.name) client.batches.delete(name=batch_job.name) except Exception as e: print(f"Cleanup note: {e}") print(f"\nSuccess! Batch workflow completed for {batch_job.name}") ``` ### OpenAI via GenAI SDK Workflow ```python import time from google import genai from google.genai.types import HttpOptions, ListBatchJobsConfig # Configuration provider = "openai" model = "gpt-4o-mini" client = genai.Client( api_key="your-openai-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": provider} ) ) # Step 1: Create inline requests print("Step 1: Creating inline requests...") inline_requests = [ { "contents": [ {"parts": [{"text": "What is 2+2?"}], "role": "user"} ], "config": {"response_modalities": ["TEXT"]} }, { "contents": [ {"parts": [{"text": "What is the capital of France?"}], "role": "user"} ], "config": {"response_modalities": ["TEXT"]} } ] print(f" Created {len(inline_requests)} inline requests") # Step 2: Create batch job print("Step 2: Creating batch job...") batch_job = client.batches.create( model=model, src=inline_requests, ) print(f" Created batch: {batch_job.name}, state: {batch_job.state}") # Step 3: Poll for completion print("Step 3: Polling batch status...") terminal_states = ["JOB_STATE_SUCCEEDED", "JOB_STATE_FAILED", "JOB_STATE_CANCELLED"] for i in range(10): batch_job = client.batches.get(name=batch_job.name) print(f" Poll {i+1}: state = {batch_job.state}") if batch_job.state in terminal_states: break time.sleep(5) # Cleanup try: client.batches.delete(name=batch_job.name) except Exception as e: print(f"Cleanup note: {e}") print(f"\nSuccess! Cross-provider batch {batch_job.name} completed via GenAI SDK.") ``` ### Anthropic via GenAI SDK Workflow ```python import time from google import genai from google.genai.types import HttpOptions # Configuration provider = "anthropic" model = "claude-3-sonnet-20240229" client = genai.Client( api_key="your-anthropic-api-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={"x-model-provider": provider} ) ) # Step 1: Create inline requests print("Step 1: Creating inline requests...") inline_requests = [ { "contents": [ {"parts": [{"text": "What is 15 * 7?"}], "role": "user"} ], "config": {"response_modalities": ["TEXT"]} }, { "contents": [ {"parts": [{"text": "What is the largest ocean?"}], "role": "user"} ], "config": {"response_modalities": ["TEXT"]} } ] print(f" Created {len(inline_requests)} inline requests") # Step 2: Create batch job print("Step 2: Creating batch job...") batch_job = client.batches.create( model=model, src=inline_requests, ) print(f" Created batch: {batch_job.name}, state: {batch_job.state}") # Step 3: Poll for completion print("Step 3: Polling batch status...") terminal_states = ["JOB_STATE_SUCCEEDED", "JOB_STATE_FAILED", "JOB_STATE_CANCELLED", "ended"] for i in range(10): batch_job = client.batches.get(name=batch_job.name) print(f" Poll {i+1}: state = {batch_job.state}") if batch_job.state in terminal_states: break time.sleep(5) print(f"\nSuccess! Anthropic batch {batch_job.name} completed via GenAI SDK.") ``` *** ## Batch Job States | State | Description | | ---------------------- | ---------------------------------- | | `JOB_STATE_QUEUED` | Job is queued and waiting to start | | `JOB_STATE_PENDING` | Job is pending processing | | `JOB_STATE_RUNNING` | Job is currently running | | `JOB_STATE_SUCCEEDED` | Job completed successfully | | `JOB_STATE_FAILED` | Job failed | | `JOB_STATE_CANCELLING` | Job is being cancelled | | `JOB_STATE_CANCELLED` | Job was cancelled | *** ## JSON Format Reference ### Gemini Batch Format ```json {"key": "request-1", "request": {"contents": [{"parts": [{"text": "Hello!"}], "role": "user"}]}} ``` ### Inline Request Format ```python { "contents": [ {"parts": [{"text": "Hello!"}], "role": "user"} ], "config": {"response_modalities": ["TEXT"]} } ``` *** ## Provider-Specific Notes | Provider | Header Value | File Upload | Batch Type | Models | | ------------- | ---------------- | --------------- | --------------- | --------------------- | | **Gemini** | `gemini` or omit | Native storage | File or Inline | `gemini-1.5-*` | | **OpenAI** | `openai` | Native storage | File or Inline | `gpt-4o-*`, `gpt-4-*` | | **Anthropic** | `anthropic` | Not supported | Inline only | `claude-3-*` | | **Bedrock** | `bedrock` | Use Bedrock SDK | Use Bedrock SDK | `anthropic.claude-*` | * **Gemini** and **OpenAI** support both file-based and inline batch creation * **Anthropic** only supports inline batch requests via this SDK * **Bedrock** requires the [Bedrock SDK](../bedrock-sdk/files-and-batch) for full batch support *** ## Next Steps * **[Overview](/finops/integrations/overview)** - GenAI SDK integration basics * **[Configuration](../../finops/model-provider)** - FinOps setup and configuration * **[Core Features](../../features/)** - Governance, semantic caching, and more --- # Overview URL: /finops/integrations/genai-sdk Use FinOps as a drop-in replacement for Google GenAI API with full compatibility and enhanced features. *** title: "Overview" description: "Use FinOps as a drop-in replacement for Google GenAI API with full compatibility and enhanced features." ---------------------------------------------------------------------------------------------------------------------- ## Overview FinOps provides complete Google GenAI API compatibility through protocol adaptation. The integration handles request transformation, response normalization, and error mapping between Google's GenAI API specification and FinOps's internal processing pipeline. This integration enables you to utilize FinOps's features like governance, load balancing, semantic caching, multi-provider support, and more, all while preserving your existing Google GenAI SDK-based architecture. **Endpoint:** `/genai` *** ## Setup ### Python ```python {7} from google import genai from google.genai.types import HttpOptions # Configure client to use FinOps client = genai.Client( api_key="dummy-key", # Keys handled by FinOps http_options=HttpOptions(base_url="{AI_GATEWAY_URL}/genai") ) # Make requests as usual response = client.models.generate_content( model="gemini-1.5-flash", contents="Hello!" ) print(response.text) ``` ### JavaScript ```javascript {5} import { GoogleGenerativeAI } from "@google/generative-ai"; // Configure client to use FinOps const genAI = new GoogleGenerativeAI("dummy-key", { baseUrl: "{AI_GATEWAY_URL}/genai", // Keys handled by FinOps }); // Make requests as usual const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" }); const response = await model.generateContent("Hello!"); console.log(response.response.text); ``` *** ## Provider/Model Usage Examples Use multiple providers through the same GenAI SDK format by prefixing model names with the provider: ### Python ```python from google import genai from google.genai.types import HttpOptions client = genai.Client( api_key="dummy-key", http_options=HttpOptions(base_url="{AI_GATEWAY_URL}/genai") ) # Google Vertex models (default) vertex_response = client.models.generate_content( model="gemini-1.5-flash", contents="Hello from Gemini!" ) # OpenAI models via GenAI SDK format openai_response = client.models.generate_content( model="openai/gpt-4o-mini", contents="Hello from OpenAI!" ) # Anthropic models via GenAI SDK format anthropic_response = client.models.generate_content( model="anthropic/claude-3-sonnet-20240229", contents="Hello from Claude!" ) # Azure models azure_response = client.models.generate_content( model="azure/gpt-4o", contents="Hello from Azure!" ) # Local Ollama models ollama_response = client.models.generate_content( model="ollama/llama3.1:8b", contents="Hello from Ollama!" ) ``` ### JavaScript ```javascript import { GoogleGenerativeAI } from "@google/generative-ai"; const genAI = new GoogleGenerativeAI("dummy-key", { baseUrl: "{AI_GATEWAY_URL}/genai", }); // Google Vertex models (default) const geminiModel = genAI.getGenerativeModel({ model: "gemini-1.5-flash" }); const vertexResponse = await geminiModel.generateContent("Hello from Gemini!"); // OpenAI models via GenAI SDK format const openaiModel = genAI.getGenerativeModel({ model: "openai/gpt-4o-mini" }); const openaiResponse = await openaiModel.generateContent("Hello from OpenAI!"); // Anthropic models via GenAI SDK format const anthropicModel = genAI.getGenerativeModel({ model: "anthropic/claude-3-sonnet-20240229" }); const anthropicResponse = await anthropicModel.generateContent("Hello from Claude!"); // Azure models const azureModel = genAI.getGenerativeModel({ model: "azure/gpt-4o" }); const azureResponse = await azureModel.generateContent("Hello from Azure!"); // Local Ollama models const ollamaModel = genAI.getGenerativeModel({ model: "ollama/llama3.1:8b" }); const ollamaResponse = await ollamaModel.generateContent("Hello from Ollama!"); ``` *** ## Adding Custom Headers Pass custom headers required by FinOps plugins (like governance, telemetry, etc.): ### Python ```python from google import genai from google.genai.types import HttpOptions # Configure client with custom headers client = genai.Client( api_key="dummy-key", http_options=HttpOptions( base_url="{AI_GATEWAY_URL}/genai", headers={ "x-bf-vk": "vk_12345", # Virtual key for governance } ) ) response = client.models.generate_content( model="gemini-1.5-flash", contents="Hello with custom headers!" ) ``` ### JavaScript ```javascript import { GoogleGenerativeAI } from "@google/generative-ai"; // Configure client with custom headers const genAI = new GoogleGenerativeAI("dummy-key", { baseUrl: "{AI_GATEWAY_URL}/genai", customHeaders: { "x-bf-vk": "vk_12345", // Virtual key for governance }, }); const model = genAI.getGenerativeModel({ model: "gemini-1.5-flash" }); const response = await model.generateContent("Hello with custom headers!"); ``` *** ## Dynamic Thinking Budget When `thinkingConfig.thinkingBudget` is set to `-1`, FinOps handles it differently per provider: * **Gemini**: Preserves `-1` for native dynamic thinking support * **Anthropic**, **Bedrock**, **Cohere**: Converts to minimum reasoning budget value (1024) * **OpenAI**: Converts to medium reasoning effort ```python response = client.models.glenerate_content( model="gemini-2.5-flash", contents="Complex reasoning task", config={ "thinking_config": { "include_thoughts": true, "thinking_budget": -1 # Dynamic thinking } } ) ``` *** ## Supported Features The Google GenAI integration supports all features that are available in both the Google GenAI SDK and FinOps core functionality. If the Google GenAI SDK supports a feature and FinOps supports it, the integration will work seamlessly. *** ## Next Steps * **[OpenAI SDK](../openai-sdk/overview)** - GPT integration patterns * **[Configuration](../../finops/model-provider)** - FinOps setup and configuration * **[Core Features](../../features/)** - Advanced FinOps capabilities --- # Files and Batch API URL: /finops/integrations/openai-sdk/files-and-batch Upload files and create batch jobs for asynchronous processing using the OpenAI SDK through FinOps across multiple providers. *** title: "Files and Batch API" description: "Upload files and create batch jobs for asynchronous processing using the OpenAI SDK through FinOps across multiple providers." tag: "Beta" ----------- import { Callout } from 'fumadocs-ui/components/callout' ## Overview FinOps supports the OpenAI Files API and Batch API with **cross-provider routing**. This means you can use the familiar OpenAI SDK to manage files and batch jobs across multiple providers including OpenAI, Anthropic, Bedrock, and Gemini. The provider is specified using `extra_body` (for POST requests) or `extra_query` (for GET requests) parameters. *** ## Client Setup The base client setup is the same for all providers. The provider is specified per-request: ```python from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="your-api-key" # Your actual API key ) ``` *** ## Files API ### Upload a File **Bedrock** requires S3 storage configuration. OpenAI and Gemini use their native file storage. Anthropic uses inline requests (no file upload). ### OpenAI Provider ```python from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="your-openai-api-key" ) # Create JSONL content for OpenAI batch format jsonl_content = '''{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "Hello!"}], "max_tokens": 100}} {"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "How are you?"}], "max_tokens": 100}}''' # Upload file (uses OpenAI's native file storage) response = client.files.create( file=("batch_input.jsonl", jsonl_content.encode, "application/jsonl"), purpose="batch", extra_body={"provider": "openai"}, ) print(f"Uploaded file ID: {response.id}") ``` ### Bedrock Provider For Bedrock, you need to provide S3 storage configuration: ```python from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="your-api-key" ) # Create JSONL content using OpenAI-style format (FinOps converts to Bedrock format internally) jsonl_content = '''{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "anthropic.claude-3-sonnet-20240229-v1:0", "messages": [{"role": "user", "content": "Hello!"}], "max_tokens": 100}} {"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "anthropic.claude-3-sonnet-20240229-v1:0", "messages": [{"role": "user", "content": "How are you?"}], "max_tokens": 100}}''' # Upload file with S3 storage configuration response = client.files.create( file=("batch_input.jsonl", jsonl_content.encode, "application/jsonl"), purpose="batch", extra_body={ "provider": "bedrock", "storage_config": { "s3": { "bucket": "your-s3-bucket", "region": "us-west-2", "prefix": "finops-batch-output", }, }, }, ) print(f"Uploaded file ID: {response.id}") ``` ### Anthropic Provider Anthropic uses inline requests for batching (no file upload needed). See the Batch API section below. ### Gemini Provider ```python from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="your-api-key" ) # Create JSONL content using OpenAI-style format (FinOps converts to Gemini format internally) jsonl_content = '''{"custom_id": "request-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini-1.5-flash", "messages": [{"role": "user", "content": "Hello!"}], "max_tokens": 100}} {"custom_id": "request-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini-1.5-flash", "messages": [{"role": "user", "content": "How are you?"}], "max_tokens": 100}}''' # Upload file (uses Gemini's native file storage) response = client.files.create( file=("batch_input.jsonl", jsonl_content.encode, "application/jsonl"), purpose="batch", extra_body={"provider": "gemini"}, ) print(f"Uploaded file ID: {response.id}") ``` ### List Files ```python # List files for OpenAI or Gemini (no S3 config needed) response = client.files.list( extra_query={"provider": "openai"} # or "gemini" ) for file in response.data: print(f"File ID: {file.id}, Name: {file.filename}") # For Bedrock (requires S3 config) response = client.files.list( extra_query={ "provider": "bedrock", "storage_config": { "s3": { "bucket": "your-s3-bucket", "region": "us-west-2", "prefix": "finops-batch-output", }, }, } ) ``` ### Retrieve File Metadata ```python # Retrieve file metadata (specify provider) file_id = "file-abc123" response = client.files.retrieve( file_id, extra_query={"provider": "bedrock"} # or "openai", "gemini" ) print(f"File ID: {response.id}") print(f"Filename: {response.filename}") print(f"Purpose: {response.purpose}") print(f"Bytes: {response.bytes}") ``` ### Delete a File ```python # Delete file (specify provider) file_id = "file-abc123" response = client.files.delete( file_id, extra_query={"provider": "bedrock"} # or "openai", "gemini" ) print(f"Deleted: {response.deleted}") ``` ### Download File Content ```python # Download file content (specify provider) file_id = "file-abc123" response = client.files.content( file_id, extra_query={"provider": "bedrock"} # or "openai", "gemini" ) # Handle different response types if hasattr(response, "read"): content = response.read elif hasattr(response, "content"): content = response.content else: content = response # Decode bytes to string if needed if isinstance(content, bytes): content = content.decode("utf-8") print(f"File content:\n{content}") ``` *** ## Batch API ### Create a Batch ### OpenAI Provider For native OpenAI batching: ```python from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="your-openai-api-key" ) # First upload a file (see Files API section) # Then create batch using the file ID batch = client.batches.create( input_file_id="file-abc123", endpoint="/v1/chat/completions", completion_window="24h", extra_body={"provider": "openai"}, ) print(f"Batch ID: {batch.id}") print(f"Status: {batch.status}") ``` ### Bedrock Provider For Bedrock, you need to provide output S3 URI: ```python from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="your-api-key" ) # First upload a file with S3 config (see Files API section) # Then create batch using the file ID batch = client.batches.create( input_file_id="file-abc123", endpoint="/v1/chat/completions", completion_window="24h", extra_body={ "provider": "bedrock", "model": "anthropic.claude-3-sonnet-20240229-v1:0", "output_s3_uri": "s3://your-bucket/batch-output", }, ) print(f"Batch ID: {batch.id}") print(f"Status: {batch.status}") ``` ### Anthropic Provider Anthropic supports inline requests (no file upload required): ```python from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="your-anthropic-api-key" ) # Create inline requests for Anthropic requests = [ { "custom_id": "request-1", "params": { "model": "claude-3-sonnet-20240229", "max_tokens": 100, "messages": [{"role": "user", "content": "Hello!"}] } }, { "custom_id": "request-2", "params": { "model": "claude-3-sonnet-20240229", "max_tokens": 100, "messages": [{"role": "user", "content": "How are you?"}] } } ] # Create batch with inline requests (no file ID needed) batch = client.batches.create( input_file_id="", # Empty for inline requests endpoint="/v1/chat/completions", completion_window="24h", extra_body={ "provider": "anthropic", "requests": requests, }, ) print(f"Batch ID: {batch.id}") print(f"Status: {batch.status}") ``` ### Gemini Provider ```python from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="your-api-key" ) # First upload a file with Gemini format (see Files API section) # Then create batch using the file ID batch = client.batches.create( input_file_id="file-abc123", endpoint="/v1/chat/completions", completion_window="24h", extra_body={ "provider": "gemini", "model": "gemini-1.5-flash", }, ) print(f"Batch ID: {batch.id}") print(f"Status: {batch.status}") ``` ### List Batches ```python # List batches (specify provider) response = client.batches.list( limit=10, extra_query={ "provider": "bedrock", # or "openai", "anthropic", "gemini" "model": "anthropic.claude-3-sonnet-20240229-v1:0", # Required for bedrock } ) for batch in response.data: print(f"Batch ID: {batch.id}, Status: {batch.status}") ``` ### Retrieve Batch Status ```python # Retrieve batch status (specify provider) batch_id = "batch-abc123" batch = client.batches.retrieve( batch_id, extra_query={"provider": "bedrock"} # or "openai", "anthropic", "gemini" ) print(f"Batch ID: {batch.id}") print(f"Status: {batch.status}") if batch.request_counts: print(f"Total: {batch.request_counts.total}") print(f"Completed: {batch.request_counts.completed}") print(f"Failed: {batch.request_counts.failed}") ``` ### Cancel a Batch ```python # Cancel batch (specify provider) batch_id = "batch-abc123" batch = client.batches.cancel( batch_id, extra_body={"provider": "bedrock"} # or "openai", "anthropic", "gemini" ) print(f"Batch ID: {batch.id}") print(f"Status: {batch.status}") # "cancelling" or "cancelled" ``` *** ## End-to-End Workflows ### OpenAI Batch Workflow ```python import time from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="your-openai-api-key" ) # Configuration provider = "openai" # Step 1: Create OpenAI JSONL content jsonl_content = '''{"custom_id": "req-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "What is 2+2?"}], "max_tokens": 100}} {"custom_id": "req-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gpt-4o-mini", "messages": [{"role": "user", "content": "What is the capital of France?"}], "max_tokens": 100}}''' # Step 2: Upload file (uses OpenAI's native file storage) print("Step 1: Uploading batch input file...") uploaded_file = client.files.create( file=("batch_e2e.jsonl", jsonl_content.encode, "application/jsonl"), purpose="batch", extra_body={"provider": provider}, ) print(f" Uploaded file: {uploaded_file.id}") # Step 3: Create batch print("Step 2: Creating batch job...") batch = client.batches.create( input_file_id=uploaded_file.id, endpoint="/v1/chat/completions", completion_window="24h", extra_body={"provider": provider}, ) print(f" Created batch: {batch.id}, status: {batch.status}") # Step 4: Poll for completion print("Step 3: Polling batch status...") for i in range(10): batch = client.batches.retrieve(batch.id, extra_query={"provider": provider}) print(f" Poll {i+1}: status = {batch.status}") if batch.status in ["completed", "failed", "expired", "cancelled"]: break if batch.request_counts: print(f" Completed: {batch.request_counts.completed}/{batch.request_counts.total}") time.sleep(5) print(f"\nSuccess! Batch {batch.id} workflow completed.") ``` ### Bedrock Batch Workflow ```python import time from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="your-api-key" ) # Configuration provider = "bedrock" s3_bucket = "your-s3-bucket" s3_region = "us-west-2" model = "anthropic.claude-3-sonnet-20240229-v1:0" # Step 1: Create JSONL content using OpenAI-style format (FinOps converts to Bedrock format internally) jsonl_content = '''{"custom_id": "req-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "anthropic.claude-3-sonnet-20240229-v1:0", "messages": [{"role": "user", "content": "What is 2+2?"}], "max_tokens": 100}} {"custom_id": "req-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "anthropic.claude-3-sonnet-20240229-v1:0", "messages": [{"role": "user", "content": "What is the capital of France?"}], "max_tokens": 100}}''' # Step 2: Upload file print("Step 1: Uploading batch input file...") uploaded_file = client.files.create( file=("batch_e2e.jsonl", jsonl_content.encode, "application/jsonl"), purpose="batch", extra_body={ "provider": provider, "storage_config": { "s3": {"bucket": s3_bucket, "region": s3_region, "prefix": "batch-input"}, }, }, ) print(f" Uploaded file: {uploaded_file.id}") # Step 3: Create batch print("Step 2: Creating batch job...") batch = client.batches.create( input_file_id=uploaded_file.id, endpoint="/v1/chat/completions", completion_window="24h", extra_body={ "provider": provider, "model": model, "output_s3_uri": f"s3://{s3_bucket}/batch-output", }, ) print(f" Created batch: {batch.id}, status: {batch.status}") # Step 4: Poll for completion print("Step 3: Polling batch status...") for i in range(10): batch = client.batches.retrieve(batch.id, extra_query={"provider": provider}) print(f" Poll {i+1}: status = {batch.status}") if batch.status in ["completed", "failed", "expired", "cancelled"]: break if batch.request_counts: print(f" Completed: {batch.request_counts.completed}/{batch.request_counts.total}") time.sleep(5) print(f"\nSuccess! Batch {batch.id} workflow completed.") ``` ### Anthropic Inline Batch Workflow ```python import time from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="your-anthropic-api-key" ) provider = "anthropic" # Step 1: Create inline requests print("Step 1: Creating inline requests...") requests = [ { "custom_id": "math-question", "params": { "model": "claude-3-sonnet-20240229", "max_tokens": 100, "messages": [{"role": "user", "content": "What is 15 * 7?"}] } }, { "custom_id": "geography-question", "params": { "model": "claude-3-sonnet-20240229", "max_tokens": 100, "messages": [{"role": "user", "content": "What is the largest ocean?"}] } } ] print(f" Created {len(requests)} inline requests") # Step 2: Create batch print("Step 2: Creating batch job...") batch = client.batches.create( input_file_id="", endpoint="/v1/chat/completions", completion_window="24h", extra_body={"provider": provider, "requests": requests}, ) print(f" Created batch: {batch.id}, status: {batch.status}") # Step 3: Poll for completion print("Step 3: Polling batch status...") for i in range(10): batch = client.batches.retrieve(batch.id, extra_query={"provider": provider}) print(f" Poll {i+1}: status = {batch.status}") if batch.status in ["completed", "failed", "expired", "cancelled", "ended"]: break time.sleep(5) print(f"\nSuccess! Batch {batch.id} workflow completed.") ``` ### Gemini Batch Workflow ```python import time from openai import OpenAI client = OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="your-api-key" ) # Configuration provider = "gemini" model = "gemini-1.5-flash" # Step 1: Create JSONL content using OpenAI-style format (FinOps converts to Gemini format internally) jsonl_content = '''{"custom_id": "req-1", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini-1.5-flash", "messages": [{"role": "user", "content": "What is 2+2?"}], "max_tokens": 100}} {"custom_id": "req-2", "method": "POST", "url": "/v1/chat/completions", "body": {"model": "gemini-1.5-flash", "messages": [{"role": "user", "content": "What is the capital of France?"}], "max_tokens": 100}}''' # Step 2: Upload file (uses Gemini's native file storage) print("Step 1: Uploading batch input file...") uploaded_file = client.files.create( file=("batch_e2e.jsonl", jsonl_content.encode, "application/jsonl"), purpose="batch", extra_body={"provider": provider}, ) print(f" Uploaded file: {uploaded_file.id}") # Step 3: Create batch print("Step 2: Creating batch job...") batch = client.batches.create( input_file_id=uploaded_file.id, endpoint="/v1/chat/completions", completion_window="24h", extra_body={ "provider": provider, "model": model, }, ) print(f" Created batch: {batch.id}, status: {batch.status}") # Step 4: Poll for completion print("Step 3: Polling batch status...") for i in range(10): batch = client.batches.retrieve(batch.id, extra_query={"provider": provider}) print(f" Poll {i+1}: status = {batch.status}") if batch.status in ["completed", "failed", "expired", "cancelled"]: break if batch.request_counts: print(f" Completed: {batch.request_counts.completed}/{batch.request_counts.total}") time.sleep(5) print(f"\nSuccess! Batch {batch.id} workflow completed.") ``` *** ## Provider-Specific Notes | Provider | File Upload | Batch Creation | Extra Configuration | | ------------- | ---------------- | ----------------- | --------------------------------- | | **OpenAI** | ✅ Native storage | ✅ File-based | None | | **Bedrock** | ✅ S3-based | ✅ File-based | `storage_config`, `output_s3_uri` | | **Anthropic** | ❌ Not supported | ✅ Inline requests | `requests` array in `extra_body` | | **Gemini** | ✅ Native storage | ✅ File-based | `model` in `extra_body` | * **OpenAI** and **Gemini** use their native file storage - no S3 configuration needed * **Bedrock** requires S3 storage configuration (`storage_config`, `output_s3_uri`) * **Anthropic** does not support file-based batch operations - use inline requests instead *** ## Next Steps * **[Overview](/finops/integrations/overview)** - OpenAI SDK integration basics * **[Configuration](../../finops/model-provider)** - FinOps setup and configuration * **[Core Features](../../features/)** - Governance, semantic caching, and more --- # Overview URL: /finops/integrations/openai-sdk Use FinOps as a drop-in replacement for OpenAI API with full compatibility and enhanced features. *** title: "Overview" description: "Use FinOps as a drop-in replacement for OpenAI API with full compatibility and enhanced features." ---------------------------------------------------------------------------------------------------------------- import { Callout } from 'fumadocs-ui/components/callout' ## Overview FinOps provides complete OpenAI API compatibility through protocol adaptation. The integration handles request transformation, response normalization, and error mapping between OpenAI's API specification and FinOps's internal processing pipeline. This integration enables you to utilize FinOps's features like governance, load balancing, semantic caching, multi-provider support, and more, all while preserving your existing OpenAI SDK-based architecture. **Endpoint:** `/openai` *** ## Setup ### Python ```python {5} import openai # Configure client to use FinOps client = openai.OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="dummy-key" # Keys handled by FinOps ) # Make requests as usual response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello!"}] ) print(response.choices[0].message.content) ``` ### JavaScript ```javascript {5} import OpenAI from "openai"; // Configure client to use FinOps const openai = new OpenAI({ baseURL: "{AI_GATEWAY_URL}/openai", apiKey: "dummy-key", // Keys handled by FinOps }); // Make requests as usual const response = await openai.chat.completions.create({ model: "gpt-4o-mini", messages: [{ role: "user", content: "Hello!" }], }); console.log(response.choices[0].message.content); ``` *** ## Provider/Model Usage Examples Use multiple providers through the same OpenAI SDK format by prefixing model names with the provider: ### Python ```python import openai client = openai.OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="dummy-key" ) # OpenAI models (default) openai_response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello from OpenAI!"}] ) # Anthropic models via OpenAI SDK format anthropic_response = client.chat.completions.create( model="anthropic/claude-3-sonnet-20240229", messages=[{"role": "user", "content": "Hello from Claude!"}] ) # Google Vertex models via OpenAI SDK format vertex_response = client.chat.completions.create( model="vertex/gemini-pro", messages=[{"role": "user", "content": "Hello from Gemini!"}] ) # Azure models azure_response = client.chat.completions.create( model="azure/gpt-4o", messages=[{"role": "user", "content": "Hello from Azure!"}] ) # Local Ollama models ollama_response = client.chat.completions.create( model="ollama/llama3.1:8b", messages=[{"role": "user", "content": "Hello from Ollama!"}] ) ``` ### JavaScript ```javascript import OpenAI from "openai"; const openai = new OpenAI({ baseURL: "{AI_GATEWAY_URL}/openai", apiKey: "dummy-key", }); // OpenAI models (default) const openaiResponse = await openai.chat.completions.create({ model: "gpt-4o-mini", messages: [{ role: "user", content: "Hello from OpenAI!" }], }); // Anthropic models via OpenAI SDK format const anthropicResponse = await openai.chat.completions.create({ model: "anthropic/claude-3-sonnet-20240229", messages: [{ role: "user", content: "Hello from Claude!" }], }); // Google Vertex models via OpenAI SDK format const vertexResponse = await openai.chat.completions.create({ model: "vertex/gemini-pro", messages: [{ role: "user", content: "Hello from Gemini!" }], }); // Azure models const azureResponse = await openai.chat.completions.create({ model: "azure/gpt-4o", messages: [{ role: "user", content: "Hello from Azure!" }], }); // Local Ollama models const ollamaResponse = await openai.chat.completions.create({ model: "ollama/llama3.1:8b", messages: [{ role: "user", content: "Hello from Ollama!" }], }); ``` *** ## Adding Custom Headers Pass custom headers required by FinOps plugins (like governance, telemetry, etc.): ### Python ```python import openai client = openai.OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="dummy-key", default_headers={ "x-bf-vk": "vk_12345", # Virtual key for governance } ) response = client.chat.completions.create( model="gpt-4o-mini", messages=[{"role": "user", "content": "Hello with custom headers!"}] ) ``` ### JavaScript ```javascript import OpenAI from "openai"; const openai = new OpenAI({ baseURL: "{AI_GATEWAY_URL}/openai", apiKey: "dummy-key", defaultHeaders: { "x-bf-vk": "vk_12345", // Virtual key for governance }, }); const response = await openai.chat.completions.create({ model: "gpt-4o-mini", messages: [{ role: "user", content: "Hello with custom headers!" }], }); ``` *** ## Async Inference Submit inference requests asynchronously and poll for results later using the `x-bf-async` header. This is useful for long-running requests where you don't want to hold a connection open. See [Async Inference](../../features/async-inference) for full details. Async inference requires a [Logs Store](../../finops/telemetry) to be configured and is not compatible with streaming. ### Chat Completions ### Python ```python import openai import time client = openai.OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="dummy-key" ) # Submit async request initial = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[{"role": "user", "content": "Tell me a short story."}], extra_headers={"x-bf-async": "true"} ) # If choices are present, the request completed synchronously if initial.choices: print(initial.choices[0].message.content) else: # Poll until completed while True: time.sleep(2) poll = client.chat.completions.create( model="openai/gpt-4o-mini", messages=[{"role": "user", "content": "Tell me a short story."}], extra_headers={"x-bf-async-id": initial.id} ) if poll.choices: print(poll.choices[0].message.content) break ``` ### JavaScript ```javascript import OpenAI from "openai"; const openai = new OpenAI({ baseURL: "{AI_GATEWAY_URL}/openai", apiKey: "dummy-key", }); // Submit async request const initial = await openai.chat.completions.create( { model: "openai/gpt-4o-mini", messages: [{ role: "user", content: "Tell me a short story." }], }, { headers: { "x-bf-async": "true" } } ); // If choices are present, the request completed synchronously if (initial.choices?.length > 0) { console.log(initial.choices[0].message.content); } else { // Poll until completed while (true) { await new Promise((r) => setTimeout(r, 2000)); const poll = await openai.chat.completions.create( { model: "openai/gpt-4o-mini", messages: [{ role: "user", content: "Tell me a short story." }], }, { headers: { "x-bf-async-id": initial.id } } ); if (poll.choices?.length > 0) { console.log(poll.choices[0].message.content); break; } } } ``` ### Responses API ### Python ```python import openai import time client = openai.OpenAI( base_url="{AI_GATEWAY_URL}/openai", api_key="dummy-key" ) # Submit async request initial = client.responses.create( model="openai/gpt-4o-mini", input="Tell me a short story.", extra_headers={"x-bf-async": "true"} ) # If status is "completed", the request completed synchronously if initial.status == "completed": print(initial.output_text) else: # Poll until completed while True: time.sleep(2) poll = client.responses.create( model="openai/gpt-4o-mini", input="Tell me a short story.", extra_headers={"x-bf-async-id": initial.id} ) if poll.status == "completed": print(poll.output_text) break ``` ### JavaScript ```javascript import OpenAI from "openai"; const openai = new OpenAI({ baseURL: "{AI_GATEWAY_URL}/openai", apiKey: "dummy-key", }); // Submit async request const initial = await openai.responses.create( { model: "openai/gpt-4o-mini", input: "Tell me a short story." }, { headers: { "x-bf-async": "true" } } ); // If status is "completed", the request completed synchronously if (initial.status === "completed") { console.log(initial.output_text); } else { // Poll until completed while (true) { await new Promise((r) => setTimeout(r, 2000)); const poll = await openai.responses.create( { model: "openai/gpt-4o-mini", input: "Tell me a short story." }, { headers: { "x-bf-async-id": initial.id } } ); if (poll.status === "completed") { console.log(poll.output_text); break; } } } ``` ### Async Headers | Header | Description | | -------------------------------------- | ---------------------------------------------------------------------- | | `x-bf-async: true` | Submit the request as an async job. Returns immediately with a job ID. | | `x-bf-async-id: ` | Poll for results of a previously submitted async job. | | `x-bf-async-job-result-ttl: ` | Override the default result TTL (default: 3600s). | *** ## Supported Features The OpenAI integration supports all features that are available in both the OpenAI SDK and FinOps core functionality. If the OpenAI SDK supports a feature and FinOps supports it, the integration will work seamlessly. *** ## Next Steps * **[Files and Batch API](/finops/integrations/files-and-batch)** - File uploads and batch processing * **[Anthropic SDK](../anthropic-sdk/overview)** - Claude integration patterns * **[Google GenAI SDK](../genai-sdk)** - Gemini integration patterns * **[Configuration](../../finops/getting-started)** - FinOps setup and configuration * **[Core Features](../../features/)** - Advanced FinOps capabilities --- # AI prompt for JSON URL: /mbrix/application-builder/appendix/ai-prompt Flow-first system prompt grounded in the current Advance Builder schema. Copy into Claude, ChatGPT, or Gemini to generate importable snapshot JSON. *** title: "AI prompt for JSON" description: "Flow-first system prompt grounded in the current Advance Builder schema. Copy into Claude, ChatGPT, or Gemini to generate importable snapshot JSON." ------------------------------------------------------------------------------------------------------------------------------------------------------------------ import { AiPromptViewer } from '@/components/application-builder/ai-prompt-viewer' A full system prompt grounded in the **current** page-builder schema (`PageDocument`, flow layout, code panel, action chains). Copy it into Claude, ChatGPT, or Gemini, fill in your requirements at the top, then paste the returned JSON via toolbar **Paste snapshot JSON**. ## How to import 1. Open Application Builder designer → toolbar **Paste snapshot JSON**. 2. Paste AI output → confirm → fix asset IDs (Data Grid, Report, Flow) in Inspector → **Save**. > **Tip:** Use **Copy snapshot JSON** on an existing design and ask the AI to modify it — best results for complex apps. ## What to fill in at the top | Field | Example | | --------- | ------------------------------------------------------------- | | Layout | FLOW (default for new work) | | Data mode | STATIC (demo data in page/globals variables) or MPILOT-BACKED | | Type | APPLICATION | | Name | Recreation Booking Portal | | Slug | recreation-demo | | Screens | Home (`""`), Site Detail (`site/:id`), Contact (`contact`) | ## What this prompt covers * Flow-first document settings (`layoutEngine: "flow"`) and container flex layout * Application shell rules (one `outlet`, `meta.application`, globals vs page code) * Registered component types (prefer `selectableCard`, avoid `calendarOs`) * Code panel: variables, computed, functions, queries (`.loading`), watchers, lifecycle * Action chains and expression sandbox helpers * Tier A (snapshot-only) vs Tier B (`meta.platformSetup`) prerequisites * **Sophisticated patterns** from real snapshots: visual polish, nav shell, filtered card grids, stepper wizards, modal detail, query loading UX, large-app screen-by-screen workflow * Minimal valid page/app examples and a pre-return checklist ## System prompt (copy all) --- # Bindings {{ }} URL: /mbrix/application-builder/code-logic/bindings Wrap expressions in double curly braces in supported text and property fields. *** title: "Bindings {{ }}" description: "Wrap expressions in double curly braces in supported text and property fields." --------------------------------------------------------------------------------------------- **Category:** Dynamic ## Problems it solves Labels, visibility, and values update when data or variables change. ## How to use it Example: `{{ userDetails.userName }}`, `{{ getSites.data.length }}`, `{{ orderTotal > 100 }}` for visibility. ## Common mistakes * Forgetting quotes inside strings in complex expressions — use Code panel to test. --- # Code panel overview URL: /mbrix/application-builder/code-logic/codepanel Full-screen editor for Application (global) and Page-scoped symbols: variables, computed, functions, queries, watchers. *** title: "Code panel overview" description: "Full-screen editor for Application (global) and Page-scoped symbols: variables, computed, functions, queries, watchers." -------------------------------------------------------------------------------------------------------------------------------------- **Category:** Logic Code panel *Code panel — symbols, editor, Output.* ## Problems it solves Separates visual layout from data fetching and business logic. ## How to use it Nav rail → Code or Cmd+J. Left: symbol tree. Right: editor for selected symbol. Run queries/functions to test. ## Examples Platform globals (e.g. userDetails) show PLATFORM badge and are read-only. --- # Event handlers URL: /mbrix/application-builder/code-logic/events Action chains on user events: click, change, blur, etc. *** title: "Event handlers" description: "Action chains on user events: click, change, blur, etc." ---------------------------------------------------------------------- **Category:** Interactions ## Problems it solves Buttons, inputs, and menus need behavior without custom code files. ## How to use it Inspector → Interaction → add handler → chain actions: Set Variable, Run Query, Navigate, Notify, Confirm, Branch, etc. ## Examples Navigate action targets screen routes in applications. Confirm wraps sub-actions on OK/Cancel. --- # Functions & Computed URL: /mbrix/application-builder/code-logic/functions Functions: reusable logic (expression or JavaScript). Computed: derived read-only values from expressions. *** title: "Functions & Computed" description: "Functions: reusable logic (expression or JavaScript). Computed: derived read-only values from expressions." ------------------------------------------------------------------------------------------------------------------------- **Category:** Logic ## Problems it solves Avoid duplicating logic across event handlers and bindings. ## How to use it Function: define params and body, test in Run tab. Computed: name + expression that auto-updates. --- # Queries URL: /mbrix/application-builder/code-logic/queries Named data fetches from Tables, Workflows, Picklists, REST, or GraphQL. *** title: "Queries" description: "Named data fetches from Tables, Workflows, Picklists, REST, or GraphQL." -------------------------------------------------------------------------------------- **Category:** Data fetch ## Problems it solves Load records once, bind many components to queryName.data. ## How to use it Add Query → pick source → configure filters → Run to test → reference as `{{ queryName.data }}` in bindings. ## Examples MObject = platform Table. MFlow = run a workflow. Picklist = dropdown list category. --- # Variables URL: /mbrix/application-builder/code-logic/variables Store runtime state: selections, flags, form values. *** title: "Variables" description: "Store runtime state: selections, flags, form values." ------------------------------------------------------------------- **Category:** State ## Problems it solves Components and bindings reference variables by name. ## How to use it Add symbol → Variable → name, kind (Temporary, URL Param, Local/Session Storage), initial value. ## Examples Temporary = in-memory for the session. URL Param reads from address bar. ## Common mistakes * Duplicate variable names in the same scope. --- # Components panel URL: /mbrix/application-builder/designer/components Searchable library grouped by Commonly Used, Input, Data, Presentation. Drag tiles onto the canvas. *** title: "Components panel" description: "Searchable library grouped by Commonly Used, Input, Data, Presentation. Drag tiles onto the canvas." ------------------------------------------------------------------------------------------------------------------ **Category:** Library Components *Component library with categories.* ## Problems it solves Pre-built widgets connect to MPilot data (List View, Reports, Form, etc.). ## How to use it Click Components in nav rail → search or scroll → drag to canvas → resize on grid. ## Examples Data components (List View, Reports) need a Data Source in Inspector after drop. --- # Designer layout URL: /mbrix/application-builder/designer/designer Toolbar on top, nav rail on the left (Components, Outline, Code, Screens), canvas in the center, Inspector on the right. *** title: "Designer layout" description: "Toolbar on top, nav rail on the left (Components, Outline, Code, Screens), canvas in the center, Inspector on the right." --------------------------------------------------------------------------------------------------------------------------------------- **Category:** Workspace Designer *Full designer workspace.* ## Problems it solves Separates layout (canvas), structure (outline), logic (code), and properties (inspector). ## How to use it Open any page/application from the listing. Use nav rail icons to switch panels. Cmd+\ toggles components; Cmd+I inspector; Cmd+J code. ## Examples Collapse panels for more canvas space — reveal pills appear on the edge. --- # Inspector panel URL: /mbrix/application-builder/designer/inspector Right panel for selected component properties: content, appearance, visibility, event handlers. Empty canvas shows Canvas settings. *** title: "Inspector panel" description: "Right panel for selected component properties: content, appearance, visibility, event handlers. Empty canvas shows Canvas settings." -------------------------------------------------------------------------------------------------------------------------------------------------- **Category:** Properties Inspector *Canvas settings — background, viewport, CSS.* ## Problems it solves Every component has configurable fields; data components have Data Source pickers. ## How to use it Select component → Inspector opens (or Cmd+I). Edit fields. Use Visibility for conditional show/hide. --- # Outline panel URL: /mbrix/application-builder/designer/outline Hierarchical list of all components on the current canvas (Shell or screen). *** title: "Outline panel" description: "Hierarchical list of all components on the current canvas (Shell or screen)." ------------------------------------------------------------------------------------------- **Category:** Tree Outline *Outline showing Shell structure.* ## Problems it solves Easier to select nested containers and see structure at a glance. ## How to use it Click Outline → expand nodes → click to select → Inspector opens for that component. --- # Preview mode URL: /mbrix/application-builder/designer/preview Full-screen view without designer chrome — how end users see the layout. *** title: "Preview mode" description: "Full-screen view without designer chrome — how end users see the layout." --------------------------------------------------------------------------------------- **Category:** Test Preview *Preview mode.* ## Problems it solves Validate navigation, bindings, and layout before Save. ## How to use it Toolbar → Preview. Exit preview button or Esc returns to Design. --- # Screens panel URL: /mbrix/application-builder/designer/screens Manage Shell (shared layout) and per-screen routes. Shell must contain exactly one Outlet. *** title: "Screens panel" description: "Manage Shell (shared layout) and per-screen routes. Shell must contain exactly one Outlet." --------------------------------------------------------------------------------------------------------- **Category:** Apps Screens *Screens — Shell plus routes.* ## Problems it solves Applications are multi-route; each screen has its own canvas content rendered inside the Outlet. ## How to use it Screens panel → Shell for chrome (nav, footer) → click each screen to design its content → Add screen for new routes. ## Examples Default screen has route "" (root /). Other screens use paths like about, site/:id. ## Common mistakes * Deleting the Outlet from Shell — Save will fail validation. --- # Toolbar actions URL: /mbrix/application-builder/designer/toolbar Rename, design width (1280/1440/full), zoom, templates, snapshot JSON copy/paste, clear, Save, Design/Preview toggle. *** title: "Toolbar actions" description: "Rename, design width (1280/1440/full), zoom, templates, snapshot JSON copy/paste, clear, Save, Design/Preview toggle." ------------------------------------------------------------------------------------------------------------------------------------ **Category:** Top bar ## Problems it solves Save persists to server. Snapshot JSON enables import/export and AI-generated layouts. ## How to use it Always Save after changes. Use Paste snapshot JSON to import AI-generated JSON (see Appendix). ## Examples Copy snapshot JSON to give Claude/GPT your current design as context. --- # Create Page or Application URL: /mbrix/application-builder/get-started/createmodal The Create dialog lets you name the asset, pick a folder, and choose Page vs Application (with slug). *** title: "Create Page or Application" description: "The Create dialog lets you name the asset, pick a folder, and choose Page vs Application (with slug)." -------------------------------------------------------------------------------------------------------------------- **Category:** New asset ## Problems it solves Correct type at creation avoids rework — applications seed a Shell with an Outlet. ## How to use it * Create → enter Name → optional Description and Folder → Page or Application tab → Slug (apps only) → confirm. ## Examples Slug examples: recreation-demo, partner-portal (lowercase, hyphens only). ## Common mistakes * Using spaces or uppercase in slug — must be kebab-case. --- # End-to-end workflow URL: /mbrix/application-builder/get-started/lifecycle Plan → Create → Design → Add logic → Preview → Save → Users open /apps/your-slug. *** title: "End-to-end workflow" description: "Plan → Create → Design → Add logic → Preview → Save → Users open /apps/your-slug." ------------------------------------------------------------------------------------------------ **Category:** Journey ## What is it? Plan → Create → Design → Add logic → Preview → Save → Users open `/apps/your-slug`. ## Problems it solves Understanding the full chain helps you know where to fix issues (data source vs layout vs code). ## How to use it 1. Build MPilot assets first (Data Grid, Report). 2) Create in listing. 3) Design canvas. 4) Code panel for queries. 5) Save. 6) Share slug URL. ## Examples Data-driven apps: create the Data Grid in List View module before dropping List View on canvas. ## Common mistakes * Skipping Preview before Save. * Forgetting Save — changes are not persisted until you click Save. ## Related topics Listing · Code panel --- # Listing & folders URL: /mbrix/application-builder/get-started/listing The Advance Builder home lists all pages and applications in folders with search, sort, and card/list view. *** title: "Listing & folders" description: "The Advance Builder home lists all pages and applications in folders with search, sort, and card/list view." -------------------------------------------------------------------------------------------------------------------------- **Category:** Home Listing *Advance Builder listing with folders and application cards.* ## Problems it solves Central place to create, find, clone, delete, and audit your builder assets. ## How to use it * Create for new items. Action menu on each card: Edit, Clone, Delete, Audit History. Use folders in the left sidebar. ## Examples System pages (Sign In, Sign Up) may not be deletable. ## Common mistakes * Confusing Advance Builder listing with Page Builder under Screens. --- # What is Advance Builder? URL: /mbrix/application-builder/get-started/overview Advance Builder is MPilot's visual studio for creating pages and multi-screen applications. You drag components onto a grid canvas, wire data and logic, and Save to publish. *** title: "What is Advance Builder?" description: "Advance Builder is MPilot's visual studio for creating pages and multi-screen applications. You drag components onto a grid canvas, wire data and logic, and Save to publish." -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- **Category:** Big picture ## Problems it solves Teams need internal tools and customer-facing apps without building custom React frontends for every use case. ## How to use it Open Screens → Advance Builder. Create a Page or Application, design in the designer, Save. Applications go live at `/apps/your-slug`. ## Examples Think of it like Retool or a low-code page builder inside MPilot. ## Common mistakes * It is not the same as MBuilder layouts for table CRUD screens. * Save is not a separate Publish step — saved = live definition today. ## Related topics Page vs Application · End-to-end workflow --- # Page vs Application URL: /mbrix/application-builder/get-started/pagevsapp A Page is a single canvas document. An Application has a Shell, multiple Screens, routes, and a public URL slug. *** title: "Page vs Application" description: "A Page is a single canvas document. An Application has a Shell, multiple Screens, routes, and a public URL slug." ------------------------------------------------------------------------------------------------------------------------------- **Category:** Choose type ## Problems it solves Single pages suit embeds and simple layouts. Applications suit products with navigation and multiple views. ## How to use it Create modal → choose Page or Application. Applications require a kebab-case slug (2–60 chars). ## Examples If end users need /apps/my-product, create an Application. ## Common mistakes * Creating a Page when you need routing — use Application instead. ## Related topics Outlet · Screens panel --- # Form component URL: /mbrix/application-builder/integrations/forms Embeds an MFlow-driven form on the canvas. *** title: "Form component" description: "Embeds an MFlow-driven form on the canvas." --------------------------------------------------------- **Category:** Workflow ## Problems it solves Complex multi-field flows authored in Workflow, displayed inside your app shell. ## How to use it Publish workflow form → drag Form component → Inspector → select form flow. --- # Integration pattern URL: /mbrix/application-builder/integrations/integrate Create the asset in its home MPilot module first, then select it in Advance Builder Inspector. *** title: "Integration pattern" description: "Create the asset in its home MPilot module first, then select it in Advance Builder Inspector." ------------------------------------------------------------------------------------------------------------- **Category:** Connect ## Problems it solves Advance Builder embeds existing platform assets — it does not replace List View or Reports builders. ## How to use it 1. Create Data Grid / Report / etc. 2) Drag matching component. 3) Inspector → Data Source → pick asset. 4) Save. ## Common mistakes * Expecting List View to work without selecting a Data Grid — canvas stays empty. --- # List View → Data Grid URL: /mbrix/application-builder/integrations/listview Renders a configured Data Grid as a list/table on your canvas. *** title: "List View → Data Grid" description: "Renders a configured Data Grid as a list/table on your canvas." ----------------------------------------------------------------------------- **Category:** Tables ## Problems it solves Reuse spreadsheet-style views with filters and columns. ## How to use it Screens → List View → create Data Grid → in Advance Builder drag List View → Inspector → select Data Grid. --- # Reports component URL: /mbrix/application-builder/integrations/reports Embeds a saved chart or tabular report on the canvas. *** title: "Reports component" description: "Embeds a saved chart or tabular report on the canvas." -------------------------------------------------------------------- **Category:** Analytics ## Problems it solves Dashboards inside custom app layouts without iframe hacks. ## How to use it Create Report in Reports module → drag Reports component → Inspector → select Report. --- # Frequently asked questions URL: /mbrix/application-builder/rules-and-faqs/faqs Frequently asked questions *** title: "Frequently asked questions" description: "Frequently asked questions" ----------------------------------------- **Category:** Answers

Page vs Application?

Page = single canvas. Application = shell + screens + /apps/slug URL.

What is an Outlet?

Placeholder in Shell where each screen's content renders.

When does Save take effect?

Immediately — runtime loads the saved definition.

How do users open my app?

/apps/your-slug when Advanced Builder is enabled.

Query vs Reports component?

Query = fetch data in Code panel. Reports = embed a saved Report visual.

--- # Known limitations URL: /mbrix/application-builder/rules-and-faqs/limitations No undo/redo. No draft/publish UI. Runtime needs tenant Advanced Builder enabled. Watchers may be feature-flagged. *** title: "Known limitations" description: "No undo/redo. No draft/publish UI. Runtime needs tenant Advanced Builder enabled. Watchers may be feature-flagged." --------------------------------------------------------------------------------------------------------------------------------- **Category:** Today ## Problems it solves Sets expectations for authors and support. ## How to use it Work carefully; use Preview before Save. ## Common mistakes * Assuming Publish is separate from Save — it is not today. --- # Application save rules URL: /mbrix/application-builder/rules-and-faqs/validations Application save rules *** title: "Application save rules" description: "Application save rules" ------------------------------------- **Category:** Must pass
RuleDetail
Slugkebab-case, 2–60 characters, unique per tenant
OutletExactly one Outlet in Shell
Default screenExactly one screen marked default
RoutesUnique paths; kebab-case or :param segments
--- # Actions Menu URL: /mbrix/application-builder/components/actions-menu Overflow ⋮ menu with searchable inline actions or items from a variable. *** title: "Actions Menu" description: "Overflow ⋮ menu with searchable inline actions or items from a variable." --------------------------------------------------------------------------------------- **Category:** Commonly Used ## Problems it solves Table rows and cards need compact Edit / Delete / Audit without cluttering the layout. ## How to use it Drag Actions Menu → define actions in Inspector or bind items from `{{ variable }}` → On item click handler. ## Examples Example solves: row actions on a List View row · card kebab menu on a directory listing. ## Related topics List View · Card View --- # Avatar URL: /mbrix/application-builder/components/avatar Profile image with initials or icon fallback. *** title: "Avatar" description: "Profile image with initials or icon fallback." ------------------------------------------------------------ **Category:** Commonly Used ## Problems it solves Show who is logged in, team members, or assignees on a record. ## How to use it Set image URL or `{{ user.photo }}` → fallback name for initials → circle or square. ## Examples Example solves: user menu avatar · team member card in a directory · comment author face. --- # Badge URL: /mbrix/application-builder/components/badge Pill/chip for status, categories, or counts with preset or custom colors. *** title: "Badge" description: "Pill/chip for status, categories, or counts with preset or custom colors." ---------------------------------------------------------------------------------------- **Category:** Commonly Used ## Problems it solves Quick visual status: Active, Pending, Overdue, New. ## How to use it Set label text or `{{ item.status }}` → pick tone (info/success/warning/danger) → optional icon. ## Examples Example solves: order status chip · "Beta" tag on a feature · notification count style label. --- # Button URL: /mbrix/application-builder/components/button Clickable button with label, icon, variants (solid, outline, ghost), and event handlers. *** title: "Button" description: "Clickable button with label, icon, variants (solid, outline, ghost), and event handlers." ------------------------------------------------------------------------------------------------------- **Category:** Commonly Used ## Problems it solves Users need clear calls-to-action: submit, save, navigate, run a search. ## How to use it Drag Button → set label/icon → Inspector → On click → add action chain (Notify, Run Query, Navigate, etc.). ## Examples Example solves: "Search" triggers query · "Save draft" sets variable · "Go to Settings" navigates to /settings. ## Common mistakes * Button with no event handler — does nothing on click. --- # Calendar (CalendarOS) URL: /mbrix/application-builder/components/calendar-os Interactive scheduling UI with domain presets, validation rules, and custom fields. *** title: "Calendar (CalendarOS)" description: "Interactive scheduling UI with domain presets, validation rules, and custom fields." -------------------------------------------------------------------------------------------------- **Category:** Data ## Problems it solves Appointment booking, resource scheduling, and calendar-based workflows. ## How to use it Configure domain preset, views (month/week/day), validation groups in Inspector. ## Examples Example solves: campground availability calendar · clinic appointment booking · equipment reservation scheduler. --- # Card View URL: /mbrix/application-builder/components/card-view Card grid fed by Table (MObject) data. Design one card, replicated per row. *** title: "Card View" description: "Card grid fed by Table (MObject) data. Design one card, replicated per row." ------------------------------------------------------------------------------------------ **Category:** Data ## Problems it solves Browse catalogs, directories, and record lists in a visual grid instead of a table. ## How to use it Set MObject/query source → design card template with Field, Text, Button children → configure columns and page size. ## Examples Example solves: campground catalog · employee directory · product marketplace grid. ## Related topics Field · List View --- # Carousel URL: /mbrix/application-builder/components/carousel Image slideshow with captions; auto-branded on sign-in pages. *** title: "Carousel" description: "Image slideshow with captions; auto-branded on sign-in pages." ---------------------------------------------------------------------------- **Category:** Presentation ## Problems it solves Marketing hero rotations, product galleries, onboarding visuals. ## How to use it Add image slides (URL or upload) → set autoplay, caption colors. ## Examples Example solves: auth page marketing slides · campground photo gallery · partner logo rotator. --- # Checkbox Group URL: /mbrix/application-builder/components/checkbox-group Multi-select checkboxes from inline list or data source. *** title: "Checkbox Group" description: "Multi-select checkboxes from inline list or data source." ----------------------------------------------------------------------- **Category:** Input ## Problems it solves Pick multiple permissions, amenities, or categories at once. ## How to use it Define options or bind source → On change updates selection variable. ## Examples Example solves: "Select amenities" (wifi, parking, pets) · role permissions checklist. --- # Checkbox URL: /mbrix/application-builder/components/checkbox Single boolean checkbox; default checked can be expression. *** title: "Checkbox" description: "Single boolean checkbox; default checked can be expression." -------------------------------------------------------------------------- **Category:** Input ## Problems it solves Agree to terms, enable optional features, toggle a setting. ## How to use it Set label → default checked true/false or `{{ expr }}` → On change handler. ## Examples Example solves: "I agree to terms" on signup · "Send me email updates" opt-in. --- # Container URL: /mbrix/application-builder/components/container Layout card with background, border, padding, and drop zone for nested components. *** title: "Container" description: "Layout card with background, border, padding, and drop zone for nested components." ------------------------------------------------------------------------------------------------- **Category:** Commonly Used ## Problems it solves Group related UI, build footers, sidebars, and card layouts. ## How to use it Drag Container → drop children inside → style background/border in Inspector → resize on grid. ## Examples Example solves: footer with 3 columns · hero card wrapping search form · sidebar panel. ## Related topics Modal · Drawer --- # Dashboard URL: /mbrix/application-builder/components/dashboard Embeds a saved Dashboard from the Dashboards module. *** title: "Dashboard" description: "Embeds a saved Dashboard from the Dashboards module." ------------------------------------------------------------------- **Category:** Data ## Problems it solves Full analytics wall of widgets inside your application shell. ## How to use it Create Dashboard → drag component → pick Dashboard in Data Source. ## Examples Example solves: executive KPI home screen · operations monitoring page · partner analytics portal. --- # Divider URL: /mbrix/application-builder/components/divider Horizontal or vertical line separator with solid, dashed, dotted styles. *** title: "Divider" description: "Horizontal or vertical line separator with solid, dashed, dotted styles." --------------------------------------------------------------------------------------- **Category:** Presentation ## Problems it solves Visually separate sections without extra whitespace confusion. ## How to use it Drag Divider → set orientation, style, color, optional center label. ## Examples Example solves: line between form sections · vertical split in a toolbar · "OR" divider between login options. --- # Drawer URL: /mbrix/application-builder/components/drawer Slide-in side panel with body and footer drop zones. *** title: "Drawer" description: "Slide-in side panel with body and footer drop zones." ------------------------------------------------------------------- **Category:** Commonly Used ## Problems it solves Filters, mobile menus, and secondary workflows that slide over content. ## How to use it Design drawer content → trigger with Open Modal/Drawer action by name. ## Examples Example solves: filter panel for List View · mobile navigation drawer · audit history side panel. --- # Field URL: /mbrix/application-builder/components/field Display a single labeled value from card row data with type-aware formatting. *** title: "Field" description: "Display a single labeled value from card row data with type-aware formatting." -------------------------------------------------------------------------------------------- **Category:** Data ## Problems it solves Show one attribute inside a Card View template (name, date, picklist label). ## How to use it Used inside Card View children → set field key or `{{ item.field }}` → display as text/date/etc. ## Examples Example solves: "Location: `{{ item.city }}`" inside a site card · formatted date on a booking row. ## Related topics Card View --- # Form URL: /mbrix/application-builder/components/form Embeds a Workflow-driven form (MFlow) on the canvas. *** title: "Form" description: "Embeds a Workflow-driven form (MFlow) on the canvas." ------------------------------------------------------------------- **Category:** Data ## Problems it solves Run complex multi-field flows authored in Workflow without rebuilding fields manually. ## How to use it Publish form workflow → drag Form → Inspector → select flow → optional show submit. ## Examples Example solves: permit application form · partner onboarding · support ticket intake. ## Related topics Workflow --- # HTML / CSS URL: /mbrix/application-builder/components/html Raw HTML block with scoped CSS stylesheet. *** title: "HTML / CSS" description: "Raw HTML block with scoped CSS stylesheet." --------------------------------------------------------- **Category:** Advanced ## Problems it solves Custom layouts, marketing heroes, or designs not covered by standard components. ## How to use it Paste HTML in content → add scoped CSS → optional data-pb-click for button wire-up. ## Examples Example solves: gradient hero banner · custom pricing table · embedded SVG illustration. ## Common mistakes * Unscoped CSS leaking — use scoped styles or .pb-page prefix. --- # Icon + Text URL: /mbrix/application-builder/components/icon-text Icon paired with a text label (prefix or suffix). *** title: "Icon + Text" description: "Icon paired with a text label (prefix or suffix)." ---------------------------------------------------------------- **Category:** Commonly Used ## Problems it solves Navigation items, feature rows, and branded labels need icon + words together. ## How to use it Set text and icon → choose start/end position → style fonts and colors. ## Examples Example solves: app logo row in header · "Download PDF" with download icon · footer link with map pin. --- # Icon URL: /mbrix/application-builder/components/icon Standalone Lucide icon with size and color. *** title: "Icon" description: "Standalone Lucide icon with size and color." ---------------------------------------------------------- **Category:** Commonly Used ## Problems it solves Visual cues for status, categories, and affordances without text. ## How to use it Drag Icon → pick icon name or bind `{{ item.icon }}` → set size/color. ## Examples Example solves: warning icon next to alert text · feature bullet icons in a feature list. --- # Component library overview URL: /mbrix/application-builder/components/library The Components panel lists every widget you can drag onto the canvas, grouped by category. *** title: "Component library overview" description: "The Components panel lists every widget you can drag onto the canvas, grouped by category." --------------------------------------------------------------------------------------------------------- **Category:** All components Commonly used components *Figure: Commonly Used + start of Input category.* Input and Data components *Figure: Input, Data, Presentation, Advanced, and Structure categories.*
Tip: Use the search box to find "List", "Report", "Modal" quickly. Data components need a Data Source in Inspector after drop.
## Problems it solves Authors pick the right building block for each user problem instead of custom HTML. ## How to use it Nav rail → Components (Cmd+) → search or scroll categories → drag to canvas → configure in Inspector. ## Examples Categories: Commonly Used (UI chrome) · Input (forms) · Data (MPilot assets) · Presentation · Advanced · Structure. --- # List View URL: /mbrix/application-builder/components/list-view Embeds a saved Data Grid (spreadsheet-style list) on the canvas. *** title: "List View" description: "Embeds a saved Data Grid (spreadsheet-style list) on the canvas." ------------------------------------------------------------------------------- **Category:** Data ## Problems it solves Show sortable, filterable tabular data without rebuilding tables in the builder. ## How to use it Create Data Grid in List View module → drag List View → Inspector → select Data Grid. ## Examples Example solves: reservations table · user admin list · inventory with inline edit from grid config. ## Related topics MPilot Integrations --- # Modal URL: /mbrix/application-builder/components/modal Overlay dialog with body and footer slots for nested components. *** title: "Modal" description: "Overlay dialog with body and footer slots for nested components." ------------------------------------------------------------------------------- **Category:** Commonly Used ## Problems it solves Confirmations, detail views, and forms without leaving the page. ## How to use it Drag Modal → design body/footer children → open via Open Modal action → close with Close Modal. ## Examples Example solves: "Delete this site?" confirmation · quick-view record details · login prompt. ## Related topics Drawer · Event handlers --- # Navigation URL: /mbrix/application-builder/components/navigation Top or side navigation with tabs in design mode and URL routing in applications. *** title: "Navigation" description: "Top or side navigation with tabs in design mode and URL routing in applications." ----------------------------------------------------------------------------------------------- **Category:** Commonly Used ## Problems it solves Multi-screen apps need consistent nav between Destinations, About, Contact, etc. ## How to use it Drag onto Shell → add nav items → wire each to Navigate action or app routes. ## Examples Example solves: Recreation.gov header links · admin portal section tabs · mobile-friendly app menu. ## Related topics Screens panel · Outlet --- # Outlet URL: /mbrix/application-builder/components/outlet Placeholder where each application screen's content renders inside the Shell. *** title: "Outlet" description: "Placeholder where each application screen's content renders inside the Shell." -------------------------------------------------------------------------------------------- **Category:** Structure ## Problems it solves Required for multi-screen apps — separates shared chrome from per-screen content. ## How to use it Keep exactly one Outlet in Shell → design each screen's canvas separately in Screens panel. ## Examples Example solves: shared nav + footer on every screen while Destinations / About content swaps in the middle. ## Common mistakes * Zero or multiple Outlets — application save fails validation. ## Related topics Screens panel · Application walkthrough --- # Rating URL: /mbrix/application-builder/components/rating Star or icon rating input with configurable max and icons. *** title: "Rating" description: "Star or icon rating input with configurable max and icons." ------------------------------------------------------------------------- **Category:** Input ## Problems it solves Collect satisfaction scores, product reviews, priority levels. ## How to use it Set max stars, icon → bind value → On change saves to variable. ## Examples Example solves: post-visit satisfaction survey · support ticket priority · product review stars. --- # Reports URL: /mbrix/application-builder/components/reports Embeds a saved Report (chart or table) from the Reports module. *** title: "Reports" description: "Embeds a saved Report (chart or table) from the Reports module." ------------------------------------------------------------------------------ **Category:** Data ## Problems it solves Add analytics and KPIs inside a custom app page or dashboard screen. ## How to use it Create Report → drag Reports component → Inspector → select Report. ## Examples Example solves: monthly bookings chart on ops dashboard · revenue table on executive home. ## Related topics Dashboard --- # Select URL: /mbrix/application-builder/components/select Dropdown picker — inline options or sourced from variable, Table, or Picklist. *** title: "Select" description: "Dropdown picker — inline options or sourced from variable, Table, or Picklist." --------------------------------------------------------------------------------------------- **Category:** Input ## Problems it solves Choose one from many: country, department, campground, status. ## How to use it Set options inline OR bind to query/picklist → On change handler optional. ## Examples Example solves: "Choose state" dropdown · department filter · dynamic list from MObject query. ## Related topics Picklist integration --- # Selectable Card URL: /mbrix/application-builder/components/selectable-card Grid of cards — single or multi-select. Design first card, replicated to all items. *** title: "Selectable Card" description: "Grid of cards — single or multi-select. Design first card, replicated to all items." -------------------------------------------------------------------------------------------------- **Category:** Input ## Problems it solves Choose a plan, product, site, or template from visual cards. ## How to use it Set data source → design card template with children → On item click handler. ## Examples Example solves: pricing plan picker · campground site selection · marketplace product grid. ## Related topics Card View --- # Stepper URL: /mbrix/application-builder/components/stepper Multi-step progress indicator; steps inline or from {{ expression }}. *** title: "Stepper" description: "Multi-step progress indicator; steps inline or from {{ expression }}." ------------------------------------------------------------------------------------ **Category:** Input ## What is it? Multi-step progress indicator; steps inline or from `{{ expression }}`. ## Problems it solves Break long flows into guided steps: onboarding, checkout, application wizard. ## How to use it Define steps → drop content containers per step → bind currentStep variable → On step change events. ## Examples Example solves: 3-step permit application · onboarding wizard · checkout flow. ## Related topics Container --- # Tag Group URL: /mbrix/application-builder/components/tag-group Row of colored tag chips — inline or from variable, Table, or Picklist. *** title: "Tag Group" description: "Row of colored tag chips — inline or from variable, Table, or Picklist." -------------------------------------------------------------------------------------- **Category:** Commonly Used ## Problems it solves Show multiple categories, skills, or filters on a profile or product. ## How to use it Add inline tags or bind source → map label/color fields in Inspector. ## Examples Example solves: product tags "Outdoor · Family · ADA" · user skills from picklist · filter chips on search results. --- # Text Input URL: /mbrix/application-builder/components/text-input Full input field: text, number, date, date range, file, lookup, select, and more. *** title: "Text Input" description: "Full input field: text, number, date, date range, file, lookup, select, and more." ------------------------------------------------------------------------------------------------ **Category:** Input ## Problems it solves Collect user-entered data in search forms, filters, and custom fields. ## How to use it Pick input type in Inspector → set label, validation, default value, prefix/suffix icons. ## Examples Example solves: search box "Find campgrounds" · date range for booking · file upload for documents · lookup to Table record. ## Related topics Form component --- # Text URL: /mbrix/application-builder/components/text Plain text or dynamic {{ binding }} with font size, weight, color, and alignment. *** title: "Text" description: "Plain text or dynamic {{ binding }} with font size, weight, color, and alignment." ------------------------------------------------------------------------------------------------ **Category:** Commonly Used ## What is it? Plain text or dynamic `{{ binding }}` with font size, weight, color, and alignment. ## Problems it solves Every screen needs labels, titles, descriptions, and live data display without building custom typography. ## How to use it Drag Text onto canvas → Inspector: set content (static or `{{ expression }}`) → style appearance. ## Examples Example solves: page title "Welcome back, `{{ userDetails.userName }}`" · KPI label "Total bookings: `{{ count.data }}`" · section heading on a dashboard. ## Common mistakes * Forgetting `{{ }}` for dynamic content — text stays static. --- # Single Page walkthrough URL: /mbrix/application-builder/walkthroughs/w1 Build a simple page with Text, Button, and a variable binding. *** title: "Single Page walkthrough" description: "Build a simple page with Text, Button, and a variable binding." -----------------------------------------------------------------------------
  1. Advance Builder → + CreatePage → name it → Create.
  2. Drag Text and Button onto the canvas.
  3. Inspector: set labels and styling.
  4. Code panel (Cmd+J): add a Variable → bind Text to `{{ myVar }}`.
  5. Button → On click → Notify "Hello!".
  6. Preview → test → Save.
Note: Single pages have no public /apps URL — use Application for that.
--- # Multi-screen Application walkthrough URL: /mbrix/application-builder/walkthroughs/w2 Shell, navigation, and multiple screens — like Recreation.gov. *** title: "Multi-screen Application walkthrough" description: "Shell, navigation, and multiple screens — like Recreation.gov." -----------------------------------------------------------------------------
  1. + CreateApplication → name + slug (e.g. my-demo).
  2. Design Shell: Navigation + Outlet (pre-seeded).
  3. Screens panel: add screens (e.g. About → route about).
  4. Design each screen's canvas.
  5. Wire Navigation → Navigate actions to routes.
  6. Save → open /apps/my-demo and /apps/my-demo/about.
--- # Data-driven page walkthrough URL: /mbrix/application-builder/walkthroughs/w3 Embed List View and Reports from existing MPilot assets. *** title: "Data-driven page walkthrough" description: "Embed List View and Reports from existing MPilot assets." -----------------------------------------------------------------------
  1. Confirm Data Grid and Report exist (create in their modules if needed).
  2. Open or create a page/screen in Advance Builder.
  3. Drag List View → Inspector → select Data Grid.
  4. Drag Reports → Inspector → select Report.
  5. Optional: Code panel Query → bind Text to row count.
  6. Preview → Save.
--- # API Reference URL: /mbrix/workflows/api-reference Complete API reference for Monetize360 platform *** title: API Reference description: Complete API reference for Monetize360 platform ------------------------------------------------------------ # API Reference Monetize360 provides a comprehensive REST API for programmatic access to all platform features. ## Base URL ``` https://api.monetize360.com/v1 ``` ## Authentication All API requests require authentication using Bearer tokens: ```bash curl -H "Authorization: Bearer YOUR_API_TOKEN" \ https://api.monetize360.com/v1/workflows ``` ## API Endpoints ### Workflows Execute and manage workflows: ```http POST /workflows/{workflowId}/execute GET /workflows/{workflowId} GET /workflows/{workflowId}/executions GET /workflows/{workflowId}/executions/{executionId} ``` ### Objects (Data Models) Manage data models: ```http GET /mobjects POST /mobjects GET /mobjects/{mobjectId} PUT /mobjects/{mobjectId} DELETE /mobjects/{mobjectId} ``` ### MData (Records) CRUD operations on records: ```http POST /mobjects/{mobjectId}/mdata GET /mobjects/{mobjectId}/mdata/{mdataId} PUT /mobjects/{mobjectId}/mdata/{mdataId} DELETE /mobjects/{mobjectId}/mdata/{mdataId} GET /mobjects/{mobjectId}/mdata ``` ## Execute Workflow Start a workflow execution: ```http POST /workflows/{workflowId}/execute Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN { "data": { "customerId": "cust-123", "amount": 250.00, "action": "process" }, "async": false } ``` ### Response ```json { "executionId": "exec-789-xyz", "status": "completed", "startedAt": "2024-01-15T10:30:00Z", "completedAt": "2024-01-15T10:30:15Z", "output": { "orderId": "ord-456", "status": "success", "result": {...} } } ``` ## Query MData Query records with filters: ```http GET /mobjects/{mobjectId}/mdata?filter=status:eq:active&limit=50&offset=0 Authorization: Bearer YOUR_API_TOKEN ``` ### Query Parameters | Parameter | Type | Description | | --------- | ------- | ---------------------------------------- | | `filter` | string | Filter expression | | `limit` | integer | Maximum records to return (default: 50) | | `offset` | integer | Number of records to skip | | `sort` | string | Sort field and direction | | `fields` | string | Comma-separated list of fields to return | ### Filter Syntax ``` field:operator:value ``` Operators: * `eq` - Equals * `ne` - Not equals * `gt` - Greater than * `lt` - Less than * `gte` - Greater than or equal * `lte` - Less than or equal * `in` - In array * `contains` - Contains substring ## Create MData Insert a new record: ```http POST /mobjects/{mobjectId}/mdata Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN { "data": { "name": "John Doe", "email": "john@example.com", "status": "active", "tier": "premium" } } ``` ### Response ```json { "id": "7f8a2ea8-6d9a-5f3b-b9f7-9f7b6d9a2eb1", "mobjectId": "3f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea9", "data": { "name": "John Doe", "email": "john@example.com", "status": "active", "tier": "premium" }, "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T10:30:00Z" } ``` ## Update MData Update an existing record: ```http PUT /mobjects/{mobjectId}/mdata/{mdataId} Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN { "data": { "status": "inactive", "deactivatedAt": "2024-01-15T10:30:00Z" } } ``` ## Delete MData Delete a record: ```http DELETE /mobjects/{mobjectId}/mdata/{mdataId} Authorization: Bearer YOUR_API_TOKEN ``` ### Response ```json { "success": true, "message": "Record deleted successfully" } ``` ## Bulk Operations ### Bulk Insert Insert multiple records at once: ```http POST /mobjects/{mobjectId}/mdata/bulk Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN { "data": [ {"name": "Customer 1", "email": "c1@example.com"}, {"name": "Customer 2", "email": "c2@example.com"}, {"name": "Customer 3", "email": "c3@example.com"} ] } ``` ### Response ```json { "success": true, "totalProcessed": 3, "created": 3, "failed": 0, "data": [...] } ``` ## Error Handling All errors follow a consistent format: ```json { "error": { "code": "VALIDATION_ERROR", "message": "Invalid email address format", "details": { "field": "email", "value": "invalid-email" }, "timestamp": "2024-01-15T10:30:00Z" } } ``` ### HTTP Status Codes | Code | Description | | ---- | --------------------- | | 200 | Success | | 201 | Created | | 400 | Bad Request | | 401 | Unauthorized | | 403 | Forbidden | | 404 | Not Found | | 429 | Too Many Requests | | 500 | Internal Server Error | ## Rate Limiting API requests are rate limited: * **Standard**: 100 requests per minute * **Premium**: 1000 requests per minute * **Enterprise**: Custom limits Rate limit headers: ``` X-RateLimit-Limit: 100 X-RateLimit-Remaining: 95 X-RateLimit-Reset: 1705363260 ``` ## Pagination Large result sets are paginated: ```http GET /mobjects/{mobjectId}/mdata?limit=50&offset=0 ``` Response includes pagination metadata: ```json { "data": [...], "pagination": { "total": 500, "limit": 50, "offset": 0, "hasMore": true } } ``` ## Webhooks Configure webhooks to receive real-time notifications: ```http POST /webhooks Content-Type: application/json Authorization: Bearer YOUR_API_TOKEN { "url": "https://your-app.com/webhook", "events": ["workflow.completed", "mdata.created"], "secret": "your-webhook-secret" } ``` ### Webhook Payload ```json { "event": "workflow.completed", "timestamp": "2024-01-15T10:30:00Z", "data": { "workflowId": "workflow-uuid", "executionId": "execution-uuid", "status": "completed", "output": {...} } } ``` ## SDK Support Official SDKs available: * **JavaScript/TypeScript**: `npm install @monetize360/sdk` * **Python**: `pip install monetize360` * **Java**: Maven/Gradle packages * **Go**: `go get github.com/monetize360/sdk-go` ### JavaScript Example ```javascript import { Monetize360Client } from '@monetize360/sdk'; const client = new Monetize360Client({ apiKey: 'YOUR_API_TOKEN', baseUrl: 'https://api.monetize360.com/v1' }); // Execute workflow const result = await client.workflows.execute('workflow-id', { data: { customerId: 'cust-123' } }); // Query MData const records = await client.mdata.query('mobject-id', { filter: 'status:eq:active', limit: 50 }); ``` ### Python Example ```python from monetize360 import Client client = Client(api_key='YOUR_API_TOKEN') # Execute workflow result = client.workflows.execute( workflow_id='workflow-id', data={'customerId': 'cust-123'} ) # Query MData records = client.mdata.query( mobject_id='mobject-id', filter='status:eq:active', limit=50 ) ``` ## Best Practices 1. **Use API Keys Securely**: Store in environment variables 2. **Handle Rate Limits**: Implement exponential backoff 3. **Validate Input**: Check data before sending 4. **Use Pagination**: For large datasets 5. **Handle Errors**: Implement proper error handling 6. **Use Webhooks**: For real-time updates 7. **Cache Responses**: When appropriate 8. **Monitor Usage**: Track API consumption ## Testing Use the API sandbox for testing: ``` https://sandbox.monetize360.com/v1 ``` Test credentials are provided in your developer portal. ## Support * **API Status**: [https://status.monetize360.com](https://status.monetize360.com) * **Documentation**: [https://docs.monetize360.com](https://docs.monetize360.com) * **Support**: [support@monetize360.com](mailto:support@monetize360.com) * **Community**: [https://community.monetize360.com](https://community.monetize360.com) --- # Functions Overview URL: /mbrix/workflows/functions Complete reference for all Monetize360 workflow functions *** title: Functions Overview description: Complete reference for all Monetize360 workflow functions ---------------------------------------------------------------------- # Functions Overview Monetize360 provides a comprehensive library of functions to build powerful workflows. Functions are organized into simple, easy-to-understand categories that match how you work. ## Function Categories ### CRUD Operations Create, read, update, and delete data in your Objects: * [Create or Update Record](/mbrix/workflows/functions/crud-operations/insert-mdata) - Add a new record or update an existing one * [Insert Workflow Tracker](/mbrix/workflows/functions/crud-operations/insert-workflow-tracker) - Insert or update workflow tracker records with auto-generated request ID * [Get Single Record](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Find and retrieve one record from a table * [Get Multiple Records](/mbrix/workflows/functions/crud-operations/multiple-record-fetch-mdata) - Execute a query and retrieve multiple records from a table * [Bulk Insert Records](/mbrix/workflows/functions/crud-operations/bulk-insert-mdata) - Add multiple records at once * [Delete Record](/mbrix/workflows/functions/crud-operations/delete-mdata) - Remove a single record from a table * [Delete All Records](/mbrix/workflows/functions/crud-operations/delete-all-mdata) - Delete all data from an Object table (non-audit enabled only) * Delete Multiple Records - Remove multiple records from a table (coming soon) ### User Interactions Interact with users through emails and action requests: * [Send Email](/mbrix/workflows/functions/user-interactions/email-notification) - Send an email to one or more recipients * [Assign Task](/mbrix/workflows/functions/user-interactions/user-action) - Create a task for someone to complete ### System Functions Core workflow logic, data processing, and utilities: * [Run Sub-Workflow](/mbrix/workflows/functions/system-functions/subflow) - Run another workflow from within this workflow * [Loop Through Items](/mbrix/workflows/functions/system-functions/foreach) - Repeat the same actions for each item in a list * [Run JavaScript Code](/mbrix/workflows/functions/system-functions/javascript) - Write and run custom JavaScript code * [Calculate Expression](/mbrix/workflows/functions/system-functions/expression) - Perform calculations and formulas * [Generate PDF](/mbrix/workflows/functions/system-functions/html-to-pdf) - Convert HTML templates to PDF documents * [Export Data to CSV](/mbrix/workflows/functions/system-functions/export) - Execute a query and convert results to CSV file * [Convert JSON to CSV](/mbrix/workflows/functions/system-functions/json-to-csv) - Convert JSON array data to CSV format and save as a file * [Parse CSV/Excel File](/mbrix/workflows/functions/system-functions/parse-csv) - Parse CSV and Excel files from file storage and convert them to JSON format * [Parse Bank Statement](/mbrix/workflows/functions/system-functions/parse-statement) - Parse bank statements and other financial documents from PDF, XML, EDI, and Excel formats * [Statement Parser](/mbrix/workflows/functions/system-functions/statement-parser) - Parse bank statements from various formats including PDF, XML, EDI and Excel * [Statement Processor](/mbrix/workflows/functions/system-functions/statement-processor) - Process bank statements by mapping categories, forex rates, and other data * [Trigger Agent](/mbrix/workflows/functions/system-functions/trigger-agent) - Trigger an AI agent chat with templated user queries * [Pipeline Query](/mbrix/workflows/functions/system-functions/pipeline-query) - Execute a query, create a materialized view, and optionally write results to an Object * [Update Execution Secondary Status](/mbrix/workflows/functions/system-functions/update-execution-secondary-status) - Update the secondary status of the current MFlow execution with custom text * [ECR Analysis](/mbrix/workflows/functions/system-functions/ecr-analysis) - Analyze ECR data for financial insights * [Intra-Bank Fee Detail Chart](/mbrix/workflows/functions/system-functions/intra-bank-fee-detail-chart) - Generate chart data for intra-bank fee analysis showing potential savings * [Intra-Bank Fee Detail Report](/mbrix/workflows/functions/system-functions/intra-bank-fee-detail-report) - Generate detailed reports for intra-bank fee analysis with transaction-level savings * [Level 1 Analysis](/mbrix/workflows/functions/system-functions/level1-analysis) - Analyze intra-bank fee data to generate summary reports with rate comparisons and potential savings * [Potential Savings Intra-Bank](/mbrix/workflows/functions/system-functions/potential-saving-intra-bank) - Calculate potential savings summary from intra-bank fee analysis * [Potential Savings Multi-Bank](/mbrix/workflows/functions/system-functions/potential-saving-multi-bank) - Calculate potential savings summary from multi-bank fee analysis * [Resolve Lookup Field](/mbrix/workflows/functions/system-functions/resolve-lookup-field) - Resolve lookup fields by finding MData records based on field name and value * [Resolve Picklist Field](/mbrix/workflows/functions/system-functions/resolve-picklist-field) - Resolve picklist fields by finding picklist items by name for a given category * [Multi-Bank Fee Analysis](/mbrix/workflows/functions/system-functions/multi-bank-fee-analysis) - Generate comprehensive multi-bank fee analysis reports comparing fees across banks by category * [Run Report](/mbrix/workflows/functions/system-functions/run-report) - Execute reports based on MReportMaster configuration and return report data * [Process Auto-Debit Payment](/mbrix/workflows/functions/system-functions/auto-debit) - Process automatic debit payments using Stripe * [Load Data from Database](/mbrix/workflows/functions/system-functions/db-data-load) - Execute SQL queries against database connections and load results into Objects * [Load Data from S3](/mbrix/workflows/functions/system-functions/s3-data-load) - Load data from S3 files and store in Objects with optional batch processing * Approval Workflow - Create multi-stage approval workflows (coming soon) ### External API Connect with external systems and services: * [Call External API](/mbrix/workflows/functions/external-api/call-external-api) - Connect to an external service or website ### Triggers Start workflows automatically or manually: * Manual Start - Start the workflow manually (coming soon) * Scheduled Start - Run the workflow on a schedule (coming soon) * Form Submission - Start workflow when a form is submitted (coming soon) ## Understanding Function Properties Each function has the following properties: ### Execution Mode * **SYNC**: Waits for completion before proceeding to next node * **ASYNC**: Triggers operation and continues immediately ### Block Type * **NATIVE**: Built-in platform functions * **CUSTOM**: User-created custom functions * **FUNCTION**: Reusable function blocks * **API**: API integration functions ### Input/Output Schemas Functions define clear input and output schemas using JSON Schema format. This ensures: * Type safety for your data * Clear documentation of required parameters * Validation of inputs before execution ## Common Patterns ### Simple CRUD Pattern ``` Start → FetchMData → UpdateLogic → InsertMData → End ``` ### User Approval Pattern ``` Start → InsertMData → UserAction → ApprovalAction → UpdateStatus → EmailNotification → End ``` ### Data Processing Pattern ``` Start → FetchMData → JavaScript (transform) → BulkInsertMData → End ``` ### External Integration Pattern ``` Start → FetchMData → CallExternalApi → ProcessResponse → InsertMData → End ``` ## Using Functions in Workflows ### 1. Drag and Drop Simply drag functions from the function palette into your workflow canvas. ### 2. Configure Inputs Each function has a configuration panel where you can: * Set required parameters * Map data from previous nodes * Define static values * Configure conditional logic ### 3. Connect Nodes Connect function nodes to define the execution flow of your workflow. ### 4. Reference Outputs Access outputs from previous nodes using expressions: ```json { "customerId": "${fetchCustomer.output.id}", "orderTotal": "${calculateTotal.output.amount}" } ``` ## Function Categories Explained ### Why These Categories? We've organized functions to match how people naturally think about workflows: **CRUD Operations** - "I need to work with data" * All database operations in one place * Create, read, update, delete records * Bulk operations for efficiency **User Interactions** - "I need to involve people" * Email notifications * Wait for user actions * Interactive workflows **System Functions** - "I need to process and control" * Workflow control (loops, subflows) * Data transformation (JavaScript, expressions) * Document generation * Reporting **External API** - "I need to connect to other systems" * REST API integration * Third-party services * External data sources **Triggers** - "How do I start workflows?" * Manual execution * Scheduled runs * Form submissions * API triggers ## Best Practices ### Choosing the Right Function 1. **Start Simple**: Use basic CRUD operations before adding complexity 2. **Batch Operations**: Use bulk functions for multiple records 3. **Reusable Logic**: Create SubFlows for repeated operations 4. **Error Handling**: Always plan for failure scenarios 5. **User Experience**: Use UserActions and EmailNotifications for clear communication ### Performance Tips * Use BulkInsertMData instead of multiple InsertMData calls * Fetch only the fields you need * Use expressions for simple calculations * Use JavaScript for complex transformations * Implement pagination for large datasets ### Security Considerations * Validate all user inputs * Use role-based access control * Store sensitive data encrypted * Audit all data modifications * Implement approval workflows for critical operations ## Function Documentation Structure Each function page includes: * **Overview**: What the function does * **Properties**: Execution mode, type, ID * **Input Schema**: Required and optional parameters * **Examples**: Real-world JSON examples * **Use Cases**: Common scenarios * **Error Handling**: How to handle failures * **Best Practices**: Tips for optimal use * **Related Functions**: Similar or complementary functions ## Getting Help * **Inline Help**: Hover over parameters in the workflow designer * **Function Documentation**: Detailed docs for each function * **Examples**: Pre-built workflow templates * **Community**: Ask questions in the community forum * **Support**: Contact support for assistance ## Next Steps Ready to start building workflows? 1. **Learn the Basics**: Start with [CRUD Operations](/mbrix/workflows/functions/crud-operations/insert-mdata) 2. **Add Logic**: Explore [System Functions](/mbrix/workflows/functions/system-functions/subflow) 3. **Connect Systems**: Use [External API](/mbrix/workflows/functions/external-api/call-external-api) 4. **Engage Users**: Implement [User Interactions](/mbrix/workflows/functions/user-interactions/email-notification) 5. **Automate**: Set up [Triggers](/mbrix/workflows/functions/triggers) --- # Getting Started URL: /mbrix/workflows/getting-started Learn how to get started with Monetize360 workflow automation platform *** title: Getting Started description: Learn how to get started with Monetize360 workflow automation platform ----------------------------------------------------------------------------------- # Getting Started with Monetize360 This guide will help you understand the fundamentals of Monetize360 and create your first workflow. ## What is Monetize360? Monetize360 is an enterprise workflow automation platform that enables you to build complex business processes through a visual interface. It provides: * **Visual Workflow Designer**: Drag-and-drop interface for building workflows * **Rich Function Library**: 25+ pre-built functions for common operations * **Custom Data Models**: Define Objects to store your business data * **Integration Capabilities**: Connect with external APIs, databases, and services * **Approval Workflows**: Built-in support for multi-stage approvals * **Real-time Execution**: Monitor workflow execution in real-time ## Key Components ### Objects (Data Models) Objects define your data structure. Each Object contains: * Fields with specific data types (text, number, date, etc.) * Reference fields for relationships * Picklist fields for dropdown values * Validation rules ### MData (Records) MData represents individual records stored in Objects. Each MData record: * Has a unique UUID * Contains data conforming to the Object schema * Tracks creation and modification timestamps * Supports relationships with other MData records ### MFlows (Workflows) MFlows are visual workflows composed of: * **Nodes**: Function blocks that perform specific operations * **Edges**: Connections between nodes defining execution flow * **Variables**: Data passed between nodes * **Triggers**: Events that start workflow execution ## Creating Your First Workflow ### Step 1: Define Your Data Model First, create an Object to store your data: 1. Navigate to **Data Models** → **New Object** 2. Define your object name (e.g., "Customer") 3. Add fields (name, email, phone, etc.) 4. Save your Object ### Step 2: Build a Workflow Create a new workflow: 1. Go to **Workflows** → **New Workflow** 2. Add a **Start** node 3. Drag function nodes from the palette 4. Configure each node's parameters 5. Connect nodes to define flow ### Step 3: Configure Functions Each function node requires input configuration: ```json { "mobjectId": "uuid-of-your-mobject", "data": { "name": "John Doe", "email": "john@example.com" } } ``` ### Step 4: Test Your Workflow Test the workflow before deployment: 1. Click **Test Run** 2. Provide test input data 3. Monitor execution in real-time 4. Review outputs and logs ### Step 5: Deploy and Monitor Deploy your workflow: 1. Click **Deploy** 2. Configure triggers (API, schedule, manual) 3. Monitor executions in the dashboard 4. View logs and troubleshoot issues ## Common Patterns ### Insert and Fetch Pattern ``` Start → InsertMData → FetchMData → End ``` Insert a record and then retrieve it with related data. ### Approval Workflow Pattern ``` Start → UserAction → ApprovalAction → InsertMData → End ``` Create a multi-stage approval process with email notifications. ### Data Loading Pattern ``` Start → S3DataLoad → ForEach → InsertMData → End ``` Load data from S3 and process each record. ## Best Practices ### Error Handling Always configure error handling for critical operations: * Use condition nodes to check for errors * Implement retry logic for API calls * Log errors for debugging ### Performance Optimization * Use bulk operations when processing multiple records * Leverage PipelineQuery for complex data operations * Minimize external API calls ### Security * Store sensitive data in encrypted fields * Use role-based access control * Validate input data before processing ## Next Steps * Explore [CRUD Operations](/mbrix/workflows/functions/crud-operations/insert-mdata) * Learn about [System Functions](/mbrix/workflows/functions/system-functions/subflow) * Review [External API Integration](/mbrix/workflows/functions/external-api/call-external-api) * Understand [User Interactions](/mbrix/workflows/functions/user-interactions/email-notification) * Check out [API Reference](/mbrix/workflows/api-reference) --- # Bulk Insert Records URL: /mbrix/workflows/functions/crud-operations/bulk-insert-mdata Add multiple records to a table at once *** title: Bulk Insert Records description: Add multiple records to a table at once ---------------------------------------------------- # Bulk Insert Records Add multiple records to a table in a single operation. This is faster than adding records one by one and helps keep your data organized. **Technical Name**: `BulkInsertMDataFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: CRUD Operations * **Function ID**: `8a1b2c3d-4e5f-6789-abcd-ef0123456789` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ----------- | ------------- | ------------------------------------------ | | `mobjectId` | string (uuid) | The UUID of the Object to insert data into | | `dataArray` | array | Array of data objects to insert | ### Optional Parameters | Parameter | Type | Description | | --------- | ------ | -------------------------------------------------------- | | `data` | object | Constant data to be merged into each record in the array | ## Input Example ```json { "mobjectId": "3f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea9", "dataArray": [ { "name": "John Doe", "email": "john@example.com", "status": "Active" }, { "name": "Jane Smith", "email": "jane@example.com", "status": "Active" } ], "data": { "source": "API Import", "importedAt": "2024-01-15T10:30:00Z" } } ``` ## Output Schema | Field | Type | Description | | ---------------- | ------- | --------------------------------------------------- | | `success` | boolean | Whether the bulk operation was successful | | `data` | array | Array of created MData records | | `totalProcessed` | integer | Total number of records processed | | `errors` | array | Array of any errors that occurred during processing | ## Performance Benefits BulkInsertMData provides significant performance improvements: * **Single Database Transaction**: All inserts in one transaction * **Reduced Network Overhead**: One API call vs. many * **Optimized Validation**: Batch validation of all records * **Faster Execution**: Up to 100x faster than individual inserts ## Best Practices 1. **Batch Size**: Keep batches between 100-1000 records for optimal performance 2. **Validation**: Pre-validate data before bulk insert to avoid partial failures 3. **Error Handling**: Always check the errors array in the response 4. **Constant Data**: Use the `data` parameter for fields common to all records ## Related Functions * [InsertMData](/mbrix/workflows/functions/crud-operations/insert-mdata) - Insert single records * [ForEach](/mbrix/workflows/functions/system-functions/foreach) - Process arrays with custom logic --- # Delete All Records URL: /mbrix/workflows/functions/crud-operations/delete-all-mdata Delete all data from an Object table. Only works for non-audit enabled Objects to prevent audit history loss *** title: Delete All Records description: Delete all data from an Object table. Only works for non-audit enabled Objects to prevent audit history loss ------------------------------------------------------------------------------------------------------------------------- # Delete All Records Delete all data from an Object table using a TRUNCATE operation. This function permanently removes all records from the specified Object. **This operation cannot be undone.** **Technical Name**: `DeleteAllMDataFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: CRUD Operations * **Function ID**: `5f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea8` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ----------- | ------------- | --------------------------------------------- | | `mobjectId` | string (UUID) | ID of the Object whose data should be deleted | ## Input Example ```json { "mobjectId": "123e4567-e89b-12d3-a456-426614174000" } ``` ## Output Schema | Field | Type | Description | | ----------- | ------------- | ------------------------------------ | | `success` | boolean | Whether the operation was successful | | `mobjectId` | string (UUID) | ID of the Object that was processed | ## Output Example ### Success Response ```json { "success": true, "mobjectId": "123e4567-e89b-12d3-a456-426614174000" } ``` ### Error Response (Audit Enabled) ```json { "error": "Operation not allowed: Cannot truncate data for Object 'Customer' because audit is enabled. Truncating would result in loss of audit history." } ``` ## How It Works The function performs the following steps: 1. **Validates Input**: Checks that `mobjectId` is provided 2. **Checks Audit Status**: Verifies that the Object does not have audit enabled 3. **Checks Object Type**: Skips TRANSIENT objects (they don't have physical tables) 4. **Performs TRUNCATE**: Executes a TRUNCATE TABLE operation on the Object's table 5. **Returns Result**: Returns success status and the processed Object ID ## Restrictions ### Audit-Enabled Objects **This function will fail if the Object has audit enabled.** This restriction prevents loss of audit history. If you need to delete all data from an audit-enabled Object, you must: 1. Disable audit on the Object (if allowed) 2. Use individual delete operations instead 3. Or use a different approach that preserves audit history ### TRANSIENT Objects TRANSIENT Objects are skipped automatically as they don't have physical database tables. ## Use Cases ### Reset Test Data Clear all test data from a development Object: ```json { "mobjectId": "test-data-mobject-uuid" } ``` ### Data Cleanup Workflow Clean up temporary data in a workflow: ``` Start → ValidatePermissions → DeleteAllMData → LogCleanup → End ``` ### Bulk Data Reset Reset staging data before importing new data: ``` Start → DeleteAllMData → LoadDataFromS3 → ValidateData → End ``` ## Important Warnings ⚠️ **Permanent Deletion**: This operation permanently deletes all data and cannot be undone. ⚠️ **No Recovery**: Once executed, there is no way to recover the deleted data unless you have a backup. ⚠️ **Audit Protection**: The function automatically prevents deletion if audit is enabled to protect audit history. ⚠️ **No Confirmation**: The function executes immediately without additional confirmation prompts. ## Best Practices 1. **Backup First**: Always create a backup before using this function 2. **Verify Object**: Double-check the Object ID before execution 3. **Check Audit Status**: Verify that audit is disabled if you need to use this function 4. **Use in Workflows**: Consider adding validation steps in workflows before deletion 5. **Log Operations**: Log the deletion operation for audit purposes 6. **Test Environment**: Test the operation in a non-production environment first ## Related Functions * [Delete Record](/mbrix/workflows/functions/crud-operations/delete-mdata) - Delete a single record by ID * [Fetch MData](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Verify data before deletion * [Insert MData](/mbrix/workflows/functions/crud-operations/insert-mdata) - Add data back after deletion --- # Delete Record URL: /mbrix/workflows/functions/crud-operations/delete-mdata Remove a single record from a table *** title: Delete Record description: Remove a single record from a table ------------------------------------------------ # Delete Record Remove a specific record from a table by selecting which record to delete. This action cannot be undone. **Technical Name**: `DeleteMDataFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: CRUD Operations * **Function ID**: `4f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea8` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ----------- | ------------- | ----------------------------------- | | `id` | string (uuid) | ID of the MData record to delete | | `mobjectId` | string (uuid) | The Object ID containing the record | ## Input Example ```json { "mobjectId": "3f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea9", "id": "7f8a2ea8-6d9a-5f3b-b9f7-9f7b6d9a2eb1" } ``` ## Output Schema | Field | Type | Description | | --------- | ------- | ----------------------------------- | | `success` | boolean | Whether the deletion was successful | ## Workflow Example ``` Start → ValidatePermissions → FetchRecord → DeleteMData → LogDeletion → End ``` ## Best Practices 1. **Soft Delete**: Consider using a status field instead of hard delete 2. **Backup**: Create backups before bulk deletions 3. **Validation**: Always verify record exists before deletion 4. **Permissions**: Check user permissions before allowing deletion 5. **Audit Trail**: Log deletions for compliance and tracking ## Related Functions * [Delete All Records](/mbrix/workflows/functions/crud-operations/delete-all-mdata) - Delete all data from an Object table * [FetchMData](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Fetch record before deletion * [InsertMData](/mbrix/workflows/functions/crud-operations/insert-mdata) - Update instead of delete (soft delete) **⚠️ Warning**: Deletion is permanent and cannot be undone. --- # Get Single Record URL: /mbrix/workflows/functions/crud-operations/fetch-mdata Find and retrieve one record from a table *** title: Get Single Record description: Find and retrieve one record from a table ------------------------------------------------------ # Get Single Record Search for and retrieve a single record from a table based on your search criteria. Use this when you need to find one specific record. **Technical Name**: `FetchMDataFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: CRUD Operations * **Function ID**: `2f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea1` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ------------- | ------ | ----------------------------------------------------- | | `queryMaster` | object | Query configuration object for building the SQL query | ## Input Example ```json { "queryMaster": { "mobjectId": "3f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea9", "filters": [ { "field": "email", "operator": "equals", "value": "john@example.com" } ], "fields": ["id", "name", "email", "status"] } } ``` ## Query Master Configuration The `queryMaster` object supports the following properties: | Property | Type | Description | | ----------- | ------------- | -------------------------------------- | | `mobjectId` | string (uuid) | The Object to query | | `filters` | array | Array of filter conditions | | `fields` | array | Fields to return in the result | | `orderBy` | object | Sort configuration | | `limit` | integer | Maximum number of records (default: 1) | ### Filter Operators Supported operators in filter conditions: * `equals` - Exact match * `notEquals` - Not equal to * `contains` - Contains substring * `startsWith` - Starts with value * `endsWith` - Ends with value * `greaterThan` - Greater than * `lessThan` - Less than * `in` - Value in array * `isNull` - Field is null * `isNotNull` - Field is not null ## Output Schema Returns a single MData record with all requested fields: ```json { "id": "7f8a2ea8-6d9a-5f3b-b9f7-9f7b6d9a2eb1", "name": "John Doe", "email": "john@example.com", "status": "Active", "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T10:30:00Z" } ``` ## Use Cases ### Fetch by ID Retrieve a specific record by its ID: ```json { "queryMaster": { "mobjectId": "customer-mobject-id", "filters": [ { "field": "id", "operator": "equals", "value": "7f8a2ea8-6d9a-5f3b-b9f7-9f7b6d9a2eb1" } ] } } ``` ### Fetch by Email Find a customer by email address: ```json { "queryMaster": { "mobjectId": "customer-mobject-id", "filters": [ { "field": "email", "operator": "equals", "value": "customer@example.com" } ], "fields": ["id", "name", "email", "phone", "address"] } } ``` ## Workflow Example ``` Start → FetchMData → CheckIfExists → ProcessRecord → End ``` ## Error Handling ### Record Not Found When no record matches the query: ```json { "error": "No record found matching the query criteria", "timestamp": "2024-01-15T10:30:00Z" } ``` ## Best Practices 1. **Always specify required fields** to minimize data transfer 2. **Use indexed fields** in filters for better performance 3. **Handle null results** gracefully in your workflow 4. **Cache frequently accessed data** to reduce database load ## Related Functions * [MultipleRecordFetchMData](/mbrix/workflows/functions/crud-operations/multiple-record-fetch-mdata) - Fetch multiple records * [InsertMData](/mbrix/workflows/functions/crud-operations/insert-mdata) - Insert or update records --- # Create or Update Record URL: /mbrix/workflows/functions/crud-operations/insert-mdata Add a new record to a table or update an existing record if it already exists. You can also link this record to other records in your system. *** title: Create or Update Record description: Add a new record to a table or update an existing record if it already exists. You can also link this record to other records in your system. *** **Technical Name**: `InsertMDataFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: CRUD Operations * **Function ID**: `3f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea9` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------ | ---------------------------- | | `data` | object | The data to insert or update | ### Optional Parameters | Parameter | Type | Description | | ----------- | ------------- | -------------------------------------------------------- | | `id` | string (uuid) | ID of the record to update (creates new if not provided) | | `mobjectId` | string (uuid) | The Object to insert data into | ## Input Example ```json { "mobjectId": "3f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea9", "data": { "name": "John Doe", "email": "john@example.com", "phone": "+1234567890", "status": "Active" } } ``` ## Output Schema The function returns the created or updated MData record: | Field | Type | Description | | ----------- | ------------------ | ------------------------------------------ | | `id` | string (uuid) | The unique identifier of the record | | `mobjectId` | string (uuid) | The Object ID this record belongs to | | `data` | object | The stored data | | `createdAt` | string (date-time) | Timestamp when the record was created | | `updatedAt` | string (date-time) | Timestamp when the record was last updated | ## Output Example ```json { "id": "7f8a2ea8-6d9a-5f3b-b9f7-9f7b6d9a2eb1", "mobjectId": "3f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea9", "data": { "name": "John Doe", "email": "john@example.com", "phone": "+1234567890", "status": "Active" }, "createdAt": "2024-01-15T10:30:00Z", "updatedAt": "2024-01-15T10:30:00Z" } ``` ## Use Cases ### Creating New Records Use InsertMData to create new records without providing an `id`: ```json { "mobjectId": "customer-mobject-id", "data": { "name": "Jane Smith", "email": "jane@example.com" } } ``` ### Updating Existing Records Provide an `id` to update an existing record: ```json { "id": "existing-record-id", "mobjectId": "customer-mobject-id", "data": { "status": "Inactive", "lastModified": "2024-01-15" } } ``` ### Working with Relationships InsertMData supports relationships through reference fields: ```json { "mobjectId": "order-mobject-id", "data": { "orderNumber": "ORD-001", "customerId": "customer-record-id", "items": [ {"productId": "prod-1", "quantity": 2}, {"productId": "prod-2", "quantity": 1} ] } } ``` ## Workflow Example A typical workflow using InsertMData: ``` Start → ValidateInput → InsertMData → EmailNotification → End ``` ## Error Handling Common errors and how to handle them: ### Validation Errors ```json { "error": "Validation failed: email field is required", "timestamp": "2024-01-15T10:30:00Z" } ``` ### Permission Errors ```json { "error": "User does not have permission to insert data in this Object", "timestamp": "2024-01-15T10:30:00Z" } ``` ## Best Practices 1. **Always validate input data** before calling InsertMData 2. **Use bulk operations** when inserting multiple records (see BulkInsertMData) 3. **Handle errors gracefully** with proper error checking nodes 4. **Set appropriate field mappings** for reference fields 5. **Use transactions** for related inserts to maintain data integrity ## Related Functions * [BulkInsertMData](/mbrix/workflows/functions/crud-operations/bulk-insert-mdata) - Insert multiple records at once * [FetchMData](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Retrieve records after insertion * [DeleteMData](/mbrix/workflows/functions/crud-operations/delete-mdata) - Delete records ## External Data Source Configuration The `mobjectId` parameter supports external data source configuration for dropdown selection: ```json { "externalDataSource": { "source": "mobject", "sourceField": "name" } } ``` This allows you to select the Object by name in the workflow designer. --- # Insert Workflow Tracker URL: /mbrix/workflows/functions/crud-operations/insert-workflow-tracker Insert or update workflow tracker records with auto-generated request ID and workflow context information *** title: Insert Workflow Tracker description: Insert or update workflow tracker records with auto-generated request ID and workflow context information ---------------------------------------------------------------------------------------------------------------------- # Insert Workflow Tracker Insert or update records in workflow tracker objects. This function automatically generates a unique request ID and extracts workflow execution context (flow ID, execution ID) from the current workflow. **Technical Name**: `InsertWorkflowTrackerFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: CRUD Operations * **Function ID**: `4a2b1cd9-7e8f-4c3b-b9d6-5f7a9b1c2d3e` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ----------- | ------------- | ---------------------------------------------- | | `mobjectId` | string (uuid) | UUID of the workflow tracker Object | | `data` | object | Data object containing workflow tracker fields | ### Optional Parameters | Parameter | Type | Description | | --------- | ------------- | -------------------------------------------------------------- | | `id` | string (uuid) | UUID of existing record to update. Omit to create a new record | ## Auto-Generated Fields The function automatically adds these fields if not provided: | Field | Description | | -------------- | ------------------------------------------------------- | | `request_id` | 7-digit base32 identifier (e.g., "ABC2XYZ") | | `flow_id` | Current workflow ID (extracted from execution context) | | `execution_id` | Current execution ID (extracted from execution context) | ## Input Example ### Create New Tracker Record ```json { "mobjectId": "workflow-tracker-mobject-uuid", "data": { "reference_field": "customer-uuid", "status": "in_progress", "notes": "Processing customer order" } } ``` ### Update Existing Tracker Record ```json { "mobjectId": "workflow-tracker-mobject-uuid", "id": "existing-record-uuid", "data": { "status": "completed", "notes": "Order processed successfully" } } ``` ### With Custom Request ID ```json { "mobjectId": "workflow-tracker-mobject-uuid", "data": { "request_id": "CUSTOM123", "reference_field": "order-uuid", "flow_type": "order_processing" } } ``` ## Output Schema | Field | Type | Description | | ------------- | ------------------ | -------------------------------------------------- | | `id` | string (uuid) | Unique identifier of the created or updated record | | `mflowId` | string (uuid) | ID of the workflow that executed this function | | `requestId` | string | Request ID (auto-generated or provided) | | `executionId` | string (uuid) | ID of the workflow execution | | `createdBy` | string | ID of the user who created the record | | `createdAt` | string (date-time) | Timestamp when the record was created | ## Output Example ```json { "id": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "mflowId": "f1a2b3c4-d5e6-f7a8-b9c0-d1e2f3a4b5c6", "requestId": "ABC2XYZ", "executionId": "e1f2a3b4-c5d6-e7f8-a9b0-c1d2e3f4a5b6", "createdBy": "user-uuid", "createdAt": "2024-01-20T14:30:22Z" } ``` ## Request ID Format Request IDs are 7-character base32 strings using characters: `ABCDEFGHJKLMNPQRSTUVWXYZ23456789` (excluding 0, 1, 8, 9 for clarity). **Examples**: `ABC2XYZ`, `KLM9NOP`, `2345DEF` ## Use Cases ### Track Workflow Execution Track each workflow execution with a unique request ID: ```json { "mobjectId": "workflow-tracker-mobject-uuid", "data": { "reference_field": "{{context.objectId}}", "status": "started" } } ``` ### Update Tracker Status Update tracker status as workflow progresses: ``` Start → InsertWorkflowTracker(status: "started") → ProcessData → InsertWorkflowTracker(status: "completed") → End ``` ## Related Functions * [Create or Update Record](/mbrix/workflows/functions/crud-operations/insert-mdata) - General purpose record creation/update * [Fetch Records](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Retrieve workflow tracker records * [Delete Record](/mbrix/workflows/functions/crud-operations/delete-mdata) - Remove workflow tracker records --- # Get Multiple Records URL: /mbrix/workflows/functions/crud-operations/multiple-record-fetch-mdata Execute a query and retrieve multiple records from a table *** title: Get Multiple Records description: Execute a query and retrieve multiple records from a table ----------------------------------------------------------------------- # Get Multiple Records Execute a query and retrieve multiple records from a table based on your search criteria. Use this when you need to find and process multiple records at once. **Technical Name**: `MultipleRecordFetchMDataFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: CRUD Operations * **Function ID**: `9e8cea51-9784-4df7-a100-db395bd84916` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ------------- | ------ | ----------------------------------------------------- | | `queryMaster` | object | Query configuration object for building the SQL query | ## Input Example ```json { "queryMaster": { "mobjectId": "3f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea9", "filters": [ { "field": "status", "operator": "equals", "value": "Active" } ], "fields": ["id", "name", "email", "status"], "orderBy": { "field": "createdAt", "direction": "desc" }, "limit": 100 } } ``` ## Query Master Configuration The `queryMaster` object supports the following properties: | Property | Type | Description | | ----------- | ------------- | ----------------------------------- | | `mobjectId` | string (uuid) | The Object to query | | `filters` | array | Array of filter conditions | | `fields` | array | Fields to return in the result | | `orderBy` | object | Sort configuration | | `limit` | integer | Maximum number of records to return | ### Filter Operators Supported operators in filter conditions: * `equals` - Exact match * `notEquals` - Not equal to * `contains` - Contains substring * `startsWith` - Starts with value * `endsWith` - Ends with value * `greaterThan` - Greater than * `lessThan` - Less than * `in` - Value in array * `isNull` - Field is null * `isNotNull` - Field is not null ## Output Schema | Field | Type | Description | | ---------- | ------ | ------------------------------- | | `dataList` | array | List of query result records | | `sql` | string | The SQL query that was executed | Each object in the `dataList` array contains the requested fields from the query. ## Output Example ```json { "dataList": [ { "id": "7f8a2ea8-6d9a-5f3b-b9f7-9f7b6d9a2eb1", "name": "John Doe", "email": "john@example.com", "status": "Active" }, { "id": "8g9b3fb9-7e0b-6g4c-c0g8-0g8c7e0b3fc2", "name": "Jane Smith", "email": "jane@example.com", "status": "Active" } ], "sql": "SELECT id, name, email, status FROM customer WHERE status = 'Active' ORDER BY createdAt DESC LIMIT 100" } ``` ## Use Cases ### Fetch All Active Records Retrieve all active records from a table: ```json { "queryMaster": { "mobjectId": "customer-mobject-id", "filters": [ { "field": "status", "operator": "equals", "value": "Active" } ], "orderBy": { "field": "name", "direction": "asc" }, "limit": 1000 } } ``` ### Fetch Records by Date Range Find records within a date range: ```json { "queryMaster": { "mobjectId": "order-mobject-id", "filters": [ { "field": "createdAt", "operator": "greaterThanOrEquals", "value": "2024-01-01" }, { "field": "createdAt", "operator": "lessThanOrEquals", "value": "2024-01-31" } ], "fields": ["id", "orderNumber", "totalAmount", "status"], "orderBy": { "field": "createdAt", "direction": "desc" } } } ``` ### Process Records in Loop Fetch multiple records and process them: ``` Start → MultipleRecordFetchMData → ForEach(ProcessRecord) → End ``` ## Field Resolution The function automatically resolves: * **Picklist values** - Converts picklist IDs to display names * **External data sources** - Resolves references to related records ## Error Handling ### No Records Found When no records match the query: ```json { "dataList": [], "sql": "SELECT id, name FROM customer WHERE status = 'Inactive'" } ``` ### Query Error When the query fails: ```json { "error": "Error executing MultipleRecordFetchMDataFunc: Invalid field name" } ``` ## Best Practices 1. **Use limit** to control the number of records returned 2. **Specify required fields** to minimize data transfer 3. **Use indexed fields** in filters for better performance 4. **Order results** for consistent processing 5. **Handle empty results** gracefully in your workflow ## Related Functions * [Get Single Record](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Fetch a single record * [Bulk Insert Records](/mbrix/workflows/functions/crud-operations/bulk-insert-mdata) - Insert multiple records * [Loop Through Items](/mbrix/workflows/functions/system-functions/foreach) - Process multiple records in a loop --- # Call External API URL: /mbrix/workflows/functions/external-api/call-external-api Connect to an external service or website *** title: Call External API description: Connect to an external service or website ------------------------------------------------------ # Call External API Connect to an external service or website to send or receive data. You can use this to integrate with other apps, send data to third-party services, or fetch information from external sources. **Technical Name**: `CallExternalApiFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: External API * **Function ID**: `8f7a2ea8-6d8a-4f2b-b8f6-9f6b6d8a2ea8` ## Input Schema ### Required Parameters | Parameter | Type | Description | | -------------- | ------------- | ----------------------------------------------------- | | `connectionId` | string (uuid) | Connection containing URL, method, auth, and defaults | ### Optional Parameters | Parameter | Type | Description | | ---------------- | ------- | ----------------------------------------------------- | | `headers` | object | Additional headers (overrides connection headers) | | `queryParams` | object | Additional query params (overrides connection params) | | `body` | string | JSON template with `{variable}` placeholders | | `bodyVariables` | object | Variables for `{placeholder}` substitution in body | | `timeoutSeconds` | integer | Request timeout in seconds (default: 30, max: 300) | ## Input Example ```json { "connectionId": "api-connection-uuid", "headers": { "X-Custom-Header": "value", "Accept": "application/json" }, "queryParams": { "page": 1, "limit": 50 }, "body": "{\"customerId\": \"{customerId}\", \"orderAmount\": {amount}}", "bodyVariables": { "customerId": "cust-123", "amount": 250.00 }, "timeoutSeconds": 60 } ``` ## Connection Configuration API connections store reusable configuration: ```json { "name": "Payment Gateway API", "url": "https://api.payment-gateway.com/v1", "method": "POST", "headers": { "Authorization": "Bearer ${API_KEY}", "Content-Type": "application/json" }, "timeout": 30 } ``` ## Output Schema | Field | Type | Description | | -------------- | ------- | ------------------------------------------ | | `success` | boolean | True if HTTP status 200-299 | | `statusCode` | integer | HTTP response status code | | `headers` | object | Response headers | | `responseBody` | any | Response body (parsed as JSON if possible) | ## Output Example ```json { "success": true, "statusCode": 200, "headers": { "content-type": "application/json", "x-rate-limit-remaining": "99" }, "responseBody": { "transactionId": "txn-789", "status": "completed", "amount": 250.00, "currency": "USD", "timestamp": "2024-01-15T10:30:00Z" } } ``` ## Use Cases ### Payment Processing Integrate with payment gateways: ``` Start → ValidatePayment → CallExternalApi(ProcessPayment) → UpdateOrder → End ``` ### Data Synchronization Sync data with external systems: ```json { "connectionId": "crm-api-connection", "body": "{\"name\": \"{customerName}\", \"email\": \"{email}\"}", "bodyVariables": { "customerName": "${fetchCustomer.output.name}", "email": "${fetchCustomer.output.email}" } } ``` ### Webhook Callbacks Send data to webhook endpoints: ```json { "connectionId": "webhook-connection", "body": "${prepareWebhookPayload.output.payload}" } ``` ## HTTP Methods Supported HTTP methods: * **GET**: Retrieve data * **POST**: Create resources * **PUT**: Update resources (full) * **PATCH**: Update resources (partial) * **DELETE**: Remove resources * **HEAD**: Get headers only * **OPTIONS**: Get supported methods ## Authentication ### Bearer Token ```json { "headers": { "Authorization": "Bearer ${API_TOKEN}" } } ``` ### API Key ```json { "headers": { "X-API-Key": "${API_KEY}" } } ``` ### Basic Auth ```json { "headers": { "Authorization": "Basic ${BASE64_CREDENTIALS}" } } ``` ## Error Handling ### HTTP Errors ```json { "success": false, "statusCode": 404, "headers": {...}, "responseBody": { "error": "Resource not found", "code": "NOT_FOUND" } } ``` ### Retry Logic Implement retry with exponential backoff: ``` Start → CallExternalApi → CheckStatus → Retry(if failed) → End ``` ## Best Practices 1. **Timeout Configuration**: Set appropriate timeouts for different APIs 2. **Error Handling**: Always check success field and status code 3. **Rate Limiting**: Implement rate limiting for external APIs 4. **Secrets Management**: Store API keys in environment variables 5. **Response Validation**: Validate response structure before processing 6. **Logging**: Log requests and responses for debugging 7. **Idempotency**: Use idempotency keys for critical operations ## Related Functions * [EmailNotification](/mbrix/workflows/functions/user-interactions/email-notification) - Send emails * [JavaScript](/mbrix/workflows/functions/system-functions/javascript) - Transform requests/responses * [SubFlow](/mbrix/workflows/functions/system-functions/subflow) - Modular API integration ## Workflow Example ``` Start → FetchOrder → PreparePayload → CallExternalApi(Payment Gateway) → CheckResponse → UpdateOrderStatus → EmailNotification → End ``` ## Limitations * Maximum request size: 10MB * Maximum response size: 50MB * Timeout range: 1-300 seconds * Maximum headers: 50 per request --- # Process Auto-Debit Payment URL: /mbrix/workflows/functions/system-functions/auto-debit Process automatic debit payments using Stripe payment gateway *** title: Process Auto-Debit Payment description: Process automatic debit payments using Stripe payment gateway -------------------------------------------------------------------------- # Process Auto-Debit Payment Process automatic debit payments from customer payment methods stored in Stripe. This function charges a customer's saved payment method for a specified amount, making it ideal for recurring payments, subscriptions, or automated billing. **Technical Name**: `AutoDebitFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `a1b2c3d4-e5f6-7890-abcd-ef1234567890` ## Input Schema ### Required Parameters | Parameter | Type | Description | | -------------- | ------------- | ------------------------------------------------------------- | | `connectionId` | string (uuid) | UUID of the Stripe connection configuration | | `customerId` | string | Stripe customer ID for the auto-debit transaction | | `amount` | number | Amount to be debited (in the specified currency) | | `currency` | string | Currency code for the transaction (e.g., 'USD', 'EUR', 'GBP') | ### Optional Parameters | Parameter | Type | Description | | ------------- | ------ | --------------------------------------------------- | | `description` | string | Optional description for the auto-debit transaction | ## Input Example ```json { "connectionId": "stripe-connection-uuid", "customerId": "cus_1234567890", "amount": 99.99, "currency": "USD", "description": "Monthly subscription payment - January 2024" } ``` ## Output Schema | Field | Type | Description | | ------------ | ------- | ----------------------------------------------------------- | | `success` | boolean | Indicates whether the auto-debit was processed successfully | | `message` | string | Response message indicating success or failure details | | `customerId` | string | Customer ID that was processed | | `amount` | number | Amount that was processed | | `currency` | string | Currency of the processed transaction | ## Output Example ### Success Response ```json { "success": true, "message": "Auto-debit processed successfully", "customerId": "cus_1234567890", "amount": 99.99, "currency": "USD" } ``` ### Error Response ```json { "success": false, "message": "Failed to process auto-debit: Insufficient funds", "customerId": "cus_1234567890", "amount": 99.99, "currency": "USD" } ``` ## Use Cases ### Recurring Subscription Payments Automatically charge customers for monthly subscriptions: ```json { "connectionId": "${stripeConnectionId}", "customerId": "${subscription.customerId}", "amount": "${subscription.monthlyAmount}", "currency": "USD", "description": "Monthly subscription - ${currentMonth}" } ``` ### Payment Retry Logic Retry failed payments with error handling: ``` Start → FetchFailedPayment → AutoDebit → [If Success] UpdateStatus → [If Failed] LogError → NotifyAdmin → End ``` ## Stripe Connection Setup Before using AutoDebit, configure a Stripe connection with your API credentials. The `connectionId` references this connection configuration. ## Customer Requirements For auto-debit to work, the Stripe customer must have: * A saved payment method (card, bank account, etc.) * A valid Stripe customer ID (starts with `cus_`) * An active payment method that is not expired ## Related Functions * [Call External API](/mbrix/workflows/functions/external-api/call-external-api) - Generic external API integration * [FetchMData](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Retrieve customer and subscription data * [EmailNotification](/mbrix/workflows/functions/user-interactions/email-notification) - Send payment confirmations --- # Load Data from Database URL: /mbrix/workflows/functions/system-functions/db-data-load Execute SQL queries against database connections and optionally load results into Objects *** title: Load Data from Database description: Execute SQL queries against database connections and optionally load results into Objects ------------------------------------------------------------------------------------------------------ # Load Data from Database Execute SQL SELECT queries against external database connections and optionally load the results into Objects. This function provides secure database connectivity with SQL injection protection and field mapping capabilities. **Technical Name**: `DbDataLoadFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `343e5e27-2e72-4156-8044-2460405a33fe` ## Input Schema ### Required Parameters | Parameter | Type | Description | | -------------- | ------------- | ---------------------------------------------------- | | `connectionId` | string (uuid) | UUID of the database connection to use | | `sqlQuery` | string | SQL SELECT query to execute (SELECT statements only) | ### Optional Parameters | Parameter | Type | Description | | --------------- | ------------- | ------------------------------------------------------------------------------------------- | | `mobjectId` | string (uuid) | UUID of the Object where results will be stored. Omit for query-only execution | | `batchSize` | integer | Batch size for processing large result sets when creating MData (default: 1000, max: 10000) | | `fieldMappings` | object | Field mappings to transform source data fields to target MData fields | ## Input Example ### Query-Only Execution Execute a query and return raw data without storing: ```json { "connectionId": "database-connection-uuid", "sqlQuery": "SELECT customer_id, customer_name, email FROM customers WHERE status = 'active'" } ``` ### Data Loading with Object Execute a query and load results into an Object: ```json { "connectionId": "database-connection-uuid", "sqlQuery": "SELECT customer_id, customer_name, email FROM customers WHERE created_date >= '2024-01-01'", "mobjectId": "customer-mobject-uuid", "fieldMappings": { "customer_id": "customerId", "customer_name": "customerName" }, "batchSize": 1000 } ``` ## Output Schema | Field | Type | Description | | ------------------ | -------------- | -------------------------------------------------------------------------------------------------- | | `success` | boolean | Whether the operation completed successfully | | `recordsProcessed` | integer | Total number of records processed from the query result | | `recordsCreated` | integer | Number of records successfully created in the Object (equals recordsProcessed for query-only mode) | | `recordsFailed` | integer | Number of records that failed to be created (0 for query-only mode) | | `executionTimeMs` | integer | Total execution time in milliseconds | | `errors` | array (string) | List of error messages if any failures occurred | ## Output Example ```json { "success": true, "recordsProcessed": 1000, "recordsCreated": 995, "recordsFailed": 5, "executionTimeMs": 1234, "errors": [ "Record 123: Validation failed - email format invalid" ] } ``` ## Security Features * **SELECT-Only**: Only SELECT statements are allowed * **Dangerous Keywords Blocked**: Blocks DROP, DELETE, UPDATE, INSERT, ALTER, CREATE, TRUNCATE, EXEC, EXECUTE * **Prepared Statements**: Uses parameterized queries internally ## Use Cases ### Data Migration Migrate data from legacy systems: ``` Start → DbDataLoad(Extract) → TransformData → InsertMData → End ``` ### Scheduled Synchronization Sync data from external databases on a schedule: ```json { "connectionId": "source-db-connection-uuid", "sqlQuery": "SELECT * FROM external_customers WHERE updated_date >= '2024-01-01'", "mobjectId": "customer-mobject-uuid", "batchSize": 2000 } ``` ## Related Functions * [FetchMData](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Retrieve data from Objects after loading * [InsertMData](/mbrix/workflows/functions/crud-operations/insert-mdata) - Insert individual records * [BulkInsertMData](/mbrix/workflows/functions/crud-operations/bulk-insert-mdata) - Bulk insert records --- # ECR Analysis URL: /mbrix/workflows/functions/system-functions/ecr-analysis Analyze ECR (Electronic Cash Register) data for financial insights including interest rates, FDIC charges, and potential interest uplift *** title: ECR Analysis description: Analyze ECR (Electronic Cash Register) data for financial insights including interest rates, FDIC charges, and potential interest uplift ----------------------------------------------------------------------------------------------------------------------------------------------------- # ECR Analysis Analyzes ECR (Electronic Cash Register) data from bank statements to calculate financial metrics including interest rates, FDIC charges, net interest, and potential interest uplift. **Technical Name**: `ECRAnalysisSummaryFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `66e31772-bde2-4a8f-801d-c215b5cdc322` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------ | ------------------------------------------------------------------------------------- | | `data` | object | Report configuration object (MReportMaster) containing query and field configurations | ## Input Example ```json { "data": { "reportConfig": { "query": { "selectFields": [ { "fieldName": "bank_name", "fieldAlias": "Bank" }, { "fieldName": "account_number", "fieldAlias": "Account Number" }, { "fieldName": "interest_rate", "fieldAlias": "Interest Rate" }, { "fieldName": "balance", "fieldAlias": "Avg Balance (Less float and overdraft)" }, { "fieldName": "reporting_total_service_fee", "fieldAlias": "Total Fee" } ] } } } } ``` ## Output Schema | Field | Type | Description | | ------------- | ----- | -------------------------------------------------------------- | | `ecrDataList` | array | List of ECR analysis entries with calculated financial metrics | Each entry in `ecrDataList` contains: | Field | Type | Description | | ---------------------------------------- | ------ | ------------------------------------ | | `Bank` | string | Bank name | | `Account Number` | string | Account number | | `Account Name` | string | Account name | | `Currency` | string | Account currency | | `ECR/Interest Rate (Annual)` | number | ECR rate (set to interest rate) | | `FDIC assessment (Annual)` | number | Calculated FDIC charges | | `Net Interest` | number | Interest rate minus FDIC charges | | `Interbank Rate` | number | Interbank interest rate | | `Hypothetical Market Int Rate` | number | Hypothetical market interest rate | | `Interest Rate` | number | Account interest rate | | `Potential Interest Uplift` | number | Calculated potential interest uplift | | `Avg Balance (Less float and overdraft)` | number | Average account balance | | `Total Fee` | number | Total service fees | ## Output Example ```json { "ecrDataList": [ { "Bank": "Chase Bank", "Account Number": "1234567890", "Account Name": "Business Checking", "Currency": "USD", "ECR/Interest Rate (Annual)": 0.02, "FDIC assessment (Annual)": 0.0012, "Net Interest": 0.0188, "Interbank Rate": 0.05, "Hypothetical Market Int Rate": 3.75, "Interest Rate": 0.02, "Potential Interest Uplift": 37500.0, "Avg Balance (Less float and overdraft)": 1000000, "Total Fee": 100.0 } ] } ``` ## Use Cases ### Bank Fee Analysis Analyze bank accounts to calculate ECR metrics and potential interest improvements: ```json { "data": { "reportConfig": { "query": { "selectFields": [ {"fieldName": "bank_name", "fieldAlias": "Bank"}, {"fieldName": "account_number", "fieldAlias": "Account Number"}, {"fieldName": "interest_rate", "fieldAlias": "Interest Rate"}, {"fieldName": "balance", "fieldAlias": "Avg Balance (Less float and overdraft)"}, {"fieldName": "reporting_total_service_fee", "fieldAlias": "Total Fee"} ], "where": [ { "field": "account_type", "operator": "equals", "value": "checking" } ] } } } } ``` ### Interest Rate Comparison Compare current interest rates with hypothetical market rates: ``` Start → FetchBankAccounts → ECRAnalysis → CalculateUplift → GenerateReport → End ``` ## Calculations The function automatically calculates: * **ECR**: Set equal to the interest rate * **FDIC Charges**: `(Total Service Fee / Average Balance) * 12` (annualized) * **Net Interest**: `Interest Rate - FDIC Charges` * **Hypothetical Market Rate**: Calculated based on interbank rate * **Interest Uplift**: `(Hypothetical Rate - Interest Rate) * Average Balance` ## Related Functions * [FetchMData](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Retrieve bank account data before analysis * [JavaScript](/mbrix/workflows/functions/system-functions/javascript) - Process ECR analysis results --- # Export Data to CSV URL: /mbrix/workflows/functions/system-functions/export Execute a query and convert the result to a CSV file with field labels as headers *** title: Export Data to CSV description: Execute a query and convert the result to a CSV file with field labels as headers ---------------------------------------------------------------------------------------------- # Export Data to CSV Execute a query and convert the results to a CSV file. This function automatically resolves picklist values and uses field labels as CSV headers for better readability. **Technical Name**: `ExportFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `6b1f97d8-265e-48f9-b6ef-2267afc70244` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ------------- | ------ | ------------------------------------------------------------------------------------------ | | `queryMaster` | object | Query configuration object containing selectFields, fromClause, and other query parameters | ### Optional Parameters | Parameter | Type | Description | | ----------------------- | ------ | ------------------------------------------------------------------------- | | `fileName` | string | Name of the CSV file to generate (default: "export.csv") | | `includeDateInFilename` | string | Whether to include date in filename - "true" or "false" (default: "true") | | `includeHeader` | string | Whether to include headers in CSV - "true" or "false" (default: "true") | ## Input Example ### Basic Export ```json { "queryMaster": { "selectFields": [ { "fieldName": "customer_name", "fieldAlias": "customerName", "fieldLabel": "Customer Name" }, { "fieldName": "email", "fieldAlias": "email", "fieldLabel": "Email Address" }, { "fieldName": "status", "fieldAlias": "status", "fieldLabel": "Status" } ], "fromClause": { "mobjectId": "customer-mobject-uuid" } }, "fileName": "customers_export.csv" } ``` ### Export with Date in Filename ```json { "queryMaster": { "selectFields": [ { "fieldName": "order_number", "fieldAlias": "orderNumber", "fieldLabel": "Order Number" }, { "fieldName": "total_amount", "fieldAlias": "totalAmount", "fieldLabel": "Total Amount" } ], "fromClause": { "mobjectId": "order-mobject-uuid" }, "where": [ { "field": "order_date", "operator": "greaterThanOrEquals", "value": "2024-01-01" } ] }, "fileName": "orders_export.csv", "includeDateInFilename": "true", "includeHeader": "true" } ``` ## Output Schema | Field | Type | Description | | ---------- | ------------- | ---------------------------------------------------------------- | | `fileId` | string (uuid) | ID of the generated CSV file in the file storage system | | `fileName` | string | Name of the generated CSV file (includes date suffix if enabled) | | `rowCount` | integer | Number of rows in the exported file | ## Output Example ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "fileName": "customers_export_20240120_143022.csv", "rowCount": 150 } ``` ## Field Labels as Headers The function automatically uses field labels from the QueryMaster as CSV headers. If a field has a `fieldLabel`, it will be used as the header; otherwise, the `fieldAlias` is used. **Example:** * Field with label: `fieldLabel: "Customer Name"` → CSV header: "Customer Name" * Field without label: `fieldAlias: "customerName"` → CSV header: "customerName" ## Picklist Resolution Picklist values are automatically resolved to their display names in the exported CSV: * **Source**: `status: "active-uuid"` * **Exported**: `Status: "Active"` ## Use Cases ### Export Customer Data Export customer records to CSV: ```json { "queryMaster": { "selectFields": [ {"fieldName": "name", "fieldAlias": "name", "fieldLabel": "Name"}, {"fieldName": "email", "fieldAlias": "email", "fieldLabel": "Email"}, {"fieldName": "phone", "fieldAlias": "phone", "fieldLabel": "Phone"} ], "fromClause": { "mobjectId": "customer-mobject-uuid" } }, "fileName": "customers.csv", "includeDateInFilename": "true" } ``` ### Scheduled Data Export Export data on a schedule and email the file: ``` Scheduled Trigger → Export → EmailNotification(attach CSV) → End ``` ## Related Functions * [FetchMData](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Retrieve data before exporting * [EmailNotification](/mbrix/workflows/functions/user-interactions/email-notification) - Send exported CSV files via email * [DbDataLoad](/mbrix/workflows/functions/system-functions/db-data-load) - Load data from external databases before exporting --- # Calculate Expression URL: /mbrix/workflows/functions/system-functions/expression Perform calculations and formulas using your data *** title: Calculate Expression description: Perform calculations and formulas using your data -------------------------------------------------------------- # Calculate Expression Perform calculations, formulas, and data transformations using your workflow data. Use this to compute values, combine fields, or transform data before using it in other steps. **Technical Name**: `ExpressionFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `e4a7c2f1-9d83-4b5a-8c6e-f2d3e1a7b890` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ------------- | ----- | ------------------------------------ | | `expressions` | array | List of MAPL expressions to evaluate | ### Optional Parameters | Parameter | Type | Description | | -------------------- | ------ | ---------------------------------------------- | | `variableVsValueMap` | object | Map of variable names to values for evaluation | | `outputVariables` | array | List of variable names to include in output | ## Input Example ```json { "expressions": [ "total = price * quantity", "tax = total * 0.08", "grandTotal = total + tax", "discount = total > 100 ? 0.10 : 0.05" ], "variableVsValueMap": { "price": 25.00, "quantity": 5 }, "outputVariables": ["total", "tax", "grandTotal", "discount"] } ``` ## Output Example ```json { "total": 125.00, "tax": 10.00, "grandTotal": 135.00, "discount": 0.10 } ``` ## MAPL Syntax ### Arithmetic Operations ``` sum = a + b difference = a - b product = a * b quotient = a / b remainder = a % b ``` ### Comparison Operations ``` isEqual = a == b isNotEqual = a != b isGreater = a > b isLess = a < b ``` ### Conditional Expressions ``` result = condition ? valueIfTrue : valueIfFalse status = amount > 1000 ? "high" : "low" ``` ## Use Cases ### Price Calculations Calculate pricing with discounts and tax: ```json { "expressions": [ "subtotal = price * quantity", "discount = subtotal > 500 ? 0.15 : subtotal > 100 ? 0.10 : 0.05", "discountAmount = subtotal * discount", "afterDiscount = subtotal - discountAmount", "tax = afterDiscount * taxRate", "total = afterDiscount + tax" ], "variableVsValueMap": { "price": 50, "quantity": 12, "taxRate": 0.08 } } ``` ### Status Determination Determine status based on multiple conditions: ```json { "expressions": [ "isPremium = customerTier == 'premium'", "isHighValue = orderTotal > 1000", "qualifiesForBonus = isPremium && isHighValue", "bonusAmount = qualifiesForBonus ? orderTotal * 0.05 : 0" ], "variableVsValueMap": { "customerTier": "premium", "orderTotal": 1500 } } ``` ## Built-in Functions ### Mathematical Functions ``` abs(x) - Absolute value ceil(x) - Round up floor(x) - Round down round(x) - Round to nearest integer sqrt(x) - Square root min(a, b, ...) - Minimum value max(a, b, ...) - Maximum value ``` ### String Functions ``` concat(a, b) - Concatenate strings length(str) - String length upper(str) - Convert to uppercase lower(str) - Convert to lowercase ``` ## Best Practices 1. **Clear Variable Names**: Use descriptive names for clarity 2. **Break Complex Logic**: Split complex calculations into multiple expressions 3. **Validate Inputs**: Check for null or undefined values 4. **Test Edge Cases**: Test with boundary values ## Comparison with JavaScript | Aspect | Expression (MAPL) | JavaScript | | --------------- | ------------------- | ------------------------- | | **Complexity** | Simple calculations | Complex logic | | **Performance** | Faster | Slower | | **Syntax** | Formula-like | Full programming language | | **Use Case** | Math and logic | Data transformation | ## Related Functions * [JavaScript](/mbrix/workflows/functions/system-functions/javascript) - Complex transformations * [SubFlow](/mbrix/workflows/functions/system-functions/subflow) - Reusable calculation logic --- # Loop Through Items URL: /mbrix/workflows/functions/system-functions/foreach Repeat the same actions for each item in a list *** title: Loop Through Items description: Repeat the same actions for each item in a list ------------------------------------------------------------ # Loop Through Items Process each item in a list one by one. For example, if you have a list of customers, you can send an email to each customer automatically. This saves you from repeating the same steps manually. **Technical Name**: `ForEachFunction` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `7d9e6750-c2a9-4c4d-8f7b-c42e96c1d8b3` ## Input Schema ### Parameters | Parameter | Type | Required | Description | | -------------- | ------ | -------- | ---------------------------------------------- | | `arrayPath` | array | No | Path to reference an array from previous nodes | | `inputArray` | array | No | Direct input array of items to process | | `contextData` | object | No | Additional context data passed with each item | | `targetFlowId` | string | No | ID of the target flow that processes each item | Note: Either `arrayPath` or `inputArray` must be provided. ## Input Example ### Using Direct Array ```json { "inputArray": [ {"orderId": "ORD-001", "amount": 150}, {"orderId": "ORD-002", "amount": 200}, {"orderId": "ORD-003", "amount": 175} ], "contextData": { "userId": "user-123", "processDate": "2024-01-15" }, "targetFlowId": "process-order-flow-id" } ``` ### Using Array Path ```json { "arrayPath": "${fetchOrders.output.data}", "contextData": { "batchId": "${start.output.batchId}" }, "targetFlowId": "process-order-flow-id" } ``` ## Output Schema | Field | Type | Description | | ------ | ----- | ------------------------------------ | | `data` | array | Array of results from each iteration | Each result object contains: | Field | Type | Description | | --------- | ------- | ------------------------------------- | | `success` | boolean | Whether the iteration was successful | | `output` | object | Output data from the target flow | | `error` | string | Error message if the iteration failed | ## Use Cases ### Batch Processing Orders Process multiple orders in parallel: ``` Start → FetchPendingOrders → ForEach(ProcessOrder) → SendSummary → End ``` ### Data Transformation Transform each item in a dataset: ```json { "inputArray": "${loadData.output.records}", "contextData": { "transformationType": "normalize" }, "targetFlowId": "transform-record-flow-id" } ``` ## Performance Considerations ### Parallel Execution ForEach executes iterations in parallel by default: * Faster processing for independent items * Configurable concurrency limit * Automatic load balancing ## Best Practices 1. **Batch Size**: Process arrays in batches of 50-100 items 2. **Error Handling**: Always check for failed iterations 3. **Context Data**: Pass shared data via contextData 4. **Timeout**: Set appropriate timeouts for target flows 5. **Logging**: Implement logging in target flows for debugging ## Workflow Example ``` Start → FetchCustomers → ForEach(ProcessCustomer) → AggregateResults → End Target Flow (ProcessCustomer): Start → ValidateData → InsertMData → EmailNotification → End ``` ## Related Functions * [SubFlow](/mbrix/workflows/functions/system-functions/subflow) - Execute single subflow * [BulkInsertMData](/mbrix/workflows/functions/crud-operations/bulk-insert-mdata) - Bulk operations alternative * [JavaScript](/mbrix/workflows/functions/system-functions/javascript) - Custom array processing ## Limitations * Maximum array size: 10,000 items * Maximum parallel executions: 100 * Timeout per iteration: 5 minutes * Total timeout: 30 minutes --- # Generate PDF from HTML Template URL: /mbrix/workflows/functions/system-functions/html-to-pdf Convert HTML templates to PDF documents with support for template resolution and data binding *** title: Generate PDF from HTML Template description: Convert HTML templates to PDF documents with support for template resolution and data binding ---------------------------------------------------------------------------------------------------------- # Generate PDF from HTML Template Convert HTML templates to PDF documents using Pebble templates. This function automatically resolves reference and picklist fields, binds your data to the template, and generates professional PDF documents. **Technical Name**: `HTMLToPDFFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `3d26f546-324b-4bb6-89d5-48064a95fbed` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ------------ | ------------- | ------------------------------------------------- | | `templateId` | string (uuid) | ID of the HTML template to use for PDF generation | ### Optional Parameters | Parameter | Type | Description | | ------------ | ------ | -------------------------------------------------------------------------------------------------------------------------- | | `dataObject` | object | Data object for template resolution. Fields with `__r` suffix are automatically resolved for reference and picklist fields | | `fileName` | string | Name of the PDF file to generate (without extension). Defaults to "document" | ## Input Example ```json { "templateId": "invoice-template-uuid", "dataObject": { "invoiceNumber": "INV-2024-001", "customerName": "John Doe", "items": [ {"name": "Product A", "quantity": 2, "price": 50.00}, {"name": "Product B", "quantity": 1, "price": 75.00} ], "total": 175.00, "status__r": "Active" }, "fileName": "invoice-INV-2024-001" } ``` ## Output Schema | Field | Type | Description | | -------- | ------------- | ------------------------------------------------------- | | `fileId` | string (uuid) | ID of the generated PDF file in the file storage system | ## Output Example ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d" } ``` ## Template Syntax HTMLToPDF uses Pebble templates with support for: * **Variables**: `{{ variableName }}` * **Conditionals**: `{% if condition %}...{% endif %}` * **Loops**: `{% for item in items %}...{% endfor %}` The function automatically resolves reference and picklist fields. Use `{{ field__r }}` for resolved values or `{{ field }}` (which will show resolved value if `__r` exists). ## Use Cases ### Invoice Generation Generate PDF invoices from order data: ```json { "templateId": "invoice-template-uuid", "dataObject": { "invoiceNumber": "INV-2024-001", "customerName": "John Doe", "items": [ {"description": "Product A", "quantity": 2, "unitPrice": 50.00, "total": 100.00} ], "subtotal": 100.00, "tax": 8.00, "total": 108.00 }, "fileName": "invoice-INV-2024-001" } ``` ### Report Generation Create formatted reports with resolved field values: ``` Start → FetchMData → HTMLToPDF → EmailNotification(attach PDF) → End ``` ## Related Functions * [EmailNotification](/mbrix/workflows/functions/user-interactions/email-notification) - Attach generated PDFs to emails * [FetchMData](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Retrieve data before PDF generation --- # Intra-Bank Fee Detail Chart URL: /mbrix/workflows/functions/system-functions/intra-bank-fee-detail-chart Generate chart data for intra-bank fee analysis showing potential savings by comparing rates across bank services *** title: Intra-Bank Fee Detail Chart description: Generate chart data for intra-bank fee analysis showing potential savings by comparing rates across bank services ------------------------------------------------------------------------------------------------------------------------------ # Intra-Bank Fee Detail Chart Analyzes intra-bank fee data to generate chart-ready data showing potential savings. The function compares actual charges against minimum rates to identify cost-saving opportunities across different bank services. **Technical Name**: `IntraBankFeeDetailChartFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `66e31772-bde2-4a8f-801d-c215b5cdc325` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------ | --------------------------------------------------------------------------------------- | | `data` | object | Report configuration object (MReportMaster) containing query with bank service fee data | The report query should include the following fields: * `bank_service_description` - Name/description of the bank service * `unit_price` - Unit price/rate for the service * `volume` - Transaction volume * `total_charges` - Total charges for the service * `forex_rate` - Foreign exchange rate (if applicable) ## Input Example ```json { "data": { "reportConfig": { "query": { "selectFields": [ { "fieldName": "bank_service_description", "fieldAlias": "Service" }, { "fieldName": "unit_price", "fieldAlias": "Unit Price" }, { "fieldName": "volume", "fieldAlias": "Volume" }, { "fieldName": "total_charges", "fieldAlias": "Total Charges" }, { "fieldName": "forex_rate", "fieldAlias": "Forex Rate" } ], "fromClause": { "mobjectId": "bank-fee-mobject-uuid" } } } } } ``` ## Output Schema | Field | Type | Description | | -------- | ----- | ------------------------------------------------------------------------------- | | `result` | array | Array of chart data objects, each containing service name and unit price values | Each object in the `result` array contains: * `Service` - Bank service description * `val1`, `val2`, `val3`, ... - Unit price values (number of columns varies based on distinct prices) ## Output Example ```json { "result": [ { "Service": "Wire Transfer", "val1": 0.25, "val2": 0.30, "val3": 0.35, "val4": 0 }, { "Service": "ACH Transfer", "val1": 0.10, "val2": 0.15, "val3": 0 } ] } ``` ## How It Works The function performs the following analysis: 1. **Groups by Service**: Groups fee data by bank service description 2. **Finds Min/Max Rates**: Identifies minimum and maximum unit prices for each service 3. **Calculates Savings**: Compares actual charges against charges at minimum rate: ``` savings = total_charges - (forex_rate × volume × min_rate) ``` 4. **Filters Results**: Only includes services where savings > 1 5. **Formats for Charts**: Structures data with service names and unit price columns for easy charting ## Use Cases ### Fee Analysis Dashboard Generate chart data for visualizing fee variations across bank services: ```json { "data": { "reportConfig": { "query": { "selectFields": [ {"fieldName": "bank_service_description", "fieldAlias": "Service"}, {"fieldName": "unit_price", "fieldAlias": "Rate"}, {"fieldName": "volume", "fieldAlias": "Volume"}, {"fieldName": "total_charges", "fieldAlias": "Charges"}, {"fieldName": "forex_rate", "fieldAlias": "Forex"} ], "fromClause": { "mobjectId": "bank-fee-mobject-uuid" }, "where": [ { "field": "transaction_date", "operator": "greaterThanOrEquals", "value": "2024-01-01" } ] } } } } ``` ### Cost Optimization Analysis Identify services with the highest potential savings: ``` Start → FetchMData(Bank Fees) → IntraBankFeeDetailChart → Visualize → End ``` ## Related Functions * [ECR Analysis](/mbrix/workflows/functions/system-functions/ecr-analysis) - Analyze ECR data for financial insights * [Export Data to CSV](/mbrix/workflows/functions/system-functions/export) - Export chart data for further analysis --- # Intra-Bank Fee Detail Report URL: /mbrix/workflows/functions/system-functions/intra-bank-fee-detail-report Generate detailed reports for intra-bank fee analysis showing transaction details and potential savings *** title: Intra-Bank Fee Detail Report description: Generate detailed reports for intra-bank fee analysis showing transaction details and potential savings -------------------------------------------------------------------------------------------------------------------- # Intra-Bank Fee Detail Report Generates detailed reports for intra-bank fee analysis. The function identifies services with multiple pricing tiers, calculates potential savings by comparing actual charges against minimum rates, and returns comprehensive transaction-level details. **Technical Name**: `IntraBankFeeDetailReportFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `66e31772-bde2-4a8f-801d-c215b5cdc324` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------ | --------------------------------------------------------------------------------------- | | `data` | object | Report configuration object (MReportMaster) containing query with bank service fee data | The report query should include the following fields: * `bank_service_description` - Name/description of the bank service * `bank_name` - Name of the bank * `from_date` - Start date of the period * `to_date` - End date of the period * `account_number` - Account number * `account_region` - Account region * `branch_name` - Branch name * `unit_price` - Unit price/rate for the service * `volume` - Transaction volume * `total_charges` - Total charges for the service * `forex_rate` - Foreign exchange rate * `currency_code` - Currency code ## Input Example ```json { "data": { "reportConfig": { "query": { "selectFields": [ { "fieldName": "bank_service_description", "fieldAlias": "Service" }, { "fieldName": "bank_name", "fieldAlias": "Bank" }, { "fieldName": "from_date", "fieldAlias": "From Date" }, { "fieldName": "to_date", "fieldAlias": "To Date" }, { "fieldName": "account_number", "fieldAlias": "Account" }, { "fieldName": "unit_price", "fieldAlias": "Unit Price" }, { "fieldName": "volume", "fieldAlias": "Volume" }, { "fieldName": "total_charges", "fieldAlias": "Total Charges" }, { "fieldName": "forex_rate", "fieldAlias": "Forex Rate" } ], "fromClause": { "mobjectId": "bank-fee-mobject-uuid" } } } } } ``` ## Output Schema | Field | Type | Description | | -------- | ----- | ------------------------------------ | | `result` | array | Array of detailed fee report objects | Each object in the `result` array contains: | Field | Type | Description | | -------------------------- | ------ | ---------------------------------------------------------------- | | `Bank` | string | Bank name | | `Period From` | date | Start date of the period | | `Period To` | date | End date of the period | | `Account Number` | string | Account number | | `Bank Service Description` | string | Description of the bank service | | `Account Region` | string | Account region | | `Branch Name` | string | Branch name | | `Unit Price` | number | Unit price/rate for the service | | `Volume` | number | Transaction volume | | `Total Charges` | number | Total charges for the service | | `Min Rate` | number | Minimum rate found for this service | | `Rearranged Charges` | number | Charges if using minimum rate (forex\_rate × volume × min\_rate) | | `Savings` | number | Potential savings (total\_charges - rearranged\_charges) | ## Output Example ```json { "result": [ { "Bank": "ABC Bank", "Period From": "2024-01-01", "Period To": "2024-01-31", "Account Number": "ACC123456", "Bank Service Description": "Wire Transfer", "Account Region": "North", "Branch Name": "Main Branch", "Unit Price": 0.30, "Volume": 1000, "Total Charges": 300.00, "Min Rate": 0.25, "Rearranged Charges": 250.00, "Savings": 50.00 } ] } ``` ## How It Works The function performs the following analysis: 1. **Groups by Service**: Groups fee data by bank service description 2. **Finds Minimum Rate**: Identifies the minimum unit price for each service 3. **Filters Multi-Price Services**: Only includes services with multiple distinct prices (more than one pricing tier) 4. **Calculates Rearranged Charges**: Computes what charges would be at minimum rate: ``` rearranged_charges = forex_rate × volume × min_rate ``` 5. **Calculates Savings**: Compares actual charges against rearranged charges: ``` savings = total_charges - rearranged_charges ``` 6. **Filters Positive Savings**: Only returns records where savings > 0 ## Use Cases ### Detailed Fee Analysis Report Generate comprehensive reports showing transaction-level fee details and savings: ```json { "data": { "reportConfig": { "query": { "selectFields": [ {"fieldName": "bank_service_description", "fieldAlias": "Service"}, {"fieldName": "bank_name", "fieldAlias": "Bank"}, {"fieldName": "unit_price", "fieldAlias": "Rate"}, {"fieldName": "volume", "fieldAlias": "Volume"}, {"fieldName": "total_charges", "fieldAlias": "Charges"} ], "fromClause": { "mobjectId": "bank-fee-mobject-uuid" }, "where": [ { "field": "from_date", "operator": "greaterThanOrEquals", "value": "2024-01-01" } ] } } } } ``` ### Cost Optimization Workflow Analyze fees and export detailed savings report: ``` Start → FetchMData(Bank Fees) → IntraBankFeeDetailReport → Export → End ``` ## Related Functions * [Intra-Bank Fee Detail Chart](/mbrix/workflows/functions/system-functions/intra-bank-fee-detail-chart) - Generate chart data for fee analysis * [ECR Analysis](/mbrix/workflows/functions/system-functions/ecr-analysis) - Analyze ECR data for financial insights * [Export Data to CSV](/mbrix/workflows/functions/system-functions/export) - Export report data for further analysis --- # Run JavaScript Code URL: /mbrix/workflows/functions/system-functions/javascript Write and run custom JavaScript code to perform advanced operations *** title: Run JavaScript Code description: Write and run custom JavaScript code to perform advanced operations -------------------------------------------------------------------------------- # Run JavaScript Code Write custom JavaScript code to perform advanced operations that aren't available in other blocks. You can access your database, perform complex calculations, and manipulate data using programming code. **Technical Name**: `JavaScriptFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `f5b8d3e2-8e94-4c6b-9d7f-e3f4a2b8c901` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------ | -------------------------- | | `jsCode` | string | JavaScript code to execute | ### Optional Parameters | Parameter | Type | Description | | -------------------- | ------ | ------------------------------------------- | | `variableVsValueMap` | object | Map of variable names to values | | `outputVariables` | array | List of variable names to include in output | ## Input Example ```json { "jsCode": "const total = items.reduce((sum, item) => sum + item.price * item.quantity, 0);\nconst tax = total * 0.08;\nconst grandTotal = total + tax;\nreturn { total, tax, grandTotal };", "variableVsValueMap": { "items": [ {"name": "Product A", "price": 10, "quantity": 2}, {"name": "Product B", "price": 25, "quantity": 1} ] } } ``` ## Use Cases ### Data Transformation Transform data between workflow steps: ```javascript const customer = { firstName: input.first_name, lastName: input.last_name, fullName: `${input.first_name} ${input.last_name}`, email: input.email.toLowerCase(), registeredAt: new Date().toISOString() }; return customer; ``` ### Complex Calculations Perform complex business calculations: ```javascript // Calculate tiered discount let discount = 0; if (orderTotal > 1000) { discount = 0.15; // 15% for orders over $1000 } else if (orderTotal > 500) { discount = 0.10; // 10% for orders over $500 } else if (orderTotal > 100) { discount = 0.05; // 5% for orders over $100 } const discountAmount = orderTotal * discount; const finalTotal = orderTotal - discountAmount; return { orderTotal, discount, discountAmount, finalTotal }; ``` ### Data Validation Validate and clean data: ```javascript const errors = []; // Validate email if (!email || !email.includes('@')) { errors.push('Invalid email address'); } // Validate phone const phoneRegex = /^\+?[\d\s-()]+$/; if (!phoneRegex.test(phone)) { errors.push('Invalid phone number'); } return { isValid: errors.length === 0, errors }; ``` ## Database Access Use the `db` object to query the database: ```javascript // Query data const customers = await db.query( 'SELECT * FROM customers WHERE status = $1 LIMIT 10', ['active'] ); return { customerCount: customers.length }; ``` ## Best Practices 1. **Keep it Simple**: Use JavaScript for complex logic only 2. **Error Handling**: Always wrap code in try-catch blocks 3. **Logging**: Use console.log for debugging 4. **Performance**: Avoid long-running operations 5. **Security**: Never execute user-provided code directly ### Error Handling Pattern ```javascript try { // Your code here const result = processData(input); return { success: true, data: result }; } catch (error) { console.error('Error:', error.message); return { success: false, error: error.message }; } ``` ## Related Functions * [Expression](/mbrix/workflows/functions/system-functions/expression) - Evaluate MAPL expressions * [SubFlow](/mbrix/workflows/functions/system-functions/subflow) - Complex logic in separate flows ## Limitations * Execution timeout: 30 seconds maximum * Memory limit: 256MB per execution * Cannot import external npm packages * Cannot make HTTP requests directly (use CallExternalApi) --- # Convert JSON to CSV URL: /mbrix/workflows/functions/system-functions/json-to-csv Convert JSON array data to CSV format and save as a file *** title: Convert JSON to CSV description: Convert JSON array data to CSV format and save as a file --------------------------------------------------------------------- # Convert JSON to CSV Convert an array of JSON objects to CSV format and save it as a file. This function automatically extracts headers from the JSON data and handles missing fields across rows. **Technical Name**: `JsonToCsvFileConverter` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `7f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea4` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ----- | ------------------------------------------------------------------------------------------------------------ | | `data` | array | Array of JSON objects to convert to CSV. Each object represents a row, and object keys become column headers | ### Optional Parameters | Parameter | Type | Description | | ----------------------- | ------ | ------------------------------------------------------------------------- | | `fileName` | string | Name of the CSV file to generate (default: "export.csv") | | `includeDateInFilename` | string | Whether to include date in filename - "true" or "false" (default: "true") | | `includeHeader` | string | Whether to include headers in CSV - "true" or "false" (default: "true") | ## Input Example ### Basic Conversion ```json { "data": [ { "name": "John Doe", "email": "john@example.com", "age": 30 }, { "name": "Jane Smith", "email": "jane@example.com", "age": 25 } ], "fileName": "users.csv" } ``` ### Without Headers ```json { "data": [ {"product": "Widget A", "price": 19.99, "quantity": 100}, {"product": "Widget B", "price": 29.99, "quantity": 50} ], "fileName": "products.csv", "includeHeader": "false", "includeDateInFilename": "true" } ``` ### With Date in Filename ```json { "data": [ { "orderId": "ORD001", "customer": "Acme Corp", "amount": 1500.00, "status": "completed" }, { "orderId": "ORD002", "customer": "Tech Inc", "amount": 2300.50, "status": "pending" } ], "fileName": "orders_export.csv", "includeDateInFilename": "true", "includeHeader": "true" } ``` ## Output Schema | Field | Type | Description | | ---------- | ------------- | ---------------------------------------------------------------- | | `fileId` | string (uuid) | ID of the generated CSV file in the file storage system | | `fileName` | string | Name of the generated CSV file (includes date suffix if enabled) | | `rowCount` | integer | Number of rows in the exported file | ## Output Example ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "fileName": "users_export_20240120_143022.csv", "rowCount": 2 } ``` ## How It Works 1. **Extracts Headers**: Automatically collects all unique keys from all JSON objects to create column headers 2. **Handles Missing Fields**: If a row doesn't have a field present in other rows, it's filled with an empty string 3. **Converts Values**: All values are converted to strings for CSV format 4. **Generates File**: Creates CSV file and uploads it to file storage 5. **Date Suffix**: Optionally appends timestamp to filename (format: `yyyyMMdd_HHmmss`) ## Use Cases ### Convert API Response to CSV Convert JSON API response data to CSV: ```json { "data": [ {"id": 1, "name": "Item 1", "value": 100}, {"id": 2, "name": "Item 2", "value": 200} ], "fileName": "api_data.csv" } ``` ### Export Workflow Results Export workflow execution results to CSV: ``` Start → ProcessData → JsonToCsv → EmailNotification(attach CSV) → End ``` ### Transform Data Before Export Transform and convert data: ``` Start → FetchMData → TransformData → JsonToCsv → End ``` ## Related Functions * [Export Data to CSV](/mbrix/workflows/functions/system-functions/export) - Execute a query and export results to CSV * [EmailNotification](/mbrix/workflows/functions/user-interactions/email-notification) - Send generated CSV files via email --- # Level 1 Analysis URL: /mbrix/workflows/functions/system-functions/level1-analysis Analyze intra-bank fee data to generate summary reports with rate comparisons, volume breakdowns, and potential savings *** title: Level 1 Analysis description: Analyze intra-bank fee data to generate summary reports with rate comparisons, volume breakdowns, and potential savings ------------------------------------------------------------------------------------------------------------------------------------ # Level 1 Analysis Generates comprehensive intra-bank fee summary reports. The function analyzes fee data across banks, services, countries, and currencies to identify rate variations, calculate fee changes, and estimate potential savings. **Technical Name**: `Level1AnalysisFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `66e31772-bde2-4a8f-801d-c215b5cdc323` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------ | ------------------------------------------------------------------------------- | | `data` | object | Report configuration object (MReportMaster) containing query with bank fee data | The report query should include the following fields: * `bank_name` - Name of the bank * `bank_service_description` - Description of the bank service * `name` - Country name * `currency_name` - Currency name * `from_date` - Start date of the period * `to_date` - End date of the period * `unit_price` - Unit price/rate for the service * `volume` - Transaction volume ## Input Example ```json { "data": { "reportConfig": { "query": { "selectFields": [ { "fieldName": "bank_name", "fieldAlias": "Bank" }, { "fieldName": "bank_service_description", "fieldAlias": "Service" }, { "fieldName": "name", "fieldAlias": "Country" }, { "fieldName": "currency_name", "fieldAlias": "Currency" }, { "fieldName": "from_date", "fieldAlias": "From Date" }, { "fieldName": "to_date", "fieldAlias": "To Date" }, { "fieldName": "unit_price", "fieldAlias": "Unit Price" }, { "fieldName": "volume", "fieldAlias": "Volume" } ], "fromClause": { "mobjectId": "bank-fee-mobject-uuid" } } } } } ``` ## Output Schema | Field | Type | Description | | -------- | ----- | --------------------------------- | | `result` | array | Array of Level 1 analysis objects | Each object in the `result` array contains: | Field | Type | Description | | ----------------------------- | ------ | ------------------------------------------------------------------------------ | | `Bank` | string | Bank name | | `Bank Service Description` | string | Description of the bank service | | `Country` | string | Country name | | `Currency LCY` | string | Currency name | | `Rate` | number | Current rate for this service | | `Minimum Rate` | number | Minimum rate found for this service | | `Total Volume` | number | Total transaction volume | | `Total Fees` | number | Total fees paid (total\_volume × rate) | | `Total Fee Increase/Decrease` | number | Fee change compared to current rate (positive = increase, negative = decrease) | | `Potential Savings` | number | Potential savings if using minimum rate (for current month) | | `Last Month Charge` | string | Last month when charges were applied (or "Current Price") | | `Volume Per Month` | array | Array of volume breakdowns by month | | `[Month Name]` | number | Custom fields for each month (e.g., "Jan 2024", "Feb 2024") showing volume | The result also includes summary rows per bank: * `Fee Increase During Analysis Period` - Total fee increases for the bank * `Fee Decrease During Analysis Period` - Total fee decreases for the bank ## Output Example ```json { "result": [ { "Bank": "ABC Bank", "Bank Service Description": "Fee Increase During Analysis Period", "Total Fee Increase/Decrease": 5000.00 }, { "Bank": "ABC Bank", "Bank Service Description": "Fee Decrease During Analysis Period", "Total Fee Increase/Decrease": -2000.00 }, { "Bank": "ABC Bank", "Bank Service Description": "Wire Transfer", "Country": "United States", "Currency LCY": "USD", "Rate": 0.30, "Minimum Rate": 0.25, "Total Volume": 10000, "Total Fees": 3000.00, "Total Fee Increase/Decrease": 500.00, "Potential Savings": 500.00, "Last Month Charge": "Current Price", "Volume Per Month": [ { "from_date": "2024-01-01", "to_date": "2024-01-31", "volume": 5000 } ], "Jan 2024": 5000.00 } ] } ``` ## How It Works The function performs the following analysis: 1. **Groups by Dimensions**: Groups fee data by bank, service, country, and currency 2. **Finds Rate Variations**: Identifies services with multiple pricing tiers (more than one distinct price) 3. **Calculates Minimum Rate**: Finds the minimum rate for each service group 4. **Aggregates Volumes**: Sums volumes by rate and groups volume per month 5. **Calculates Fee Metrics**: * Total fees paid = total\_volume × rate * Fee increase/decrease = (current\_rate - rate) × total\_volume * Potential savings = volume × (rate - min\_rate) for current month 6. **Identifies Current Rate**: Marks the latest month's rate as "Current Price" 7. **Adds Summary**: Includes bank-level summaries showing total fee increases and decreases ## Use Cases ### Bank Fee Summary Report Generate comprehensive fee analysis across banks and services: ```json { "data": { "reportConfig": { "query": { "selectFields": [ {"fieldName": "bank_name", "fieldAlias": "Bank"}, {"fieldName": "bank_service_description", "fieldAlias": "Service"}, {"fieldName": "unit_price", "fieldAlias": "Rate"}, {"fieldName": "volume", "fieldAlias": "Volume"} ], "fromClause": { "mobjectId": "bank-fee-mobject-uuid" }, "where": [ { "field": "from_date", "operator": "greaterThanOrEquals", "value": "2024-01-01" } ] } } } } ``` ### Multi-Bank Fee Comparison Compare fee structures across multiple banks: ``` Start → FetchMData(Bank Fees) → Level1Analysis → Export → End ``` ## Related Functions * [Intra-Bank Fee Detail Report](/mbrix/workflows/functions/system-functions/intra-bank-fee-detail-report) - Generate detailed transaction-level fee reports * [Intra-Bank Fee Detail Chart](/mbrix/workflows/functions/system-functions/intra-bank-fee-detail-chart) - Generate chart data for fee analysis * [ECR Analysis](/mbrix/workflows/functions/system-functions/ecr-analysis) - Analyze ECR data for financial insights --- # Multi-Bank Fee Analysis URL: /mbrix/workflows/functions/system-functions/multi-bank-fee-analysis Generate comprehensive multi-bank fee analysis reports comparing fees across banks by category with percentage breakdowns *** title: Multi-Bank Fee Analysis description: Generate comprehensive multi-bank fee analysis reports comparing fees across banks by category with percentage breakdowns -------------------------------------------------------------------------------------------------------------------------------------- # Multi-Bank Fee Analysis Generates comprehensive multi-bank fee analysis reports. The function compares fees across multiple banks, groups data by categories, converts all charges to USD, and provides percentage breakdowns for sub-categories. **Technical Name**: `MultiBankFeeAnalysisFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `66e31772-bde2-4a8f-801d-c215b5cdc328` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------ | ------------------------------------------------------------------------------- | | `data` | object | Report configuration object (MReportMaster) containing query with bank fee data | The report query should include the following fields: * `bank_name` - Name of the bank * `name` - Category name * `total_charges` - Total charges for the service * `volume` - Transaction volume * `forex_rate` - Foreign exchange rate for currency conversion ## Input Example ```json { "data": { "reportConfig": { "query": { "selectFields": [ { "fieldName": "bank_name", "fieldAlias": "Bank" }, { "fieldName": "name", "fieldAlias": "Category" }, { "fieldName": "total_charges", "fieldAlias": "Total Charges" }, { "fieldName": "volume", "fieldAlias": "Volume" }, { "fieldName": "forex_rate", "fieldAlias": "Forex Rate" } ], "fromClause": { "mobjectId": "bank-fee-mobject-uuid" } } } } } ``` ## Output Schema | Field | Type | Description | | -------------- | ------- | -------------------------------------- | | `result` | object | Result object containing analysis data | | `result.data` | array | Array of Level 3 analysis objects | | `result.count` | integer | Number of categories analyzed | Each object in the `result.data` array contains: | Field | Type | Description | | ----------------------------- | ------- | -------------------------------------------------------------------------- | | `Bank` | string | Bank name (for parent category rows) | | `Custom Category Description` | string | Category or sub-category name | | `Bank Service Description` | string | Bank service description (for sub-categories) | | `Category` | string | Parent category name | | `Total Charges` | number | Total charges (converted to USD) | | `Total Volume` | number | Total transaction volume | | `Total Primary Charges` | number | Total primary charges (converted to USD) | | `Total Primary Volume` | number | Total primary volume | | `Potential Savings` | number | Potential savings (only for categories with include\_l3\_savings flag) | | `Percent` | boolean | Whether this row shows percentage breakdown | | `[Bank Name] Spend` | number | Custom field: Total spend for this bank (or percentage if Percent=true) | | `[Bank Name] Primary Volume` | number | Custom field: Primary volume for this bank (or percentage if Percent=true) | | `[Bank Name] Per unit` | number | Custom field: Average price per unit for this bank | ## Output Example ```json { "result": { "data": [ { "Custom Category Description": "Payment Services", "Category": "Payment Services", "ABC Bank Spend": 50000, "ABC Bank Primary Volume": 100000, "ABC Bank Per unit": 0.50, "XYZ Bank Spend": 45000, "XYZ Bank Primary Volume": 90000, "XYZ Bank Per unit": 0.50, "Potential Savings": 5000 }, { "Custom Category Description": "Wire Transfer", "Bank Service Description": "Wire Transfer", "Category": "Payment Services", "ABC Bank Spend": 30000, "ABC Bank Primary Volume": 60000, "ABC Bank Per unit": 0.50, "XYZ Bank Spend": 25000, "XYZ Bank Primary Volume": 50000, "XYZ Bank Per unit": 0.50 }, { "Custom Category Description": "Payment Services Percentages", "Category": "Payment Services", "Percent": true, "ABC Bank Spend": 0.60, "ABC Bank Primary Volume": 0.60, "XYZ Bank Spend": 0.56, "XYZ Bank Primary Volume": 0.56 } ], "count": 3 } } ``` ## How It Works The function performs the following analysis: 1. **Currency Conversion**: Converts all charges to USD using forex rates: ``` total_charges_converted = total_charges × forex_rate ``` 2. **Groups by Bank and Category**: Groups fee data by bank name and category 3. **Aggregates Metrics**: Sums charges and volumes for each bank-category combination 4. **Organizes by Category**: Structures results hierarchically: * Parent category rows show totals across all banks * Sub-category rows show breakdowns by bank service * Percentage rows show child category percentages relative to parent 5. **Calculates Per-Unit Prices**: Computes average price per unit for each bank: ``` per_unit = total_charges / total_primary_volume ``` 6. **Calculates Potential Savings**: For categories with `include_l3_savings` flag, calculates potential savings by comparing rates across banks 7. **Adds Percentage Breakdowns**: Creates percentage rows showing how sub-categories contribute to parent categories ## Use Cases ### Multi-Bank Fee Comparison Compare fees across multiple banks by category: ```json { "data": { "reportConfig": { "query": { "selectFields": [ {"fieldName": "bank_name", "fieldAlias": "Bank"}, {"fieldName": "name", "fieldAlias": "Category"}, {"fieldName": "total_charges", "fieldAlias": "Charges"}, {"fieldName": "volume", "fieldAlias": "Volume"}, {"fieldName": "forex_rate", "fieldAlias": "Forex"} ], "fromClause": { "mobjectId": "bank-fee-mobject-uuid" } } } } } ``` ### Category-Based Analysis Analyze fee distribution across categories and banks: ``` Start → FetchMData(Bank Fees) → MultiBankFeeAnalysis → Export → End ``` ## Related Functions * [Level 1 Analysis](/mbrix/workflows/functions/system-functions/level1-analysis) - Analyze intra-bank fee data with rate comparisons * [Intra-Bank Fee Detail Report](/mbrix/workflows/functions/system-functions/intra-bank-fee-detail-report) - Generate detailed transaction-level fee reports * [Export Data to CSV](/mbrix/workflows/functions/system-functions/export) - Export analysis results for further processing --- # Parse CSV/Excel File URL: /mbrix/workflows/functions/system-functions/parse-csv Parse CSV and Excel files from file storage and convert them to JSON format *** title: Parse CSV/Excel File description: Parse CSV and Excel files from file storage and convert them to JSON format ---------------------------------------------------------------------------------------- # Parse CSV/Excel File Parse CSV and Excel files from the file storage system and convert them to JSON format. The function automatically detects file type and handles headers, making it easy to process spreadsheet data in workflows. **Technical Name**: `ParseCSVMFunction` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `990807b7-c819-447d-887b-4921390679ac` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------------- | ------------------------------------------------------ | | `fileId` | string (uuid) | UUID of the file to parse (must exist in file storage) | ### Optional Parameters | Parameter | Type | Description | | ------------ | ------- | --------------------------------------------------------------- | | `hasHeader` | boolean | Whether the file has a header row (default: true) | | `sheetIndex` | integer | For Excel files, the sheet index to parse (0-based, default: 0) | ## Input Example ### Parse CSV with Headers ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "hasHeader": true } ``` ### Parse CSV without Headers ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "hasHeader": false } ``` ### Parse Excel File (Specific Sheet) ```json { "fileId": "b8c0d5e3-4f6g-5b2c-d9e8-8f7g6c5d4e3f", "hasHeader": true, "sheetIndex": 1 } ``` ## Output Schema | Field | Type | Description | | --------- | -------------- | ---------------------------------------------------------------------------- | | `headers` | array (string) | Column headers from the first row (only if hasHeader is true) | | `rows` | array (object) | Array of parsed row objects, where each object contains column names as keys | Each object in the `rows` array contains: * Column names as keys (from headers if hasHeader=true, or "Column1", "Column2", etc. if hasHeader=false) * Cell values as string values ## Output Example ### With Headers ```json { "headers": ["Name", "Email", "Age"], "rows": [ { "Name": "John Doe", "Email": "john@example.com", "Age": "30" }, { "Name": "Jane Smith", "Email": "jane@example.com", "Age": "25" } ] } ``` ### Without Headers ```json { "rows": [ { "Column1": "John Doe", "Column2": "john@example.com", "Column3": "30" }, { "Column1": "Jane Smith", "Column2": "jane@example.com", "Column3": "25" } ] } ``` ## Supported File Types * **CSV files** (`.csv`, `text/csv`, `text/plain`) * **Excel files** (`.xlsx`, `.xls`, `application/vnd.openxmlformats-officedocument.spreadsheetml.sheet`) ## How It Works 1. **File Detection**: Automatically detects file type based on MIME type or file extension 2. **Header Processing**: * If `hasHeader=true`: Uses first row as column names * If `hasHeader=false`: Generates column names like "Column1", "Column2", etc. 3. **Data Parsing**: * **CSV**: Parses using UTF-8 encoding * **Excel**: Supports both `.xlsx` and `.xls` formats, converts cell values to strings 4. **Data Normalization**: All values are converted to strings, missing cells are filled with empty strings ## Use Cases ### Process Uploaded CSV File Parse a CSV file uploaded by a user: ```json { "fileId": "{{context.uploadedFileId}}", "hasHeader": true } ``` ### Import Data from Excel Parse a specific sheet from an Excel file: ``` Start → UploadFile → ParseCSV(sheetIndex: 1) → ForEach(InsertMData) → End ``` ### Process File Without Headers Parse a file without header row: ```json { "fileId": "file-uuid", "hasHeader": false } ``` ## Excel Sheet Index For Excel files, use `sheetIndex` to specify which sheet to parse: * `0` - First sheet (default) * `1` - Second sheet * `2` - Third sheet * And so on... ## Error Handling ### File Not Found ```json { "error": "Error parsing file: File not found with ID: invalid-uuid" } ``` ### Unsupported File Type ```json { "error": "Error parsing file: Unsupported file type: application/pdf" } ``` ## Best Practices 1. **Always check fileId exists** before parsing 2. **Set hasHeader correctly** to ensure proper column mapping 3. **For Excel files**, verify sheet index exists (0-based) 4. **Handle empty files** gracefully in your workflow 5. **Validate parsed data** before processing further ## Related Functions * [Convert JSON to CSV](/mbrix/workflows/functions/system-functions/json-to-csv) - Convert JSON data to CSV format * [Export Data to CSV](/mbrix/workflows/functions/system-functions/export) - Execute a query and export to CSV * [Loop Through Items](/mbrix/workflows/functions/system-functions/foreach) - Process parsed rows in a loop --- # Parse Bank Statement URL: /mbrix/workflows/functions/system-functions/parse-statement Parse bank statements and other financial documents from PDF, XML, EDI, and Excel formats *** title: Parse Bank Statement description: Parse bank statements and other financial documents from PDF, XML, EDI, and Excel formats ------------------------------------------------------------------------------------------------------ # Parse Bank Statement Parse bank statements and other financial documents from various file formats. The function automatically detects file type, selects the appropriate parser, and extracts account information, transactions, and fee details. **Technical Name**: `ParseStatementFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `66e31772-bde2-4a8f-801d-c215b5cdc321` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------------- | --------------------------------------------------------------- | | `fileId` | string (uuid) | UUID of the uploaded file to parse (must exist in file storage) | ### Optional Parameters | Parameter | Type | Description | | ------------------ | ------------- | ----------------------------------------------------------------------- | | `bankName` | string | Name of the bank for statement identification and parser selection | | `parserName` | string | Specific parser bean name to use (e.g., "chaseBankParser") | | `parserPatternId` | string (uuid) | UUID of a parser pattern configuration to use for pattern-based parsing | | `currency` | string | Currency code to use (e.g., "USD", "EUR") | | `country` | string | Country alpha-2 code (e.g., "US", "GB") | | `usePatternParser` | boolean | Force use of pattern-based parser instead of bank-specific parsers | ## Input Example ### Basic Parsing ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d" } ``` ### With Bank Name ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "bankName": "Chase Bank", "currency": "USD", "country": "US" } ``` ### Using Specific Parser ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "parserName": "chaseBankParser" } ``` ### Using Pattern-Based Parser ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "parserPatternId": "pattern-uuid-here", "usePatternParser": true } ``` ## Supported File Types * **PDF** (`application/pdf`) - Bank statement PDFs * **XML** (`application/xml`, `text/xml`) - CAMT.053, ISO 20022 formats * **EDI** (`.edi`) - Electronic Data Interchange formats * **Excel** (`.xlsx`, `.xls`) - Spreadsheet-based statements ## Output Schema | Field | Type | Description | | ------------------- | ------ | ---------------------------------------------------------- | | `statementGroup` | object | Group information about the parsed statement (metadata) | | `statementAccounts` | array | Account information including balances and account details | | `statementServices` | array | Service/transaction details including fees and charges | The output structure contains: * **Statement Metadata**: Bank name, account numbers, statement period, currency * **Account Balances**: Opening/closing balances, ledger balances * **Activity Details**: Transactions, service charges, fees * **Conversion Rates**: Exchange rates if applicable * **Tax Details**: Tax information if present ## Output Example ```json { "statementGroup": { "bankName": "Chase Bank", "fileName": "statement_2024_01.pdf", "statementFrom": "2024-01-01", "statementTo": "2024-01-31", "duplicate": false }, "statementAccounts": [ { "accountNumber": "1234567890", "accountType": "DETAIL", "openingBalance": 10000.00, "closingBalance": 9500.00, "currency": "USD" } ], "statementServices": [ { "serviceDescription": "Wire Transfer", "unitPrice": 25.00, "volume": 5, "totalCharges": 125.00, "accountNumber": "1234567890" } ] } ``` ## How It Works 1. **File Type Detection**: Automatically detects file type (PDF, XML, EDI, Excel) 2. **Parser Selection**: * If `parserName` provided: Uses specified parser * If `parserPatternId` or `usePatternParser=true`: Uses pattern-based generic parser * If `bankName` provided: Attempts to find bank-specific parser or pattern * Otherwise: Tries all available parsers until one succeeds 3. **Parsing**: Extracts statement data based on file format 4. **Data Enrichment**: * Resolves bank metadata * Populates currency and country information * Validates account numbers * Checks for duplicate statements 5. **Output**: Returns structured statement data ## Use Cases ### Parse Uploaded Statement Parse a bank statement uploaded by a user: ```json { "fileId": "{{context.uploadedFileId}}", "bankName": "Wells Fargo", "currency": "USD" } ``` ### Process Multiple Statements Parse multiple statements in a workflow: ``` Start → UploadFile → ParseStatement → ProcessFees → End ``` ### Use Pattern-Based Parsing Parse statements using a custom parser pattern: ```json { "fileId": "file-uuid", "parserPatternId": "custom-pattern-uuid", "usePatternParser": true } ``` ## Parser Selection Strategy The function uses the following strategy to select a parser: 1. **Explicit Parser**: If `parserName` is provided, uses that parser 2. **Pattern Parser**: If `parserPatternId` or `usePatternParser=true`, uses pattern-based parser 3. **Bank-Specific**: If `bankName` is provided, searches for bank-specific parser or pattern 4. **Fallback**: Tries all available parsers sequentially until one succeeds 5. **Generic Parser**: Falls back to generic PDF parser if all specific parsers fail ## Error Handling ### File Not Found ```json { "error": "File not found with ID: invalid-uuid" } ``` ### Unsupported File Type ```json { "error": "Unsupported file type: image/jpeg" } ``` ### Bank Not Found ```json { "error": "No bank metadata found for bank: Unknown Bank" } ``` ## Best Practices 1. **Provide bankName** when known to improve parser selection accuracy 2. **Use parserPatternId** for custom statement formats 3. **Set currency and country** for proper data enrichment 4. **Handle duplicate detection** - check `duplicate` flag in output 5. **Validate parsed data** before processing further ## Related Functions * [Statement Processor](/mbrix/workflows/functions/system-functions/statement-processor) - Process parsed statements by mapping categories, forex rates, and other data * [Statement Parser](/mbrix/workflows/functions/system-functions/statement-parser) - Alternative parser function * [Parse CSV/Excel File](/mbrix/workflows/functions/system-functions/parse-csv) - Parse CSV and Excel files for general data * [ECR Analysis](/mbrix/workflows/functions/system-functions/ecr-analysis) - Analyze ECR data from parsed statements --- # Pipeline Query URL: /mbrix/workflows/functions/system-functions/pipeline-query Execute a query, create a materialized view, and optionally write results to an Object with flexible field mappings *** title: Pipeline Query description: Execute a query, create a materialized view, and optionally write results to an Object with flexible field mappings -------------------------------------------------------------------------------------------------------------------------------- # Pipeline Query Execute a query and create a materialized view for use in subsequent workflow steps. Optionally write query results directly to an Object with flexible field mappings supporting constants, runtime values, and node field references. **Technical Name**: `PipelineQueryFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `1b4ff763-94ad-4726-8dbe-c95a65ad0c00` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ------------- | ------ | ----------------------------------------------------- | | `queryMaster` | object | Query configuration object for building the SQL query | ### Optional Parameters | Parameter | Type | Description | | ---------------- | ------ | ------------------------------------------------- | | `writeToMobject` | object | Configuration to write query results to an Object | ### WriteToMobject Configuration | Parameter | Type | Description | | --------------- | ------------- | -------------------------------------------------------------- | | `mobjectId` | string (uuid) | ID of the target Object to write data to | | `fieldMappings` | array | Array of field mappings between source query and target Object | ### Field Mapping Properties | Parameter | Type | Description | | -------------------- | ------ | ------------------------------------------------------------------------------------------- | | `mobjectField` | string | Name of the field in the target Object (required) | | `sourceType` | string | Type of source: "FIELD", "CONSTANT", "RUNTIME\_CONSTANT", or "NODE\_FIELD" (required) | | `sourceField` | string | Name of the field from query results (required if sourceType is FIELD) | | `constantValue` | string | Constant value to use (required if sourceType is CONSTANT) | | `runtimeConstantKey` | string | Runtime constant key (required if sourceType is RUNTIME\_CONSTANT) | | `nodeFieldId` | string | Node field identifier in format "nodeId->fieldName" (required if sourceType is NODE\_FIELD) | ## Source Types ### FIELD Map a field directly from the query results: ```json { "mobjectField": "customerName", "sourceType": "FIELD", "sourceField": "name" } ``` ### CONSTANT Use a constant value: ```json { "mobjectField": "status", "sourceType": "CONSTANT", "constantValue": "Active" } ``` ### RUNTIME\_CONSTANT Use a runtime constant value: **Available Runtime Constants:** * `CURRENT_USER` - Current user's username * `CURRENT_USER_ID` - Current user's ID * `CURRENT_ROLE` - Current user's role names (comma-separated) * `CURRENT_ROLE_ID` - Current user's role ID * `CURRENT_TIMESTAMP` - Current local timestamp * `CURRENT_UTC_TIMESTAMP` - Current UTC timestamp * `TODAY` - Current date * `EXECUTION_ID` - Current workflow execution ID * `REQUEST_ID` - Current request ID ```json { "mobjectField": "createdBy", "sourceType": "RUNTIME_CONSTANT", "runtimeConstantKey": "CURRENT_USER_ID" } ``` ### NODE\_FIELD Reference a field from a previous workflow node: ```json { "mobjectField": "orderId", "sourceType": "NODE_FIELD", "nodeFieldId": "node-123->orderId" } ``` ## Input Example ### Query Only (Create Materialized View) ```json { "queryMaster": { "selectFields": [ { "fieldName": "name", "fieldAlias": "customerName" }, { "fieldName": "email", "fieldAlias": "email" } ], "fromClause": { "mobjectId": "customer-mobject-uuid" } } } ``` ### Query with Write to Object ```json { "queryMaster": { "selectFields": [ {"fieldName": "name", "fieldAlias": "customerName"}, {"fieldName": "email", "fieldAlias": "email"} ], "fromClause": { "mobjectId": "customer-mobject-uuid" } }, "writeToMobject": { "mobjectId": "report-mobject-uuid", "fieldMappings": [ { "mobjectField": "customerName", "sourceType": "FIELD", "sourceField": "customerName" }, { "mobjectField": "email", "sourceType": "FIELD", "sourceField": "email" }, { "mobjectField": "status", "sourceType": "CONSTANT", "constantValue": "Processed" }, { "mobjectField": "createdBy", "sourceType": "RUNTIME_CONSTANT", "runtimeConstantKey": "CURRENT_USER_ID" } ] } } ``` ## Output Schema | Field | Type | Description | | -------------- | ------- | ---------------------------------------------------------------------------------- | | `viewName` | string | Generated materialized view name (can be used in subsequent queries) | | `sql` | string | The SQL query that was executed | | `rowsInserted` | integer | Number of rows inserted into Object (only if writeToMobject was configured) | | `writeSuccess` | boolean | Whether the write operation was successful (only if writeToMobject was configured) | ## Output Example ### Query Only ```json { "viewName": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6", "sql": "SELECT name AS customerName, email FROM customer_table WHERE status = 'Active'" } ``` ### With Write to Object ```json { "viewName": "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6", "sql": "SELECT name AS customerName, email FROM customer_table WHERE status = 'Active'", "rowsInserted": 150, "writeSuccess": true } ``` ## How It Works 1. **Query Execution**: Executes the query defined in `queryMaster` 2. **Materialized View Creation**: Creates a materialized view with a unique name 3. **Optional Write Operation**: If `writeToMobject` is configured: * Maps query fields to Object fields using field mappings * Supports constants, runtime values, and node field references * Creates data ownership records automatically * Inserts records into the target Object ## Use Cases ### Create Reusable Query View Create a materialized view for use in multiple workflow steps: ```json { "queryMaster": { "selectFields": [ {"fieldName": "orderNumber", "fieldAlias": "Order"}, {"fieldName": "totalAmount", "fieldAlias": "Amount"} ], "fromClause": { "mobjectId": "order-mobject-uuid" }, "where": [ { "field": "status", "operator": "equals", "value": "Completed" } ] } } ``` ### Transform and Load Data Query data, transform it, and write to another Object: ``` Start → PipelineQuery(Query + Write) → ProcessResults → End ``` ### Use Runtime Values Populate audit fields automatically: ```json { "queryMaster": {...}, "writeToMobject": { "mobjectId": "audit-mobject-uuid", "fieldMappings": [ { "mobjectField": "createdBy", "sourceType": "RUNTIME_CONSTANT", "runtimeConstantKey": "CURRENT_USER_ID" }, { "mobjectField": "createdAt", "sourceType": "RUNTIME_CONSTANT", "runtimeConstantKey": "CURRENT_TIMESTAMP" } ] } } ``` ## Materialized View Usage The generated `viewName` can be used in subsequent queries: ```sql SELECT * FROM "a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6" ``` ## Data Ownership When writing to Object, the function automatically: * Creates data ownership records for the current organization * Sets system fields (created\_at, created\_by, updated\_at, updated\_by, deleted) * Ensures proper data isolation across organizations ## Related Functions * [Get Multiple Records](/mbrix/workflows/functions/crud-operations/multiple-record-fetch-mdata) - Query data without creating a view * [Insert MData](/mbrix/workflows/functions/crud-operations/insert-mdata) - Insert individual records * [Bulk Insert MData](/mbrix/workflows/functions/crud-operations/bulk-insert-mdata) - Bulk insert records --- # Potential Savings Intra-Bank URL: /mbrix/workflows/functions/system-functions/potential-saving-intra-bank Calculate potential savings from intra-bank fee analysis by comparing actual charges against minimum rates *** title: Potential Savings Intra-Bank description: Calculate potential savings from intra-bank fee analysis by comparing actual charges against minimum rates ----------------------------------------------------------------------------------------------------------------------- # Potential Savings Intra-Bank Calculate potential savings from intra-bank fee analysis. The function compares actual charges against minimum rates across bank services and returns a summary of total potential savings and the number of services with savings opportunities. **Technical Name**: `PotentialSavingIntraBankFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `66e31772-bde2-4a8f-801d-c215b5cdc326` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------ | --------------------------------------------------------------------------------------- | | `data` | object | Report configuration object (MReportMaster) containing query with bank service fee data | The report query should include the following fields: * `bank_service_description` - Name/description of the bank service * `unit_price` - Unit price/rate for the service * `volume` - Transaction volume * `total_charges` - Total charges for the service * `forex_rate` - Foreign exchange rate (if applicable) ## Input Example ```json { "data": { "reportConfig": { "query": { "selectFields": [ { "fieldName": "bank_service_description", "fieldAlias": "Service" }, { "fieldName": "unit_price", "fieldAlias": "Unit Price" }, { "fieldName": "volume", "fieldAlias": "Volume" }, { "fieldName": "total_charges", "fieldAlias": "Total Charges" }, { "fieldName": "forex_rate", "fieldAlias": "Forex Rate" } ], "fromClause": { "mobjectId": "bank-fee-mobject-uuid" } } } } } ``` ## Output Schema | Field | Type | Description | | -------- | ------ | ----------------------------------------- | | `result` | object | Summary object containing savings metrics | The `result` object contains: | Field | Type | Description | | ---------- | ------ | ---------------------------------------------------- | | `Savings` | string | Total potential savings (rounded to nearest integer) | | `Variance` | string | Number of services with potential savings > 1 | ## Output Example ```json { "result": { "Savings": "5000", "Variance": "12" } } ``` ## How It Works The function performs the following analysis: 1. **Groups by Service**: Groups fee data by bank service description 2. **Finds Min/Max Rates**: Identifies minimum and maximum unit prices for each service 3. **Calculates Savings**: Compares actual charges against charges at minimum rate: ``` savings = total_charges - (forex_rate × volume × min_rate) ``` 4. **Aggregates by Service**: Sums savings for each service 5. **Filters Results**: Only includes services where total\_savings > 1 6. **Returns Summary**: * Total savings across all services (rounded) * Number of services with savings opportunities (Variance) ## Use Cases ### Quick Savings Assessment Get a quick summary of potential savings: ```json { "data": { "reportConfig": { "query": { "selectFields": [ {"fieldName": "bank_service_description", "fieldAlias": "Service"}, {"fieldName": "unit_price", "fieldAlias": "Rate"}, {"fieldName": "volume", "fieldAlias": "Volume"}, {"fieldName": "total_charges", "fieldAlias": "Charges"}, {"fieldName": "forex_rate", "fieldAlias": "Forex"} ], "fromClause": { "mobjectId": "bank-fee-mobject-uuid" }, "where": [ { "field": "transaction_date", "operator": "greaterThanOrEquals", "value": "2024-01-01" } ] } } } } ``` ### Savings Dashboard Display total savings in a dashboard: ``` Start → FetchMData(Bank Fees) → PotentialSavingIntraBank → DisplayDashboard → End ``` ## Related Functions * [Intra-Bank Fee Detail Chart](/mbrix/workflows/functions/system-functions/intra-bank-fee-detail-chart) - Generate detailed chart data for fee analysis * [Intra-Bank Fee Detail Report](/mbrix/workflows/functions/system-functions/intra-bank-fee-detail-report) - Generate detailed transaction-level reports * [Level 1 Analysis](/mbrix/workflows/functions/system-functions/level1-analysis) - Analyze intra-bank fee data with rate comparisons --- # Potential Savings Multi-Bank URL: /mbrix/workflows/functions/system-functions/potential-saving-multi-bank Calculate potential savings summary from multi-bank fee analysis by comparing rates across banks *** title: Potential Savings Multi-Bank description: Calculate potential savings summary from multi-bank fee analysis by comparing rates across banks ------------------------------------------------------------------------------------------------------------- # Potential Savings Multi-Bank Calculate potential savings summary from multi-bank fee analysis. The function compares fees across multiple banks, groups data by categories, and returns the total potential savings for categories configured with savings calculation enabled. **Technical Name**: `PotentialSavingMultiBankFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `66e31772-bde2-4a8f-801d-c215b5cdc327` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------ | ------------------------------------------------------------------------------- | | `data` | object | Report configuration object (MReportMaster) containing query with bank fee data | The report query should include the following fields: * `bank_name` - Name of the bank * `name` - Category name * `total_charges` - Total charges for the service * `volume` - Transaction volume * `forex_rate` - Foreign exchange rate for currency conversion ## Input Example ```json { "data": { "reportConfig": { "query": { "selectFields": [ { "fieldName": "bank_name", "fieldAlias": "Bank" }, { "fieldName": "name", "fieldAlias": "Category" }, { "fieldName": "total_charges", "fieldAlias": "Total Charges" }, { "fieldName": "volume", "fieldAlias": "Volume" }, { "fieldName": "forex_rate", "fieldAlias": "Forex Rate" } ], "fromClause": { "mobjectId": "bank-fee-mobject-uuid" } } } } } ``` ## Output Schema | Field | Type | Description | | -------- | ------ | ---------------------------------------- | | `result` | object | Summary object containing savings metric | The `result` object contains: | Field | Type | Description | | --------- | ------------- | ---------------------------------------------------- | | `Savings` | number (long) | Total potential savings (rounded to nearest integer) | ## Output Example ```json { "result": { "Savings": 15000 } } ``` ## How It Works The function performs the following analysis: 1. **Currency Conversion**: Converts all charges to USD using forex rates: ``` total_charges_converted = total_charges × forex_rate ``` 2. **Groups by Bank and Category**: Groups fee data by bank name and category 3. **Calculates Per-Unit Prices**: Computes average price per unit for each bank-category combination: ``` per_unit = total_charges / total_primary_volume ``` 4. **Organizes by Category**: Structures results hierarchically by category and bank 5. **Calculates Potential Savings**: For categories with `include_l3_savings` flag enabled: * Compares per-unit prices across banks * Calculates potential savings by identifying the minimum rate * Aggregates savings across all eligible categories 6. **Returns Summary**: Returns total potential savings (rounded to nearest integer) ## Category Configuration Potential savings are only calculated for categories that have the `include_l3_savings` flag set to `true` in the Category Object. Categories without this flag will have savings set to 0. ## Use Cases ### Multi-Bank Savings Summary Get a quick summary of potential savings across multiple banks: ```json { "data": { "reportConfig": { "query": { "selectFields": [ {"fieldName": "bank_name", "fieldAlias": "Bank"}, {"fieldName": "name", "fieldAlias": "Category"}, {"fieldName": "total_charges", "fieldAlias": "Charges"}, {"fieldName": "volume", "fieldAlias": "Volume"}, {"fieldName": "forex_rate", "fieldAlias": "Forex"} ], "fromClause": { "mobjectId": "bank-fee-mobject-uuid" } } } } } ``` ### Savings Dashboard Display total potential savings in a dashboard: ``` Start → FetchMData(Bank Fees) → PotentialSavingMultiBank → DisplayDashboard → End ``` ## Related Functions * [Multi-Bank Fee Analysis](/mbrix/workflows/functions/system-functions/multi-bank-fee-analysis) - Generate detailed multi-bank fee analysis reports * [Potential Savings Intra-Bank](/mbrix/workflows/functions/system-functions/potential-saving-intra-bank) - Calculate potential savings from intra-bank analysis * [Level 1 Analysis](/mbrix/workflows/functions/system-functions/level1-analysis) - Analyze intra-bank fee data with rate comparisons --- # Resolve Lookup Field URL: /mbrix/workflows/functions/system-functions/resolve-lookup-field Resolve lookup fields by finding MData records based on field name and value, returning the record ID *** title: Resolve Lookup Field description: Resolve lookup fields by finding MData records based on field name and value, returning the record ID ------------------------------------------------------------------------------------------------------------------ # Resolve Lookup Field Resolve lookup fields by finding MData records in a specified Object where a field matches a given value. Returns the UUID of the matching record, which is useful for converting string values (like names) into record IDs for data import and workflow processing. **Technical Name**: `ResolveLookupFieldFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `8f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea2` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ----------- | ------------- | ------------------------------------------------ | | `mObjectId` | string (UUID) | The UUID of the Object to search in | | `fieldName` | string | The name of the field in the JSON data to search | ### Optional Parameters | Parameter | Type | Description | | ------------- | ------ | ------------------------------------------------------------- | | `lookupValue` | string | The value to search for as a String. If null, returns null ID | ## Input Example ```json { "mObjectId": "123e4567-e89b-12d3-a456-426614174000", "fieldName": "name", "lookupValue": "Acme Corporation" } ``` ## Output Schema | Field | Type | Description | | ------- | ------------- | --------------------------------------------------------- | | `id` | string (UUID) | The ID of the found record (null if lookupValue is null) | | `found` | boolean | Whether a record was found | | `error` | string | Error message if no record was found or an error occurred | ## Output Example ### Success Response ```json { "id": "789e4567-e89b-12d3-a456-426614174001", "found": true } ``` ### Error Response ```json { "error": "No record found for name = Acme Corporation", "found": false } ``` ### Null Lookup Value ```json { "id": null } ``` ## How It Works The function performs the following steps: 1. **Validates Input**: Checks that `mObjectId` and `fieldName` are provided 2. **Handles Null Values**: If `lookupValue` is null, returns null ID immediately 3. **Searches MData**: Uses `MDataService.findSingleMDataByFields()` to find a record where the specified field matches the lookup value 4. **Returns Result**: * If found: Returns the record's UUID and `found: true` * If not found: Returns an error message and `found: false` ## Use Cases ### Data Import with Lookup Resolution Convert string values to record IDs during data import: ```json { "mObjectId": "bank-mobject-uuid", "fieldName": "bank_name", "lookupValue": "Chase Bank" } ``` ### Workflow Lookup Resolution Resolve lookup fields in workflow processing: ``` Start → ParseCSV → ResolveLookupField(Bank) → InsertMData → End ``` ### Conditional Lookup Handle optional lookup values: ```json { "mObjectId": "vendor-mobject-uuid", "fieldName": "vendor_code", "lookupValue": "${csv.vendor_code}" } ``` If `lookupValue` is null or empty, the function returns `null` ID without error. ## Notes * The function searches for an **exact match** on the specified field * Only the **first matching record** is returned if multiple records exist * Field matching is case-sensitive * Commonly used in file import workflows to convert text values to record references ## Related Functions * [Resolve Picklist Field](/mbrix/workflows/functions/system-functions/resolve-picklist-field) - Resolve picklist fields by finding picklist items by name for a given category * [Fetch MData](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Retrieve MData records with filtering and pagination * [Insert MData](/mbrix/workflows/functions/crud-operations/insert-mdata) - Create new MData records * [Parse CSV](/mbrix/workflows/functions/system-functions/parse-csv) - Parse CSV files with automatic lookup field resolution --- # Resolve Picklist Field URL: /mbrix/workflows/functions/system-functions/resolve-picklist-field Resolve picklist fields by finding picklist items by name for a given category, returning the item ID *** title: Resolve Picklist Field description: Resolve picklist fields by finding picklist items by name for a given category, returning the item ID ------------------------------------------------------------------------------------------------------------------ # Resolve Picklist Field Resolve picklist fields by finding picklist items in a specified category where the item name matches a given value. Returns the UUID of the matching picklist item, which is useful for converting string values (like picklist item names) into picklist item IDs for data import and workflow processing. **Technical Name**: `ResolvePicklistFieldFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `9f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea3` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ------------ | ------------- | ---------------------------------------------- | | `categoryId` | string (UUID) | The UUID of the Picklist Category to search in | ### Optional Parameters | Parameter | Type | Description | | ------------------ | ------ | --------------------------------------------------------------------- | | `picklistItemName` | string | The name of the picklist item to search for. If null, returns null ID | ## Input Example ```json { "categoryId": "123e4567-e89b-12d3-a456-426614174000", "picklistItemName": "Active" } ``` ## Output Schema | Field | Type | Description | | ------- | ------------- | -------------------------------------------------------------------- | | `id` | string (UUID) | The ID of the found picklist item (null if picklistItemName is null) | | `found` | boolean | Whether a picklist item was found | | `error` | string | Error message if no item was found or an error occurred | ## Output Example ### Success Response ```json { "id": "789e4567-e89b-12d3-a456-426614174001", "found": true } ``` ### Error Response ```json { "error": "No picklist item found with name 'Active' in category 123e4567-e89b-12d3-a456-426614174000", "found": false } ``` ### Null Picklist Item Name ```json { "id": null } ``` ## How It Works The function performs the following steps: 1. **Validates Input**: Checks that `categoryId` is provided 2. **Handles Null Values**: If `picklistItemName` is null, returns null ID immediately 3. **Searches Picklist Items**: Uses `PicklistItemService.getItemsByCategory()` to retrieve all items in the category, then filters for a case-insensitive match 4. **Returns Result**: * If found: Returns the picklist item's UUID and `found: true` * If not found: Returns an error message and `found: false` ## Matching Behavior * **Case-Insensitive**: The function uses case-insensitive matching (`equalsIgnoreCase`) * **Trimming**: Whitespace is automatically trimmed from the `picklistItemName` before matching * **First Match**: Only the first matching item is returned if multiple items exist with the same name (case-insensitive) ## Use Cases ### Data Import with Picklist Resolution Convert string values to picklist item IDs during data import: ```json { "categoryId": "status-category-uuid", "picklistItemName": "Active" } ``` ### Workflow Picklist Resolution Resolve picklist fields in workflow processing: ``` Start → ParseCSV → ResolvePicklistField(Status) → InsertMData → End ``` ### Conditional Picklist Resolution Handle optional picklist values: ```json { "categoryId": "priority-category-uuid", "picklistItemName": "${csv.priority}" } ``` If `picklistItemName` is null or empty, the function returns `null` ID without error. ## Notes * The function searches for a **case-insensitive match** on the picklist item name * Only the **first matching item** is returned if multiple items exist * Matching is performed after trimming whitespace from the item name * Commonly used in file import workflows to convert text values to picklist item references * The picklist category must exist and contain items for the function to succeed ## Related Functions * [Resolve Lookup Field](/mbrix/workflows/functions/system-functions/resolve-lookup-field) - Resolve lookup fields by finding MData records based on field name and value * [Parse CSV](/mbrix/workflows/functions/system-functions/parse-csv) - Parse CSV files with automatic picklist field resolution * [Insert MData](/mbrix/workflows/functions/crud-operations/insert-mdata) - Create new MData records with picklist field references --- # Run Report URL: /mbrix/workflows/functions/system-functions/run-report Execute reports based on MReportMaster configuration and return report data. Supports existing reports by ID or ad-hoc reports with full configuration *** title: Run Report description: Execute reports based on MReportMaster configuration and return report data. Supports existing reports by ID or ad-hoc reports with full configuration ------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Run Report Execute reports based on MReportMaster configuration and return report data. The function supports executing existing saved reports by ID or creating ad-hoc reports with full configuration. It supports multiple input patterns for flexibility. **Technical Name**: `RunReportFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `a7c9f3b2-4e5d-4a1f-9b8c-2d3e4f5a6b7c` ## Input Schema The function supports three input patterns: ### Pattern 1: Nested with `reportConfig` (Ad-hoc Reports) Use this pattern for ad-hoc reports with full configuration: | Parameter | Type | Description | | ---------------- | ------- | ----------------------------------------------- | | `reportConfig` | object | Complete MReportMaster configuration object | | `formatResponse` | boolean | Whether to format the response (default: false) | ### Pattern 2: Nested with `reportMaster` (Ad-hoc Reports) Alternative nested pattern: | Parameter | Type | Description | | ---------------- | ------- | ----------------------------------------------- | | `reportMaster` | object | Complete MReportMaster configuration object | | `formatResponse` | boolean | Whether to format the response (default: false) | ### Pattern 3: Flat Structure (Existing Reports) Use this pattern for existing reports by ID or flat configuration: | Parameter | Type | Description | | ------------------- | ------------- | ------------------------------------------------- | | `reportId` | string (UUID) | UUID of existing report to execute | | `reportName` | string | Name of the report | | `flowId` | string (UUID) | UUID of the flow to execute (optional) | | `dashboardId` | string (UUID) | UUID of the dashboard (optional) | | `description` | string | Report description | | `reportConfig` | object | Report configuration (QueryMaster, filters, etc.) | | `additionalFilters` | object | Additional filters to apply | | `drilldownFilters` | object | Drilldown filters to apply | | `globalFilters` | object | Global filters to apply | | `drillDownConfig` | object | Drill down configuration | | `formatResponse` | boolean | Whether to format the response (default: false) | ## Input Examples ### Execute Existing Report by ID ```json { "reportId": "123e4567-e89b-12d3-a456-426614174000", "formatResponse": false } ``` ### Ad-hoc Report with Nested Config ```json { "reportConfig": { "reportName": "Sales Report", "reportConfig": { "query": { "selectFields": [ { "fieldName": "amount", "fieldAlias": "Total Sales" }, { "fieldName": "date", "fieldAlias": "Date" } ], "fromClause": { "mobjectId": "sales-mobject-uuid" }, "criteriaTree": { "lhs": { "fieldName": "date" }, "operator": "greaterThanOrEquals", "rhs": { "value": "2024-01-01" } } } }, "additionalFilters": {}, "globalFilters": {} }, "formatResponse": true } ``` ### Flat Structure with Filters ```json { "reportName": "Customer Analysis", "reportConfig": { "query": { "selectFields": [ { "fieldName": "customer_name", "fieldAlias": "Customer" }, { "fieldName": "total_orders", "fieldAlias": "Orders" } ], "fromClause": { "mobjectId": "customer-mobject-uuid" } } }, "additionalFilters": { "status": "Active" }, "formatResponse": false } ``` ## Output Schema | Field | Type | Description | | --------- | ------- | ------------------------------------------------------------------------ | | `success` | boolean | Indicates if the report execution was successful | | `data` | object | Report data result (structure depends on report type and formatResponse) | | `error` | string | Error message if execution fails | ## Output Example ### Success Response ```json { "success": true, "data": { "columns": [ { "fieldAlias": "Total Sales", "fieldName": "amount" }, { "fieldAlias": "Date", "fieldName": "date" } ], "data": [ { "Total Sales": 5000, "Date": "2024-01-15" }, { "Total Sales": 7500, "Date": "2024-01-16" } ], "totalRecords": 2 } } ``` ### Error Response ```json { "success": false, "error": "Error executing report: Report configuration is required" } ``` ## How It Works The function performs the following steps: 1. **Parse Input**: Detects the input pattern (nested `reportConfig`, nested `reportMaster`, or flat structure) 2. **Load Report Configuration**: * If `reportId` is provided, fetches the saved report configuration * Otherwise, uses the provided configuration 3. **Apply Filters**: Applies additional filters, drilldown filters, and global filters if provided 4. **Execute Report**: Runs the report query using `MReportService.runReport()` 5. **Format Response**: Optionally formats the response based on `formatResponse` flag 6. **Return Result**: Returns report data with success status ## Use Cases ### Execute Saved Report Run a pre-configured report by ID: ```json { "reportId": "saved-report-uuid" } ``` ### Dynamic Report with Filters Create a dynamic report with runtime filters: ```json { "reportConfig": { "reportName": "Dynamic Sales Report", "reportConfig": { "query": { "selectFields": [ {"fieldName": "amount", "fieldAlias": "Sales"}, {"fieldName": "region", "fieldAlias": "Region"} ], "fromClause": { "mobjectId": "sales-mobject-uuid" } } }, "additionalFilters": { "region": "${workflow.region}", "date_range": "${workflow.dateRange}" } } } ``` ### Workflow Report Execution Execute reports within workflows: ``` Start → FetchMData → RunReport → ProcessResults → End ``` ### Formatted Report Output Get formatted report data: ```json { "reportId": "report-uuid", "formatResponse": true } ``` ## Notes * **Report ID Priority**: If `reportId` is provided, the function loads the saved report configuration and ignores other configuration fields * **Ad-hoc Reports**: For ad-hoc reports, provide complete `reportConfig` with query structure * **Filter Application**: Filters are applied in order: global filters → additional filters → drilldown filters * **Format Response**: When `formatResponse` is `true`, the response includes formatted data suitable for display * **Query Structure**: The `reportConfig.query` follows QueryMaster structure with selectFields, criteriaTree, joinInfos, etc. * **Materialized Views**: Reports may use materialized views for performance optimization ## Related Functions * [Fetch MData](/mbrix/workflows/functions/crud-operations/fetch-mdata) - Retrieve MData records with filtering and pagination * [Export](/mbrix/workflows/functions/system-functions/export) - Export query results to CSV format * [Pipeline Query](/mbrix/workflows/functions/system-functions/pipeline-query) - Execute queries with data transformation and materialized views --- # Load Data from S3 URL: /mbrix/workflows/functions/system-functions/s3-data-load Load data from S3 files and store in Objects with optional batch processing. Supports CSV, JSON, and TXT formats with configurable parsing options *** title: Load Data from S3 description: Load data from S3 files and store in Objects with optional batch processing. Supports CSV, JSON, and TXT formats with configurable parsing options --------------------------------------------------------------------------------------------------------------------------------------------------------------- # Load Data from S3 Load data from Amazon S3 files and optionally store it in Objects with batch processing. This function provides secure S3 connectivity, multi-format file support (CSV, JSON, TXT), configurable parsing options, and automatic type detection. **Technical Name**: `S3DataLoadFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `17930933-4345-4ec6-bc43-fbbaf26f463c` ## Input Schema ### Required Parameters | Parameter | Type | Description | | -------------- | ------------- | ------------------------------------------------------------------- | | `connectionId` | string (UUID) | UUID of the S3 connection to use for data loading | | `filePath` | string | S3 key/path to the file to be processed (max 1024 characters) | | `fileType` | string | Type of file to process: `CSV`, `JSON`, `XLSX`, `TXT`, or `PARQUET` | | `batchSize` | integer | Number of records to process in each batch (1-10000, default: 1000) | | `skipRows` | integer | Number of rows to skip from the beginning of the file (default: 0) | | `delimiter` | string | Delimiter character for CSV files (max 5 characters, default: ",") | ### Optional Parameters | Parameter | Type | Description | | --------------- | ------------- | ------------------------------------------------------------------------------------------------------------------------------------ | | `mobjectId` | string (UUID) | UUID of the Object where data will be stored (optional for query-only execution) | | `hasHeader` | boolean | Whether the file has a header row (default: true) | | `encoding` | string | Character encoding of the file: `UTF-8`, `UTF-16`, `ISO-8859-1`, or `Windows-1252` (default: UTF-8) | | `datePattern` | string | Pattern for parsing date fields (e.g., 'yyyy-MM-dd', max 50 characters) | | `maxRecords` | integer | Maximum number of records to process (0 means no limit, default: 0) | | `fieldMappings` | object | Optional field mappings to transform source data fields to target MData fields. Key is source field name, value is target field name | ## Input Example ### Load CSV File to Object ```json { "connectionId": "123e4567-e89b-12d3-a456-426614174000", "filePath": "data/sales/2024/sales_data.csv", "fileType": "CSV", "mobjectId": "sales-mobject-uuid", "batchSize": 1000, "skipRows": 1, "delimiter": ",", "hasHeader": true, "encoding": "UTF-8", "maxRecords": 0 } ``` ### Load JSON File with Field Mappings ```json { "connectionId": "s3-connection-uuid", "filePath": "exports/customers.json", "fileType": "JSON", "mobjectId": "customer-mobject-uuid", "batchSize": 500, "skipRows": 0, "fieldMappings": { "customer_name": "name", "customer_email": "email", "customer_phone": "phone" }, "encoding": "UTF-8" } ``` ### Query-Only Execution (No Storage) ```json { "connectionId": "s3-connection-uuid", "filePath": "reports/data.csv", "fileType": "CSV", "batchSize": 1000, "skipRows": 0, "delimiter": ",", "hasHeader": true, "maxRecords": 100 } ``` ## Output Schema | Field | Type | Description | | ------------------ | -------------- | ----------------------------------------------------------------------- | | `success` | boolean | Whether the operation completed successfully | | `totalRecords` | integer | Total number of records found in the file | | `processedRecords` | integer | Number of records that were processed | | `createdRecords` | integer | Number of MData records successfully created | | `skippedRecords` | integer | Number of records that were skipped due to validation errors | | `errors` | array (string) | List of errors encountered during processing | | `warnings` | array (string) | List of warnings encountered during processing | | `fileInfo` | object | Information about the processed file (fileName, fileSize, lastModified) | | `data` | array (object) | Raw data records (only returned when mObjectId is not provided) | | `executionTime` | integer | Execution time in milliseconds | | `connectionId` | string (UUID) | The S3 connection ID that was used | | `mObjectId` | string (UUID) | The Object ID where data was stored (if provided) | ## Output Example ### Success Response with Data Storage ```json { "success": true, "totalRecords": 5000, "processedRecords": 5000, "createdRecords": 4950, "skippedRecords": 50, "errors": [], "warnings": [ "50 records skipped due to validation errors" ], "fileInfo": { "fileName": "sales_data.csv", "fileSize": 1048576, "lastModified": "2024-01-15T10:30:00" }, "executionTime": 2500, "connectionId": "s3-connection-uuid", "mObjectId": "sales-mobject-uuid" } ``` ### Query-Only Response ```json { "success": true, "totalRecords": 100, "processedRecords": 100, "createdRecords": 0, "skippedRecords": 0, "errors": [], "warnings": [], "fileInfo": { "fileName": "data.csv", "fileSize": 51200, "lastModified": "2024-01-15T10:30:00" }, "data": [ { "column1": "value1", "column2": "value2" } ], "executionTime": 500, "connectionId": "s3-connection-uuid" } ``` ## How It Works The function performs the following steps: 1. **Validate Input**: Validates file path, format, parsing parameters, and S3 connection 2. **Establish S3 Connection**: Connects to S3 using the provided connection ID and validates file accessibility 3. **Parse File**: Parses file content based on file type: * **CSV**: Custom delimiters, headers, row skipping, automatic type detection * **JSON**: Array and object parsing with max record limits * **TXT**: Text file parsing with delimiter support 4. **Transform Data**: Applies field mappings if provided and transforms data types 5. **Process Data**: * If `mobjectId` is provided: Creates MData records in batches * If `mobjectId` is not provided: Returns raw data without storage 6. **Return Result**: Returns processing statistics, file metadata, and optional data ## Supported File Formats ### CSV Files * Custom delimiters (comma, semicolon, tab, etc.) * Header row detection * Row skipping * Automatic type detection (numbers, booleans, dates, strings) * Custom date pattern parsing ### JSON Files * JSON array parsing (array of objects) * Single JSON object parsing * Max record limits * Nested object support ### TXT Files * Delimiter-based parsing * Encoding support ## Use Cases ### Bulk Data Import from S3 Import large CSV files from S3 into Objects: ```json { "connectionId": "s3-connection-uuid", "filePath": "imports/products.csv", "fileType": "CSV", "mobjectId": "product-mobject-uuid", "batchSize": 5000, "skipRows": 1, "delimiter": ",", "hasHeader": true } ``` ### Data Transformation with Field Mappings Transform and map fields during import: ```json { "connectionId": "s3-connection-uuid", "filePath": "data/customers.json", "fileType": "JSON", "mobjectId": "customer-mobject-uuid", "batchSize": 1000, "fieldMappings": { "first_name": "firstName", "last_name": "lastName", "email_address": "email" } } ``` ### Workflow Data Processing Process S3 files in workflows: ``` Start → S3DataLoad → TransformData → InsertMData → End ``` ### Query-Only File Reading Read and process S3 files without storage: ```json { "connectionId": "s3-connection-uuid", "filePath": "reports/summary.csv", "fileType": "CSV", "batchSize": 1000, "maxRecords": 1000 } ``` ## Notes * **S3 Connection**: Requires a configured S3 connection with proper credentials and bucket access * **File Path**: S3 key/path must be valid and accessible with the provided connection credentials * **Batch Processing**: Large files are processed in batches to optimize memory usage * **Type Detection**: Automatic type detection for numbers, booleans, dates, and strings * **Field Mappings**: Use field mappings to transform source field names to target Object field names * **Error Handling**: Validation errors skip individual records but continue processing * **Security**: File path validation prevents directory traversal attacks * **Encoding**: Supports multiple character encodings for international file support * **Date Parsing**: Custom date patterns can be specified for date field parsing ## Related Functions * [Load Data from Database](/mbrix/workflows/functions/system-functions/db-data-load) - Execute SQL queries against database connections and load results into Objects * [Parse CSV](/mbrix/workflows/functions/system-functions/parse-csv) - Parse CSV files with automatic field resolution * [Insert MData](/mbrix/workflows/functions/crud-operations/insert-mdata) - Create new MData records --- # Statement Parser URL: /mbrix/workflows/functions/system-functions/statement-parser Parse bank statements from various formats including PDF, XML, EDI and Excel *** title: Statement Parser description: Parse bank statements from various formats including PDF, XML, EDI and Excel ----------------------------------------------------------------------------------------- # Statement Parser Parse bank statements from various file formats including PDF, XML, EDI, and Excel. The function automatically detects file type, selects the appropriate parser, and extracts account information, transactions, and fee details. **Technical Name**: `ParseStatementFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `ef13a8f3-8388-47b1-9354-6be62f241964` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------------- | --------------------------------------------------------------- | | `fileId` | string (UUID) | UUID of the uploaded file to parse (must exist in file storage) | ### Optional Parameters | Parameter | Type | Description | | ------------------ | ------------- | ------------------------------------------------------ | | `bankName` | string | Optional name of the bank for statement identification | | `parserName` | string | Optional specific parser to use | | `parserPatternId` | string (UUID) | Optional UUID of a parser pattern configuration to use | | `usePatternParser` | boolean | Optional flag to force use of pattern-based parser | ## Input Example ### Basic Parsing ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d" } ``` ### With Bank Name ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "bankName": "Chase Bank" } ``` ### Using Specific Parser ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "parserName": "chaseBankParser" } ``` ### Using Pattern-Based Parser ```json { "fileId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "parserPatternId": "pattern-uuid-here", "usePatternParser": true } ``` ## Supported File Types * **PDF** (`application/pdf`) - Bank statement PDFs * **XML** (`application/xml`, `text/xml`) - CAMT.053, ISO 20022 formats * **EDI** (`.edi`) - Electronic Data Interchange formats * **Excel** (`.xlsx`, `.xls`) - Spreadsheet-based statements ## Output Schema | Field | Type | Description | | ------------------- | ------ | --------------------------------------------- | | `statementGroup` | object | Group information about the parsed statement | | `statementAccounts` | array | Account information from the parsed statement | | `statementServices` | array | Service information from the parsed statement | The output structure contains: * **Statement Metadata**: Bank name, account numbers, statement period, currency * **Account Balances**: Opening/closing balances, ledger balances * **Activity Details**: Transactions, service charges, fees ## Output Example ```json { "statementGroup": { "bankName": "Chase Bank", "fileName": "statement_2024_01.pdf", "statementFrom": "2024-01-01", "statementTo": "2024-01-31" }, "statementAccounts": [ { "accountNumber": "1234567890", "accountType": "DETAIL", "openingBalance": 10000.00, "closingBalance": 9500.00, "currency": "USD" } ], "statementServices": [ { "serviceDescription": "Wire Transfer", "unitPrice": 25.00, "volume": 5, "totalCharges": 125.00, "accountNumber": "1234567890" } ] } ``` ## How It Works 1. **File Type Detection**: Automatically detects file type (PDF, XML, EDI, Excel) 2. **Parser Selection**: * If `parserName` provided: Uses specified parser * If `parserPatternId` or `usePatternParser=true`: Uses pattern-based parser * If `bankName` provided: Attempts to find bank-specific parser or pattern * Otherwise: Tries all available parsers until one succeeds 3. **Parsing**: Extracts statement data based on file format 4. **Data Enrichment**: Resolves bank metadata, validates account numbers, checks for duplicates 5. **Output**: Returns structured statement data ## Use Cases ### Parse Uploaded Statement Parse a bank statement uploaded by a user: ```json { "fileId": "{{context.uploadedFileId}}", "bankName": "Wells Fargo" } ``` ### Process Multiple Statements Parse multiple statements in a workflow: ``` Start → UploadFile → StatementParser → ProcessFees → End ``` ### Use Pattern-Based Parsing Parse statements using a custom parser pattern: ```json { "fileId": "file-uuid", "parserPatternId": "custom-pattern-uuid", "usePatternParser": true } ``` ## Parser Selection Strategy The function uses the following strategy to select a parser: 1. **Explicit Parser**: If `parserName` is provided, uses that parser 2. **Pattern Parser**: If `parserPatternId` or `usePatternParser=true`, uses pattern-based parser 3. **Bank-Specific**: If `bankName` is provided, searches for bank-specific parser or pattern 4. **Fallback**: Tries all available parsers sequentially until one succeeds 5. **Generic Parser**: Falls back to generic PDF parser if all specific parsers fail ## Related Functions * [Statement Processor](/mbrix/workflows/functions/system-functions/statement-processor) - Process parsed statements by mapping categories, forex rates, and other data * [Parse Bank Statement](/mbrix/workflows/functions/system-functions/parse-statement) - Similar function with additional currency and country parameters * [Parse CSV/Excel File](/mbrix/workflows/functions/system-functions/parse-csv) - Parse CSV and Excel files for general data * [ECR Analysis](/mbrix/workflows/functions/system-functions/ecr-analysis) - Analyze ECR data from parsed statements --- # Statement Processor URL: /mbrix/workflows/functions/system-functions/statement-processor Process bank statements by mapping categories, forex rates, and other data. Enriches parsed statement data with category mappings, currency conversions, and interbank rates *** title: Statement Processor description: Process bank statements by mapping categories, forex rates, and other data. Enriches parsed statement data with category mappings, currency conversions, and interbank rates ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- # Statement Processor Process bank statements by mapping categories, forex rates, and interbank rates. This function enriches parsed statement data with category mappings, performs currency conversions, maps price book details, and calculates reporting values. It processes statements in batches and updates the statement group status. **Technical Name**: `StatementProcessor` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `ef13a8f3-8388-47b1-9354-6be62f241965` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ------------------ | ------------- | ----------------------------------------------------------------- | | `statementGroupId` | string (UUID) | UUID of the statement group to process (must exist and be parsed) | ## Input Example ```json { "statementGroupId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d" } ``` ## Output Schema | Field | Type | Description | | ----------------- | ------- | --------------------------------------------------------------------- | | `status` | string | Processing status: `PROCESSING`, `PROCESSED`, `DUPLICATE`, or `ERROR` | | `comments` | string | Comments or error message (if status is ERROR or DUPLICATE) | | `duplicate` | boolean | Whether the statement was detected as a duplicate | | Additional fields | object | All statement group fields | ## Output Example ### Success Response ```json { "status": "PROCESSED", "duplicate": false, "bankName": "Chase Bank", "fileName": "statement_2024_01.pdf", "statementFrom": "2024-01-01", "statementTo": "2024-01-31" } ``` ### Duplicate Response ```json { "status": "DUPLICATE", "duplicate": true, "comments": "Duplicate file detected, processing aborted." } ``` ### Error Response ```json { "status": "ERROR", "comments": "Error processing statement: Category mapping not found" } ``` ## How It Works The function performs the following steps: 1. **Load Statement Group**: Retrieves the statement group by ID and sets status to `PROCESSING` 2. **Check for Duplicates**: If duplicate flag is set, aborts processing and sets status to `DUPLICATE` 3. **Initialize Caches**: Loads category mappings, forex rates, and interbank rates into memory caches 4. **Process Statement Services**: For each statement service in the group: * **Validates Dates**: Ensures fromDate and toDate are valid * **Finds Interbank Rate**: Looks up interbank rate based on currency, country, and date range * **Finds Category Mapping**: Maps bank service description to category using AFP codes and bank ID * **Finds Forex Rate**: Looks up forex rate for currency conversion to reporting currency * **Maps Price Book**: If category mapping found, maps price book details * **Calculates Reporting Values**: Converts charges to reporting currency * **Updates Status**: Sets service status to `IMPORTED` if all mappings found, otherwise `UNMAPPED` 5. **Updates Statement Account**: Calculates reporting balances, NII (Net Interest Income), and wallet balance 6. **Final Status**: Sets statement group status to `PROCESSED`, `DUPLICATE`, or `ERROR` ## Processing Details ### Category Mapping Maps bank service descriptions to categories using: * AFP Category Code * AFP Service Code * Bank Service Description * Bank ID ### Forex Rate Conversion Converts service charges to reporting currency: * Looks up forex rate for currency pair and date range * Calculates `totalChargesReporting = totalCharges × forexRate` * Updates statement account reporting values ### Interbank Rate Finds interbank rate for: * Currency * Country * Date range (fromDate to toDate) ### Price Book Mapping If category mapping includes price book service description: * Finds active price book for the bank * Matches price book details by country, currency, and service description * Calculates agreed price (with forex conversion if needed) ### NII Calculation Calculates Net Interest Income: ``` NII = ((Balance × ForexRate) × ((InterbankRate/100) - (InterestRate/100))) / 12 ``` ### Service Status * **IMPORTED**: All mappings found (category, forex, interbank rate) * **UNMAPPED**: One or more mappings missing ## Use Cases ### Process Parsed Statement Process a statement after parsing: ```json { "statementGroupId": "{{parsedStatement.statementGroupId}}" } ``` ### Complete Statement Workflow Full statement processing workflow: ``` Start → UploadFile → ParseStatement → StatementProcessor → AnalyzeFees → End ``` ### Batch Processing The function processes statement services in batches of 50 for optimal performance. ## Status Values | Status | Description | | ------------ | ------------------------------------------------------- | | `PROCESSING` | Statement is currently being processed | | `PROCESSED` | Statement processing completed successfully | | `DUPLICATE` | Statement was detected as duplicate, processing aborted | | `ERROR` | An error occurred during processing | ## Notes * **Prerequisites**: Statement must be parsed first using ParseStatement or StatementParser * **Batch Processing**: Processes statement services in batches of 50 for performance * **Caching**: Uses in-memory caches for category mappings, forex rates, and interbank rates * **Currency Conversion**: Converts to reporting currency from tenant settings * **Date Validation**: Validates that fromDate is not after toDate * **Rate Validation**: Validates rates are within acceptable range (0.000001 to 1000000) * **Duplicate Detection**: Checks duplicate flag before processing * **Error Handling**: Continues processing other services if one fails ## Related Functions * [Parse Bank Statement](/mbrix/workflows/functions/system-functions/parse-statement) - Parse bank statements from files * [Statement Parser](/mbrix/workflows/functions/system-functions/statement-parser) - Alternative parser function * [ECR Analysis](/mbrix/workflows/functions/system-functions/ecr-analysis) - Analyze ECR data from processed statements --- # Run Sub-Workflow URL: /mbrix/workflows/functions/system-functions/subflow Run another workflow from within this workflow *** title: Run Sub-Workflow description: Run another workflow from within this workflow ----------------------------------------------------------- # Run Sub-Workflow Run another workflow (called a sub-workflow) from within your current workflow. This lets you reuse common workflows and keep your main workflow organized and easy to understand. **Technical Name**: `SubFlowFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `8e9b1ea8-5d9a-4f2b-a8f6-8f6b5d9a1eb0` ## Input Schema ### Required Parameters | Parameter | Type | Description | | --------- | ------------- | ---------------------------------------------- | | `mflowId` | string (uuid) | ID of the subflow to execute | | `data` | object | Input data to pass to the subflow's Start node | ## Input Example ```json { "mflowId": "a1b2c3d4-e5f6-7890-abcd-ef0123456789", "data": { "customerId": "cust-123", "orderId": "ord-456", "action": "process" } } ``` ## Output Schema | Field | Type | Description | | ------ | ------------- | --------------------------------------- | | `id` | string (uuid) | ID returned by the subflow's End node | | `data` | object | Data returned by the subflow's End node | ## Use Cases ### Modular Workflow Design Break complex workflows into reusable subflows: ``` Main Flow: Start → ValidateInput → SubFlow(ProcessOrder) → SubFlow(SendNotification) → End ProcessOrder Subflow: Start → CalculateTotals → InsertOrder → UpdateInventory → End ``` ### Reusable Business Logic Create reusable subflows for common operations: ```json { "mflowId": "validate-customer-subflow-id", "data": { "customerId": "${start.output.customerId}", "validationType": "full" } } ``` ## Best Practices 1. **Single Responsibility**: Each subflow should have one clear purpose 2. **Clear Contracts**: Define explicit input/output schemas 3. **Error Handling**: Handle errors at appropriate levels 4. **Documentation**: Document subflow purpose and parameters 5. **Versioning**: Maintain subflow versions for backward compatibility ## Benefits * **Modularity**: Break complex workflows into manageable pieces * **Reusability**: Use the same subflow in multiple parent flows * **Maintainability**: Update logic in one place * **Testing**: Test components independently ## Related Functions * [ForEach](/mbrix/workflows/functions/system-functions/foreach) - Execute flow for each array item * [UserAction](/mbrix/workflows/functions/user-interactions/user-action) - Pause for user interaction --- # Trigger Agent URL: /mbrix/workflows/functions/system-functions/trigger-agent Trigger an AI agent chat with templated user queries. Supports variable substitution in the format {variableName} *** title: Trigger Agent description: Trigger an AI agent chat with templated user queries. Supports variable substitution in the format {variableName} ------------------------------------------------------------------------------------------------------------------------------ # Trigger Agent Trigger an AI agent chat with templated user queries. This function allows you to programmatically interact with AI agents using template strings with variable substitution. The function processes template variables, triggers the agent conversation, and returns the agent's response. **Technical Name**: `TriggerAgentFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `8a2e4c9f-1b3d-4f5a-8e9c-2d6f8a1b4e7c` ## Input Schema ### Required Parameters | Parameter | Type | Description | | ----------- | ------------- | ------------------------------------------------------------------------------------------------------------------ | | `agentUUID` | string (UUID) | UUID of the AI agent to trigger | | `userQuery` | string | Template string with variables in `{variable}` format. Example: `'Create order for {userId} with status {status}'` | ### Optional Parameters | Parameter | Type | Description | | ------------------ | ------------- | -------------------------------------------------------------------------------------------------------------- | | `fileUUID` | string (UUID) | UUID of the attached file to include in the chat | | `variableMappings` | object | Map of variable names to their replacement values. Keys should match variable names used in userQuery template | ## Input Example ### Basic Query Without Variables ```json { "agentUUID": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "userQuery": "Analyze the sales data for Q1 2024" } ``` ### Query With Template Variables ```json { "agentUUID": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "userQuery": "Create order for {userId} with status {status} and amount {amount}", "variableMappings": { "userId": "user-123", "status": "pending", "amount": "99.99" } } ``` ### Query With File Attachment ```json { "agentUUID": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "userQuery": "Analyze this document: {documentType}", "fileUUID": "file-uuid-here", "variableMappings": { "documentType": "invoice" } } ``` ## Output Schema | Field | Type | Description | | ---------------- | ------------- | ---------------------------------------------------------------------------- | | `success` | boolean | Whether the agent trigger operation completed successfully | | `conversationId` | string (UUID) | Generated conversation ID for the chat session | | `runId` | string (UUID) | Generated run ID for this specific chat execution | | `agentId` | string (UUID) | ID of the triggered agent | | `agentName` | string | Name of the triggered agent | | `processedQuery` | string | The final user query after template variable processing | | `agentResponse` | string | The agent's string response content (only supports StringAgentOutput agents) | | `errorMessage` | string | Error message if the operation failed (only present when success is false) | ## Output Example ### Success Response ```json { "success": true, "conversationId": "c9d1e6f4-5g7b-6c3d-0e1f-9g8c7d6e5f4g", "runId": "b8c0d5e3-4f6a-5b2c-9d0e-8f7b6c5d4e3f", "agentId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "agentName": "Sales Analysis Agent", "processedQuery": "Create order for user-123 with status pending and amount 99.99", "agentResponse": "Order created successfully. Order ID: ORD-12345" } ``` ### Error Response ```json { "success": false, "errorMessage": "Agent not found with ID: invalid-uuid" } ``` ## How It Works The function performs the following steps: 1. **Parse Input**: Validates and parses input parameters 2. **Process Template**: Uses Spring AI PromptTemplate to replace `{variable}` placeholders with values from `variableMappings` 3. **Load Agent**: Retrieves the AI agent by UUID from the repository 4. **Generate IDs**: Creates a unique run ID for this execution 5. **Create Chat Request**: Builds an AI chat request with the processed query 6. **Execute Agent**: Triggers the agent chat in a separate thread to preserve execution context 7. **Extract Response**: Extracts string content from the agent's response (only supports StringAgentOutput) 8. **Return Result**: Returns success status, agent information, processed query, and response ## Template Variable Processing The function uses Spring AI PromptTemplate for variable substitution: * **Format**: Variables are enclosed in curly braces: `{variableName}` * **Substitution**: Values from `variableMappings` replace the variables * **Missing Variables**: If a variable in the template has no mapping, it remains as-is * **No Mappings**: If `variableMappings` is null or empty, the query is returned as-is ### Template Examples ```json { "userQuery": "Hello {name}, your order {orderId} is {status}", "variableMappings": { "name": "John", "orderId": "ORD-123", "status": "shipped" } } ``` Result: `"Hello John, your order ORD-123 is shipped"` ## Use Cases ### Dynamic Agent Queries Trigger agents with dynamic data from workflows: ```json { "agentUUID": "{{workflow.agentId}}", "userQuery": "Analyze customer {customerId} transaction history", "variableMappings": { "customerId": "{{workflow.customerId}}" } } ``` ### Workflow Automation Use AI agents in automated workflows: ``` Start → FetchMData → TriggerAgent → ProcessResponse → End ``` ### Document Analysis Send documents to agents for analysis: ```json { "agentUUID": "document-analysis-agent-uuid", "userQuery": "Analyze this {documentType} and extract key information", "fileUUID": "{{uploadedFileId}}", "variableMappings": { "documentType": "invoice" } } ``` ## Notes * **Agent Type**: Only supports agents with `StringAgentOutput` response type * **Template Processing**: Uses Spring AI PromptTemplate for variable substitution * **Thread Isolation**: Executes agent chat in a separate thread to preserve workflow execution context * **File Attachments**: Optional file can be attached to the chat request * **Error Handling**: Returns error message in `errorMessage` field if operation fails * **Agent Validation**: Validates that the agent exists before processing * **Variable Mappings**: All values in `variableMappings` are treated as strings ## Limitations * **Output Type**: Only supports `StringAgentOutput` agents. Other output types will throw an exception * **Synchronous Execution**: The function waits for the agent response before returning * **Template Variables**: Variables must match exactly (case-sensitive) between template and mappings ## Related Functions * [Call External API](/mbrix/workflows/functions/external-api/call-external-api) - Call external APIs and services * [Run JavaScript Code](/mbrix/workflows/functions/system-functions/javascript) - Execute custom JavaScript logic * [Calculate Expression](/mbrix/workflows/functions/system-functions/expression) - Perform calculations and formulas --- # Update Execution Secondary Status URL: /mbrix/workflows/functions/system-functions/update-execution-secondary-status Update the secondary status of the current MFlow execution with custom text *** title: Update Execution Secondary Status description: Update the secondary status of the current MFlow execution with custom text ---------------------------------------------------------------------------------------- # Update Execution Secondary Status Update the secondary status of the current MFlow execution with custom text. This function allows you to set a custom status message for tracking execution progress or state. The execution ID is automatically retrieved from the current execution context. **Technical Name**: `UpdateExecutionSecondaryStatusFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: System Functions * **Function ID**: `8e5f2c1d-4b9a-4f8e-a1c6-7d3e9f2a8b4c` ## Input Schema ### Optional Parameters | Parameter | Type | Description | | ----------------- | ------ | ------------------------------------------------------------------------------ | | `secondaryStatus` | string | Custom secondary status text to set (any string value, or null/empty to clear) | ## Input Example ### Set Secondary Status ```json { "secondaryStatus": "Processing payment batch" } ``` ### Clear Secondary Status ```json { "secondaryStatus": "" } ``` Or: ```json { "secondaryStatus": null } ``` ## Output Schema | Field | Type | Description | | ----------------- | ------------- | ------------------------------------------------------ | | `executionId` | string (UUID) | The current execution ID that was updated | | `secondaryStatus` | string | The secondary status that was set (or null if cleared) | | `message` | string | Success message | ## Output Example ### Success Response ```json { "executionId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "secondaryStatus": "Processing payment batch", "message": "Secondary status updated successfully" } ``` ### Clear Status Response ```json { "executionId": "a7b9c4d2-3e5f-4a1b-9c8d-7e6f5a4b3c2d", "secondaryStatus": null, "message": "Secondary status updated successfully" } ``` ## Use Cases ### Track Execution Progress Update status during long-running workflows: ```json { "secondaryStatus": "Step 3 of 10: Validating customer data" } ``` ### Update Status Based on Conditions Use in conditional branches to track workflow state: ```json { "secondaryStatus": "{{#if error}}Error occurred: {{errorMessage}}{{else}}Processing completed{{/if}}" } ``` ### Clear Status on Completion Reset status when workflow completes: ```json { "secondaryStatus": "" } ``` ## Notes * **Execution Context**: The function automatically uses the current execution ID from the MFlow execution context * **Status Format**: Secondary status accepts any string value - use it for custom tracking, progress indicators, or state messages * **Clearing Status**: Pass null, empty string, or whitespace-only string to clear the secondary status * **Trimming**: Status text is automatically trimmed of leading/trailing whitespace * **Error Handling**: Throws an error if no execution ID is available in the current context ## Related Functions * [Run Sub-Workflow](/mbrix/workflows/functions/system-functions/subflow) - Execute sub-workflows within a workflow --- # Send Email URL: /mbrix/workflows/functions/user-interactions/email-notification Send an email to one or more recipients *** title: Send Email description: Send an email to one or more recipients ---------------------------------------------------- # Send Email Send an email to specific people or to everyone with a certain role. You can use templates to personalize the email, attach files, and include your data in the message. **Technical Name**: `EmailNotificationFunc` ## Properties * **Execution Mode**: SYNC * **Type**: NATIVE * **Category**: User Interactions * **Function ID**: `5f9a1ea8-5d9a-4f2b-a8f6-8f6b5d9a1ea6` ## Input Schema ### Optional Parameters | Parameter | Type | Description | | --------------- | ------------- | ------------------------------------------------- | | `to` | string | Comma-separated list of recipient emails | | `roleId` | string (uuid) | Role ID to send email to all users with this role | | `mobjectId` | string (uuid) | Object ID for resolving reference/picklist fields | | `mdataId` | string (uuid) | MData record ID for field resolution | | `cc` | string | Comma-separated list of CC email addresses | | `bcc` | string | Comma-separated list of BCC email addresses | | `body` | string | Email body content | | `replyTo` | string | Reply-to email address | | `attachmentIds` | array | Array of attachment file IDs | | `templateId` | string (uuid) | ID of the template to use for email content | | `dataObject` | object | Object for template resolution | ## Input Example ### Simple Email ```json { "to": "customer@example.com", "body": "Your order has been processed successfully.", "cc": "manager@example.com", "replyTo": "support@example.com" } ``` ### Template-Based Email ```json { "roleId": "customer-role-uuid", "templateId": "order-confirmation-template-uuid", "dataObject": { "orderNumber": "ORD-12345", "totalAmount": "$250.00", "customerName": "John Doe" } } ``` ## Output Schema | Field | Type | Description | | ----------- | ------------------ | -------------------------------------------- | | `success` | boolean | Indicates if the email was sent successfully | | `timestamp` | string (date-time) | Timestamp when the email was sent | | `messageId` | string | Message identifier or status message | ## Email Templates Templates support variable substitution using `{{variable}}` syntax: ```html

Dear {{customerName}},

Your order {{orderNumber}} has been confirmed.

Total Amount: {{totalAmount}}

``` ## Use Cases ### Order Confirmation Send confirmation emails after order placement: ``` Start → InsertOrder → EmailNotification(OrderConfirmation) → End ``` ### Approval Notifications Notify approvers of pending tasks: ```json { "roleId": "approver-role-uuid", "templateId": "approval-request-template-uuid", "dataObject": { "requestType": "Purchase Order", "amount": "$5,000", "requester": "John Doe" } } ``` ## Best Practices 1. **Use Templates**: Create reusable templates for consistency 2. **Personalization**: Include recipient-specific information 3. **Test Emails**: Always test templates before production use 4. **Error Handling**: Check success status and handle failures 5. **Mobile Responsive**: Design templates for mobile devices ## Related Functions * [UserAction](/mbrix/workflows/functions/user-interactions/user-action) - Combine with user tasks * [HTMLToPDF](/mbrix/workflows/functions/system-functions/html-to-pdf) - Generate PDF attachments ## Limitations * Maximum recipients per email: 100 * Maximum attachment size: 10MB total * Maximum email size: 15MB * Rate limit: 100 emails per minute --- # Assign Task URL: /mbrix/workflows/functions/user-interactions/user-action Create a task for someone to complete *** title: Assign Task description: Create a task for someone to complete -------------------------------------------------- # Assign Task Create a task and assign it to a specific person or role. The workflow will wait for them to complete the task before continuing. You can send email notifications to let them know about the task. **Technical Name**: `UserActionFunc` ## Properties * **Execution Mode**: ASYNC * **Type**: NATIVE * **Category**: User Interactions * **Function ID**: `dc2763db-b462-4362-9ba5-015fe95d9981` ## Input Schema ### Optional Parameters | Parameter | Type | Description | | ------------- | ------------- | ------------------------------------------ | | `label` | string | Label of the step | | `description` | string | Description of the step | | `roleId` | string (uuid) | Role ID for the task | | `userId` | string (uuid) | User ID for the task | | `templateId` | string (uuid) | Email template ID for notification | | `flowData` | object | Flow data for the user action | | `dataObject` | object | Token mapping for email template rendering | ## Input Example ```json { "label": "Review Customer Application", "description": "Please review the customer application and provide your decision", "roleId": "reviewer-role-uuid", "templateId": "review-request-template-uuid", "flowData": { "applicationId": "app-123", "customerName": "John Doe", "applicationType": "Premium Account" }, "dataObject": { "applicationNumber": "APP-2024-001", "submittedDate": "2024-01-15" } } ``` ## Output Schema Returns data based on user's action: ```json { "action": "approved", "comments": "Application looks good", "completedBy": "user@example.com", "completedAt": "2024-01-15T10:30:00Z", "additionalData": {...} } ``` ## Use Cases ### Manual Review Process Pause workflow for manual review: ``` Start → FetchApplication → UserAction(Review) → ProcessDecision → End ``` ### Data Collection Collect additional information from user: ```json { "label": "Provide Additional Information", "description": "Please fill in the missing customer details", "userId": "specific-user-uuid", "flowData": { "customerId": "cust-123", "requiredFields": ["address", "phone", "taxId"] } } ``` ### Multi-Step Approval Combine with other nodes for multi-step processes: ``` Start → InsertMData → UserAction(ManagerReview) → UserAction(DirectorApproval) → FinalizeProcess → End ``` ## How It Works 1. **Workflow Pauses**: Execution stops at the UserAction node 2. **Task Created**: A task is assigned to the specified user or role 3. **Notification Sent**: Email notification sent if template provided 4. **User Completes**: User accesses their task inbox and completes the action 5. **Workflow Resumes**: Execution continues with user's response ## Task Assignment ### Assign to Specific User ```json { "userId": "user-uuid", "label": "Your approval is needed" } ``` ### Assign to Role ```json { "roleId": "approvers-role-uuid", "label": "Approval required" } ``` Any user with the specified role can complete the task. ## Best Practices 1. **Clear Instructions**: Provide clear label and description 2. **Send Notifications**: Always use email templates to notify users 3. **Set Deadlines**: Configure timeout for time-sensitive tasks 4. **Track Progress**: Use workflow tracker to monitor pending tasks 5. **Handle Timeouts**: Plan for scenarios where users don't respond ## Error Handling ### Timeout Configure timeout for tasks: ```json { "label": "Urgent Review", "timeout": 3600, // 1 hour in seconds "timeoutAction": "auto-reject" } ``` ### No Available Users When no users match the role: ```json { "error": "No users found with the specified role", "timestamp": "2024-01-15T10:30:00Z" } ``` ## Related Functions * [ApprovalAction](/mbrix/workflows/functions/system-functions/approval-action) - Specialized approval workflows * [EmailNotification](/mbrix/workflows/functions/user-interactions/email-notification) - Send notification emails * [SubFlow](/mbrix/workflows/functions/system-functions/subflow) - Break complex approval logic into subflows ## Workflow Patterns ### Sequential Approval ``` Start → UserAction(Level1) → UserAction(Level2) → UserAction(Level3) → End ``` ### Conditional Approval ``` Start → CheckAmount → (if > $10k) → UserAction(ManagerApproval) → End ``` ### Parallel Review ``` Start → Parallel(UserAction(Legal), UserAction(Finance), UserAction(Operations)) → AggregateDecisions → End ``` ## User Experience When a UserAction is triggered, users see: * Task in their inbox * Clear description and instructions * Relevant data and context * Action buttons (approve, reject, etc.) * Comment field for feedback * File upload for attachments ## Monitoring Track UserAction tasks: * View all pending tasks * See who is assigned * Monitor task age * Track completion time * Analyze bottlenecks