mirror of
https://github.com/simstudioai/sim.git
synced 2026-01-09 15:07:55 -05:00
fix(sockets): added throttling, refactor entire socket server, added tests (#534)
* refactor(kb): use chonkie locally (#475) * feat(parsers): text and markdown parsers (#473) * feat: text and markdown parsers * fix: don't readfile on buffer, convert buffer to string instead * fix(knowledge-wh): fixed authentication error on webhook trigger fix(knowledge-wh): fixed authentication error on webhook trigger * feat(tools): add huggingface tools/blcok (#472) * add hugging face tool * docs: add Hugging Face tool documentation * fix: format and lint Hugging Face integration files * docs: add manual intro section to Hugging Face documentation * feat: replace Record<string, any> with proper HuggingFaceRequestBody interface * accidental local files added * restore some docs * make layout full for model field * change huggingface logo * add manual content * fix lint --------- Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-MacBook-Air.local> * fix(knowledge-ux): fixed ux for knowledge base (#478) fix(knowledge-ux): fixed ux for knowledge base (#478) * fix(billing): bump better-auth version & fix existing subscription issue when adding seats (#484) * bump better-auth version & fix existing subscription issue Bwhen adding seats * ack PR comments * fix(env): added NEXT_PUBLIC_APP_URL to .env.example (#485) * feat(subworkflows): workflows as a block within workflows (#480) * feat(subworkflows) workflows in workflows * revert sync changes * working output vars * fix greptile comments * add cycle detection * add tests * working tests * works * fix formatting * fix input var handling * add images --------- Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-MacBook-Air.local> Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-Air.attlocal.net> * fix(kb): fixed kb race condition resulting in no chunks found (#487) * fix: added all blocks activeExecutionPath (#486) * refactor(chunker): replace chonkie with custom TextChunker (#479) * refactor(chunker): replace chonkie with custom TextChunker implementation and update document processing logic * chore: cleanup unimplemented types * fix: KB tests updated * fix(tab-sync): sync between tabs on change (#489) * fix(tab-sync): sync between tabs on change * refactor: optimize JSON.stringify operations that are redundant * fix(file-upload): upload presigned url to kb for file upload instead of the whole file, circumvents 4.5MB serverless func limit (#491) * feat(folders): folders to manage workflows (#490) * feat(subworkflows) workflows in workflows * revert sync changes * working output vars * fix greptile comments * add cycle detection * add tests * working tests * works * fix formatting * fix input var handling * fix(tab-sync): sync between tabs on change * feat(folders): folders to organize workflows * address comments * change schema types * fix lint error * fix typing error * fix race cond * delete unused files * improved UI * updated naming conventions * revert unrelated changes to db schema * fixed collapsed sidebar subfolders * add logs filters for folders --------- Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-MacBook-Air.local> Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-Air.attlocal.net> Co-authored-by: Waleed Latif <walif6@gmail.com> * revert tab sync * improvement(folders): added multi-select for moving folders (#493) * added multi-select for folders * allow drag into root * remove extraneous comments * instantly create worfklow on plus * styling improvements, fixed flicker * small improvement to dragover container * ack PR comments * fix(deployed-chat): made the chat mobile friendly (#494) * improvement(ui/ux): chat deploy (#496) * improvement(ui/ux): chat deploy experience * improvement(ui/ux): chat fontweight * feat(gmail): added option to access raw gmail from gmail polling service (#495) * added option to grab raw gmail from gmail polling service * safe json parse for function block execution to prevent vars in raw email from being resolved as sim studio vars * added tests * remove extraneous comments * fix(ui): fix the UI for folder deletion, huggingface icon, workflow block icon, standardized alert dialog (#498) * fixed folder delete UI * fixed UI for workflow block, huggingface, & added alert dialog for deleting folders * consistently style all alert dialogs * fix(reset-data): remove reset all data button from settings modal along with logic (#499) * fix(airtable): fixed airtable oauth token refresh, added tests (#502) * fixed airtable token refresh, added tests * added helpers for refreshOAuthToken function * feat(registration): disable registration + handle env booleans (#501) * feat: disable registration + handle env booleans * chore: removing pre-process because we need to use util * chore: format * feat(providers): added azure openai (#503) * added azure openai * fix request params being passed through agent block for azure * remove o1 from azure-openai models list * fix: add vscode settings to gitignore * feat(file-upload): generalized storage to support azure blob, enhanced error logging in kb, added xlsx parser (#506) * added blob storage option for azure, refactored storage client to be provider agnostic, tested kb & file upload and s3 is undisrupted, still have to test blob * updated CORS policy for blob, added azure blob-specific headers * remove extraneous comments * add file size limit and timeout * added some extra error handling in kb add documents * grouped envvars * ack PR comments * added sheetjs and xlsx parser * fix(folders): modified folder deletion to delete subfolders & workflows in it instead of moving to root (#508) * modified folder deletion to delete subfolders & workflows in it instead of moving to root * added additional testing utils * ack PR comments * feat: api response block and implementation * improvement(local-storage): remove use of local storage except for oauth and last active workspace id (#497) * remove local storage usage * remove migration for last active workspace id * Update apps/sim/app/w/[id]/components/workflow-block/components/sub-block/components/file-selector/components/jira-issue-selector.tsx Add fallback for required scopes Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> * add url builder util * fi * fix lint * lint * modify pre commit hook * fix oauth * get last active workspace working again * new workspace logic works * fetch locks * works now * remove empty useEffect * fix loading issue * skip empty workflow syncs * use isWorkspace in transition flag * add logging * add data initialized flag * fix lint * fix: build error by create a server-side utils * remove migration snapshots * reverse search for workspace based on workflow id * fix lint * improvement: loading check and animation * remove unused utils * remove console logs --------- Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-Air.attlocal.net> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> Co-authored-by: Emir Karabeg <emirkarabeg@berkeley.edu> Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@vikhyaths-air.lan> * feat(multi-select): simplified chat to always return readable stream, can select multiple outputs and get response streamed back in chat panel & deployed chat (#507) * improvement: all workflow executions return ReadableStream & use sse to support multiple streamed outputs in chats * fixed build * remove extraneous comments * general improvemetns * ack PR comments * fixed built * improvement(workflow-state): split workflow state into separate tables (#511) * new tables to track workflow state * fix lint * refactor into separate tables * fix typing * fix lint * add tests * fix lint * add correct foreign key constraint * add self ref * remove unused checks * fix types * fix type --------- Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-Air.attlocal.net> * feat(models): added new openai models, updated model pricing, added new groq model (#513) * fix(autocomplete): fixed extra closing tag on tag dropdown autocomplete (#514) * chore: enable input format again * fix: process the input made on api calls with proper extraction * feat: add json-object for ai generation for response block and others * chore: add documentation for response block * chore: rollback temp fix and uncomment original input handler * chore: add missing mock for response handler * chore: add missing mock * chore: greptile recommendations * added cost tracking for router & evaluator blocks, consolidated model information into a single file, hosted keys for evaluator & router, parallelized unit tests (#516) * fix(deployState): deploy not persisting bug (#518) * fix(undeploy-bug): fix deployment persistence failing bug * fix lint --------- Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-MacBook-Air.local> * fix decimal entry issues * remove unused files * fix(db): decimal position entry issues (#520) * fix decimal entry issues * remove unused files --------- Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-Air.attlocal.net> * fix lint * fix test * improvement(kb): added configurability for chunks, query across multiple knowledge bases (#512) * refactor: consolidate create modal file * fix: identify dead processes * fix: mark failed in DB after processing timeout * improvement: added overlap chunks and fixed modal UI * feat: multiselect logic * fix: biome changes for css ordering warn instead of error * improvement: create chunk ui * fix: removed unused schema columns * fix: removed references to deleted columns * improvement: sped up vector search time * feat: multi-kb search * add bulk endpoint to disable/delete multiple chunks * add bulk endpoint to disable/delete multiple chunks * fix: removed unused schema columns * fix: removed references to deleted columns * made endpoints for knowledge more RESTful, added tests * added batch operations for delete/enable/disable docs, alr have this for chunks * added migrations * added migrations --------- Co-authored-by: Waleed Latif <walif6@gmail.com> * fix(models): remove temp from models that don't support it * feat(sdk): added ts and python SDKs + docs (#524) * added ts & python sdk, renamed cli from simstudio to cli * added docs * ack PR comments * improvements * fixed issue where it goes to random workspace when you click reload fixed lint issue * feat: better response builder + doc update * fix(auth): added preview URLs to list of trusted origins (#525) * trusted origins * lint error * removed localhost * ran lint --------- Co-authored-by: Waleed Latif <walif6@gmail.com> * fix(sdk): remove dev script from SDK * PR: changes for migration * add changes on top of db migration changes * fix: allow removing single input field * improvement(permissions): workspace permissions improvements, added provider and reduced API calls by 85% (#530) * improved permissions UI & access patterns, show outstanding invites * added logger * added provider for workspace permissions, 85% reduction in API calls to get user permissions and improved performance for invitations * ack PR comments * cleanup * fix disabled tooltips * improvement(tests): parallelized tests and build fixes (#531) * added provider for workspace permissions, 85% reduction in API calls to get user permissions and improved performance for invitations * parallelized more tests, fixed test warnings * removed waitlist verification route, use more utils in tests * fixed build * ack PR comments * fix * fix(kb): reduced params in kb block, added advanced mode to starter block, updated docs * feat(realtime): sockets + normalized tables + deprecate sync (#523) * feat: implement real-time collaborative workflow editing with Socket.IO - Add Socket.IO server with room-based architecture for workflow collaboration - Implement socket context for client-side real-time communication - Add collaborative workflow hook for synchronized state management - Update CSP to allow socket connections to localhost:3002 - Add fallback authentication for testing collaborative features - Enable real-time broadcasting of workflow operations between tabs - Support multi-user editing of blocks, edges, and workflow state Key components: - socket-server/: Complete Socket.IO server with authentication and room management - contexts/socket-context.tsx: Client-side socket connection and state management - hooks/use-collaborative-workflow.ts: Hook for collaborative workflow operations - Workflow store integration for real-time state synchronization Status: Basic collaborative features working, authentication bypass enabled for testing * feat: complete collaborative subblock editing implementation ✅ All collaborative features now working perfectly: - Real-time block movement and positioning - Real-time subblock value editing (text fields, inputs) - Real-time edge operations and parent updates - Multi-user workflow rooms with proper broadcasting - Socket.IO server with room-based architecture - Permission bypass system for testing 🔧 Technical improvements: - Modified useSubBlockValue hook to use collaborative event system - All subblock setValue calls now dispatch 'update-subblock-value' events - Collaborative workflow hook handles all real-time operations - Socket server processes and persists all operations to database - Clean separation between local and collaborative state management 🧪 Tested and verified: - Multiple browser tabs with different fallback users - Block dragging and positioning updates in real-time - Subblock text editing reflects immediately across tabs - Workflow room management and user presence - Database persistence of all collaborative operations Status: Full collaborative workflow editing working with fallback authentication * feat: implement proper authentication for collaborative Socket.IO server ✅ **Authentication System Complete**: - Removed all fallback authentication code and bypasses - Socket server now requires valid Better Auth session cookies - Proper session validation using auth.api.getSession() - Authentication errors properly handled and logged - User info extracted from session: userId, userName, email, organizationId 🔧 **Technical Implementation**: - Updated CSP to allow WebSocket connections (ws://localhost:3002) - Socket authentication middleware validates session tokens - Proper error handling for missing/invalid sessions - Permission system enforces workflow access controls - Clean separation between authenticated and unauthenticated states 🧪 **Testing Status**: - Socket server properly rejects unauthenticated connections - Authentication errors logged with clear messages - CSP updated to allow both HTTP and WebSocket protocols - Ready for testing with authenticated users Status: Production-ready collaborative authentication system * feat: complete authentication integration for collaborative Socket.IO system 🎉 **PRODUCTION-READY COLLABORATIVE SYSTEM** ✅ **Authentication Integration Complete**: - Fixed Socket.IO client to send credentials (withCredentials: true) - Updated server CORS to accept credentials with specific origin - Removed all fallback authentication bypasses - Proper Better Auth session validation working 🔧 **Technical Fixes**: - Socket client: Enable withCredentials for cookie transmission - Socket server: Accept credentials with origin 'http://localhost:3000' - Better Auth cookie utility integration for session parsing - Comprehensive authentication middleware with proper error handling 🧪 **Verified Working Features**: - ✅ Real user authentication (Vikhyath Mondreti authenticated) - ✅ Multi-user workflow rooms (2+ users in same workflow) - ✅ Permission system enforcing workflow access controls - ✅ Real-time subblock editing across browser tabs - ✅ Block movement and positioning updates - ✅ Automatic room cleanup and management - ✅ Database persistence of all collaborative operations 🚀 **Status**: Complete enterprise-grade collaborative workflow editing system - No more fallback users - production authentication - Multi-tab collaboration working perfectly - Secure access control with Better Auth integration - Real-time updates for all workflow operations * remove sync system and move to server side * fix lint * delete unused file * added socketio dep * fix subblock persistence bug * working deletion of workflows * fix lint * added railway * add debug logging for railway deployment * improve typing * fix lint * working subflow persistence * fix lint * working cascade deletion * fix lint * working subflow inside subflow * works * fix lint * prevent subflow in subflow * fix lint * add additional logs, add localhost as allowedOrigin * add additional logs, add localhost as allowedOrigin * fix type error * remove unused code * fix lint * fix tests * fix lint * fix build error * workign folder updates * fix typing issue * fix lint * fix typing issues * lib/ * fix tests * added old presence component back, updated to use one-time-token better auth plugin for socket server auth, tested * fix errors * fix bugs * add migration scripts to run * fix lint * fix deploy tests * fix lint * fix minor issues * fix lint * fix migration script * allow comma separateds id file input to migration script * fix lint * fixed * fix lint * fix fallback case * fix type errors * address greptile comments * fix lint * fix script to generate new block ids * fix lint --------- Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-Air.attlocal.net> Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@vikhyaths-air.lan> Co-authored-by: Waleed Latif <walif6@gmail.com> Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-MacBook-Air.local> * fix(sockets): updated CSP * remove unecessary logs * fix lint * added throttling, refactor entire socket server, added tests * improvements * remove self monitoring func, add block name event * working isWide, isAdvanced toggles with sockets * fix lint * fix duplicate key issue for user avatar * fix lint * fix user presence * working parallel badges / loop badges updates * working connection output persistence * fix lint * fix build errors * fix lint * logs removed * fix cascade var name update bug * works * fix lint * fix parallel blocks * fix placeholder * fix test * fixed tests --------- Co-authored-by: Aditya Tripathi <aditya@climactic.co> Co-authored-by: Adam Gough <77861281+aadamgough@users.noreply.github.com> Co-authored-by: Vikhyath Mondreti <vikhyathvikku@gmail.com> Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-MacBook-Air.local> Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@Vikhyaths-Air.attlocal.net> Co-authored-by: Emir Karabeg <emirkarabeg@berkeley.edu> Co-authored-by: Emir Karabeg <78010029+emir-karabeg@users.noreply.github.com> Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com> Co-authored-by: Vikhyath Mondreti <vikhyathmondreti@vikhyaths-air.lan> Co-authored-by: Ajit Kadaveru <ajit.kadaveru@berkeley.edu>
This commit is contained in:
@@ -263,3 +263,10 @@ export const SlackIcon = (props: SVGProps<SVGSVGElement>) => (
|
||||
</g>
|
||||
</svg>
|
||||
)
|
||||
|
||||
export const ResponseIcon = (props: SVGProps<SVGSVGElement>) => (
|
||||
<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24' fill='currentColor' {...props}>
|
||||
<path d='M20 18v-2a4 4 0 0 0-4-4H4' />
|
||||
<path d='m9 17-5-5 5-5' />
|
||||
</svg>
|
||||
)
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
import { AgentIcon, ApiIcon, ChartBarIcon, CodeIcon, ConditionalIcon, ConnectIcon } from '../icons'
|
||||
import {
|
||||
AgentIcon,
|
||||
ApiIcon,
|
||||
ChartBarIcon,
|
||||
CodeIcon,
|
||||
ConditionalIcon,
|
||||
ConnectIcon,
|
||||
ResponseIcon,
|
||||
} from '../icons'
|
||||
|
||||
// Custom Feature component specifically for BlockTypes to handle the 6-item layout
|
||||
const BlockFeature = ({
|
||||
@@ -127,6 +135,13 @@ export function BlockTypes() {
|
||||
icon: <ChartBarIcon className='h-6 w-6' />,
|
||||
href: '/blocks/evaluator',
|
||||
},
|
||||
{
|
||||
title: 'Response',
|
||||
description:
|
||||
'Send a response back to the caller with customizable data, status, and headers.',
|
||||
icon: <ResponseIcon className='h-6 w-6' />,
|
||||
href: '/blocks/response',
|
||||
},
|
||||
]
|
||||
|
||||
const totalItems = features.length
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
{
|
||||
"title": "Blocks",
|
||||
"pages": ["agent", "api", "condition", "function", "evaluator", "router"]
|
||||
"pages": ["agent", "api", "condition", "function", "evaluator", "router", "response", "workflow"]
|
||||
}
|
||||
|
||||
188
apps/docs/content/docs/blocks/response.mdx
Normal file
188
apps/docs/content/docs/blocks/response.mdx
Normal file
@@ -0,0 +1,188 @@
|
||||
---
|
||||
title: Response
|
||||
description: Send a structured response back to API calls
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
import { ThemeImage } from '@/components/ui/theme-image'
|
||||
|
||||
The Response block is the final component in API-enabled workflows that transforms your workflow's variables into a structured HTTP response. This block serves as the endpoint that returns data, status codes, and headers back to API callers.
|
||||
|
||||
<ThemeImage
|
||||
lightSrc="/static/light/response-light.png"
|
||||
darkSrc="/static/dark/response-dark.png"
|
||||
alt="Response Block"
|
||||
width={430}
|
||||
height={784}
|
||||
/>
|
||||
|
||||
<Callout type="info">
|
||||
Response blocks are terminal blocks - they mark the end of a workflow execution and cannot have further connections.
|
||||
</Callout>
|
||||
|
||||
## Overview
|
||||
|
||||
The Response block serves as the final output mechanism for API workflows, enabling you to:
|
||||
|
||||
<Steps>
|
||||
<Step>
|
||||
<strong>Return structured data</strong>: Transform workflow variables into JSON responses
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Set HTTP status codes</strong>: Control the response status (200, 400, 500, etc.)
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Configure headers</strong>: Add custom HTTP headers to the response
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Reference variables</strong>: Use workflow variables dynamically in the response
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Configuration Options
|
||||
|
||||
### Response Data
|
||||
|
||||
The response data is the main content that will be sent back to the API caller. This should be formatted as JSON and can include:
|
||||
|
||||
- Static values
|
||||
- Dynamic references to workflow variables using the `<variable.name>` syntax
|
||||
- Nested objects and arrays
|
||||
- Any valid JSON structure
|
||||
|
||||
### Status Code
|
||||
|
||||
Set the HTTP status code for the response. Common status codes include:
|
||||
|
||||
<Tabs items={['Success (2xx)', 'Client Error (4xx)', 'Server Error (5xx)']}>
|
||||
<Tab>
|
||||
<ul className="list-disc space-y-2 pl-6">
|
||||
<li><strong>200</strong>: OK - Standard success response</li>
|
||||
<li><strong>201</strong>: Created - Resource successfully created</li>
|
||||
<li><strong>204</strong>: No Content - Success with no response body</li>
|
||||
</ul>
|
||||
</Tab>
|
||||
<Tab>
|
||||
<ul className="list-disc space-y-2 pl-6">
|
||||
<li><strong>400</strong>: Bad Request - Invalid request parameters</li>
|
||||
<li><strong>401</strong>: Unauthorized - Authentication required</li>
|
||||
<li><strong>404</strong>: Not Found - Resource doesn't exist</li>
|
||||
<li><strong>422</strong>: Unprocessable Entity - Validation errors</li>
|
||||
</ul>
|
||||
</Tab>
|
||||
<Tab>
|
||||
<ul className="list-disc space-y-2 pl-6">
|
||||
<li><strong>500</strong>: Internal Server Error - Server-side error</li>
|
||||
<li><strong>502</strong>: Bad Gateway - External service error</li>
|
||||
<li><strong>503</strong>: Service Unavailable - Service temporarily down</li>
|
||||
</ul>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
<p className="mt-4 text-sm text-gray-600 dark:text-gray-400">
|
||||
Default status code is 200 if not specified.
|
||||
</p>
|
||||
|
||||
### Response Headers
|
||||
|
||||
Configure additional HTTP headers to include in the response.
|
||||
|
||||
Headers are configured as key-value pairs:
|
||||
|
||||
| Key | Value |
|
||||
|-----|-------|
|
||||
| Content-Type | application/json |
|
||||
| Cache-Control | no-cache |
|
||||
| X-API-Version | 1.0 |
|
||||
|
||||
## Inputs and Outputs
|
||||
|
||||
<Tabs items={['Inputs', 'Outputs']}>
|
||||
<Tab>
|
||||
<ul className="list-disc space-y-2 pl-6">
|
||||
<li>
|
||||
<strong>data</strong> (JSON, optional): The JSON data to send in the response body
|
||||
</li>
|
||||
<li>
|
||||
<strong>status</strong> (number, optional): HTTP status code (default: 200)
|
||||
</li>
|
||||
<li>
|
||||
<strong>headers</strong> (JSON, optional): Additional response headers
|
||||
</li>
|
||||
</ul>
|
||||
</Tab>
|
||||
<Tab>
|
||||
<ul className="list-disc space-y-2 pl-6">
|
||||
<li>
|
||||
<strong>response</strong>: Complete response object containing:
|
||||
<ul className="list-disc space-y-1 pl-6 mt-2">
|
||||
<li><strong>data</strong>: The response body data</li>
|
||||
<li><strong>status</strong>: HTTP status code</li>
|
||||
<li><strong>headers</strong>: Response headers</li>
|
||||
</ul>
|
||||
</li>
|
||||
</ul>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Variable References
|
||||
|
||||
Use the `<variable.name>` syntax to dynamically insert workflow variables into your response:
|
||||
|
||||
```json
|
||||
{
|
||||
"user": {
|
||||
"id": "<variable.userId>",
|
||||
"name": "<variable.userName>",
|
||||
"email": "<variable.userEmail>"
|
||||
},
|
||||
"query": "<variable.searchQuery>",
|
||||
"results": "<variable.searchResults>",
|
||||
"totalFound": "<variable.resultCount>",
|
||||
"processingTime": "<variable.executionTime>ms"
|
||||
}
|
||||
```
|
||||
|
||||
<Callout type="warning">
|
||||
Variable names are case-sensitive and must match exactly with the variables available in your workflow.
|
||||
</Callout>
|
||||
|
||||
## Example Usage
|
||||
|
||||
Here's an example of how a Response block might be configured for a user search API:
|
||||
|
||||
```yaml
|
||||
data: |
|
||||
{
|
||||
"success": true,
|
||||
"data": {
|
||||
"users": "<variable.searchResults>",
|
||||
"pagination": {
|
||||
"page": "<variable.currentPage>",
|
||||
"limit": "<variable.pageSize>",
|
||||
"total": "<variable.totalUsers>"
|
||||
}
|
||||
},
|
||||
"query": {
|
||||
"searchTerm": "<variable.searchTerm>",
|
||||
"filters": "<variable.appliedFilters>"
|
||||
},
|
||||
"timestamp": "<variable.timestamp>"
|
||||
}
|
||||
status: 200
|
||||
headers:
|
||||
- key: X-Total-Count
|
||||
value: <variable.totalUsers>
|
||||
- key: Cache-Control
|
||||
value: public, max-age=300
|
||||
```
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Use meaningful status codes**: Choose appropriate HTTP status codes that accurately reflect the outcome of the workflow
|
||||
- **Structure your responses consistently**: Maintain a consistent JSON structure across all your API endpoints for better developer experience
|
||||
- **Include relevant metadata**: Add timestamps and version information to help with debugging and monitoring
|
||||
- **Handle errors gracefully**: Use conditional logic in your workflow to set appropriate error responses with descriptive messages
|
||||
- **Validate variable references**: Ensure all referenced variables exist and contain the expected data types before the Response block executes
|
||||
231
apps/docs/content/docs/blocks/workflow.mdx
Normal file
231
apps/docs/content/docs/blocks/workflow.mdx
Normal file
@@ -0,0 +1,231 @@
|
||||
---
|
||||
title: Workflow
|
||||
description: Execute other workflows as reusable components within your current workflow
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
import { ThemeImage } from '@/components/ui/theme-image'
|
||||
|
||||
The Workflow block allows you to execute other workflows as reusable components within your current workflow. This powerful feature enables modular design, code reuse, and the creation of complex nested workflows that can be composed from smaller, focused workflows.
|
||||
|
||||
<ThemeImage
|
||||
lightSrc="/static/light/workflow-light.png"
|
||||
darkSrc="/static/dark/workflow-dark.png"
|
||||
alt="Workflow Block"
|
||||
width={300}
|
||||
height={175}
|
||||
/>
|
||||
|
||||
<Callout type="info">
|
||||
Workflow blocks enable modular design by allowing you to compose complex workflows from smaller, reusable components.
|
||||
</Callout>
|
||||
|
||||
## Overview
|
||||
|
||||
The Workflow block serves as a bridge between workflows, enabling you to:
|
||||
|
||||
<Steps>
|
||||
<Step>
|
||||
<strong>Reuse existing workflows</strong>: Execute previously created workflows as components within new workflows
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Create modular designs</strong>: Break down complex processes into smaller, manageable workflows
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Maintain separation of concerns</strong>: Keep different business logic isolated in separate workflows
|
||||
</Step>
|
||||
<Step>
|
||||
<strong>Enable team collaboration</strong>: Share and reuse workflows across different projects and team members
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## How It Works
|
||||
|
||||
The Workflow block:
|
||||
|
||||
1. Takes a reference to another workflow in your workspace
|
||||
2. Passes input data from the current workflow to the child workflow
|
||||
3. Executes the child workflow in an isolated context
|
||||
4. Returns the results back to the parent workflow for further processing
|
||||
|
||||
## Configuration Options
|
||||
|
||||
### Workflow Selection
|
||||
|
||||
Choose which workflow to execute from a dropdown list of available workflows in your workspace. The list includes:
|
||||
|
||||
- All workflows you have access to in the current workspace
|
||||
- Workflows shared with you by other team members
|
||||
- Both enabled and disabled workflows (though only enabled workflows can be executed)
|
||||
|
||||
### Input Data
|
||||
|
||||
Define the data to pass to the child workflow:
|
||||
|
||||
- **Single Variable Input**: Select a variable or block output to pass to the child workflow
|
||||
- **Variable References**: Use `<variable.name>` to reference workflow variables
|
||||
- **Block References**: Use `<blockName.response.field>` to reference outputs from previous blocks
|
||||
- **Automatic Mapping**: The selected data is automatically available as `start.response.input` in the child workflow
|
||||
- **Optional**: The input field is optional - child workflows can run without input data
|
||||
- **Type Preservation**: Variable types (strings, numbers, objects, etc.) are preserved when passed to the child workflow
|
||||
|
||||
### Examples of Input References
|
||||
|
||||
- `<variable.customerData>` - Pass a workflow variable
|
||||
- `<dataProcessor.response.result>` - Pass the result from a previous block
|
||||
- `<start.response.input>` - Pass the original workflow input
|
||||
- `<apiCall.response.data.user>` - Pass a specific field from an API response
|
||||
|
||||
### Execution Context
|
||||
|
||||
The child workflow executes with:
|
||||
|
||||
- Its own isolated execution context
|
||||
- Access to the same workspace resources (API keys, environment variables)
|
||||
- Proper workspace membership and permission checks
|
||||
- Independent logging and monitoring
|
||||
|
||||
## Safety and Limitations
|
||||
|
||||
To prevent infinite recursion and ensure system stability, the Workflow block includes several safety mechanisms:
|
||||
|
||||
<Callout type="warning">
|
||||
**Cycle Detection**: The system automatically detects and prevents circular dependencies between workflows to avoid infinite loops.
|
||||
</Callout>
|
||||
|
||||
- **Maximum Depth Limit**: Nested workflows are limited to a maximum depth of 10 levels
|
||||
- **Cycle Detection**: Automatic detection and prevention of circular workflow dependencies
|
||||
- **Timeout Protection**: Child workflows inherit timeout settings to prevent indefinite execution
|
||||
- **Resource Limits**: Memory and execution time limits apply to prevent resource exhaustion
|
||||
|
||||
## Inputs and Outputs
|
||||
|
||||
<Tabs items={['Inputs', 'Outputs']}>
|
||||
<Tab>
|
||||
<ul className="list-disc space-y-2 pl-6">
|
||||
<li>
|
||||
<strong>Workflow ID</strong>: The identifier of the workflow to execute
|
||||
</li>
|
||||
<li>
|
||||
<strong>Input Variable</strong>: Variable or block reference to pass to the child workflow (e.g., `<variable.name>` or `<block.response.field>`)
|
||||
</li>
|
||||
</ul>
|
||||
</Tab>
|
||||
<Tab>
|
||||
<ul className="list-disc space-y-2 pl-6">
|
||||
<li>
|
||||
<strong>Response</strong>: The complete output from the child workflow execution
|
||||
</li>
|
||||
<li>
|
||||
<strong>Child Workflow Name</strong>: The name of the executed child workflow
|
||||
</li>
|
||||
<li>
|
||||
<strong>Success Status</strong>: Boolean indicating whether the child workflow completed successfully
|
||||
</li>
|
||||
<li>
|
||||
<strong>Error Information</strong>: Details about any errors that occurred during execution
|
||||
</li>
|
||||
<li>
|
||||
<strong>Execution Metadata</strong>: Information about execution time, resource usage, and performance
|
||||
</li>
|
||||
</ul>
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Example Usage
|
||||
|
||||
Here's an example of how a Workflow block might be used to create a modular customer onboarding process:
|
||||
|
||||
### Parent Workflow: Customer Onboarding
|
||||
```yaml
|
||||
# Main customer onboarding workflow
|
||||
blocks:
|
||||
- type: workflow
|
||||
name: "Validate Customer Data"
|
||||
workflowId: "customer-validation-workflow"
|
||||
input: "<variable.newCustomer>"
|
||||
|
||||
- type: workflow
|
||||
name: "Setup Customer Account"
|
||||
workflowId: "account-setup-workflow"
|
||||
input: "<Validate Customer Data.response.result>"
|
||||
|
||||
- type: workflow
|
||||
name: "Send Welcome Email"
|
||||
workflowId: "welcome-email-workflow"
|
||||
input: "<Setup Customer Account.response.result.accountDetails>"
|
||||
```
|
||||
|
||||
### Child Workflow: Customer Validation
|
||||
```yaml
|
||||
# Reusable customer validation workflow
|
||||
# Access the input data using: start.response.input
|
||||
blocks:
|
||||
- type: function
|
||||
name: "Validate Email"
|
||||
code: |
|
||||
const customerData = start.response.input;
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
return emailRegex.test(customerData.email);
|
||||
|
||||
- type: api
|
||||
name: "Check Credit Score"
|
||||
url: "https://api.creditcheck.com/score"
|
||||
method: "POST"
|
||||
body: "<start.response.input>"
|
||||
```
|
||||
|
||||
### Variable Reference Examples
|
||||
|
||||
```yaml
|
||||
# Using workflow variables
|
||||
input: "<variable.customerInfo>"
|
||||
|
||||
# Using block outputs
|
||||
input: "<dataProcessor.response.cleanedData>"
|
||||
|
||||
# Using nested object properties
|
||||
input: "<apiCall.response.data.user.profile>"
|
||||
|
||||
# Using array elements (if supported by the resolver)
|
||||
input: "<listProcessor.response.items[0]>"
|
||||
```
|
||||
|
||||
## Access Control and Permissions
|
||||
|
||||
The Workflow block respects workspace permissions and access controls:
|
||||
|
||||
- **Workspace Membership**: Only workflows within the same workspace can be executed
|
||||
- **Permission Inheritance**: Child workflows inherit the execution permissions of the parent workflow
|
||||
- **API Key Access**: Child workflows have access to the same API keys and environment variables as the parent
|
||||
- **User Context**: The execution maintains the original user context for audit and logging purposes
|
||||
|
||||
## Best Practices
|
||||
|
||||
- **Keep workflows focused**: Design child workflows to handle specific, well-defined tasks
|
||||
- **Minimize nesting depth**: Avoid deeply nested workflow hierarchies for better maintainability
|
||||
- **Handle errors gracefully**: Implement proper error handling for child workflow failures
|
||||
- **Document dependencies**: Clearly document which workflows depend on others
|
||||
- **Version control**: Consider versioning strategies for workflows that are used as components
|
||||
- **Test independently**: Ensure child workflows can be tested and validated independently
|
||||
- **Monitor performance**: Be aware that nested workflows can impact overall execution time
|
||||
|
||||
## Common Patterns
|
||||
|
||||
### Microservice Architecture
|
||||
Break down complex business processes into smaller, focused workflows that can be developed and maintained independently.
|
||||
|
||||
### Reusable Components
|
||||
Create library workflows for common operations like data validation, email sending, or API integrations that can be reused across multiple projects.
|
||||
|
||||
### Conditional Execution
|
||||
Use workflow blocks within conditional logic to execute different business processes based on runtime conditions.
|
||||
|
||||
### Parallel Processing
|
||||
Combine workflow blocks with parallel execution to run multiple child workflows simultaneously for improved performance.
|
||||
|
||||
<Callout type="tip">
|
||||
When designing modular workflows, think of each workflow as a function with clear inputs, outputs, and a single responsibility.
|
||||
</Callout>
|
||||
@@ -12,7 +12,10 @@
|
||||
"---Execution---",
|
||||
"execution",
|
||||
"---Advanced---",
|
||||
"./variables/index"
|
||||
"./variables/index",
|
||||
"---SDKs---",
|
||||
"./sdks/python",
|
||||
"./sdks/typescript"
|
||||
],
|
||||
"defaultOpen": true
|
||||
}
|
||||
|
||||
409
apps/docs/content/docs/sdks/python.mdx
Normal file
409
apps/docs/content/docs/sdks/python.mdx
Normal file
@@ -0,0 +1,409 @@
|
||||
---
|
||||
title: Python SDK
|
||||
description: The official Python SDK for Sim Studio
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Card, Cards } from 'fumadocs-ui/components/card'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
|
||||
The official Python SDK for Sim Studio allows you to execute workflows programmatically from your Python applications.
|
||||
|
||||
<Callout type="info">
|
||||
The Python SDK supports Python 3.8+ and provides synchronous workflow execution. All workflow executions are currently synchronous.
|
||||
</Callout>
|
||||
|
||||
## Installation
|
||||
|
||||
Install the SDK using pip:
|
||||
|
||||
```bash
|
||||
pip install simstudio-sdk
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
Here's a simple example to get you started:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Initialize the client
|
||||
client = SimStudioClient(
|
||||
api_key="your-api-key-here",
|
||||
base_url="https://simstudio.ai" # optional, defaults to https://simstudio.ai
|
||||
)
|
||||
|
||||
# Execute a workflow
|
||||
try:
|
||||
result = client.execute_workflow("workflow-id")
|
||||
print("Workflow executed successfully:", result)
|
||||
except Exception as error:
|
||||
print("Workflow execution failed:", error)
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### SimStudioClient
|
||||
|
||||
#### Constructor
|
||||
|
||||
```python
|
||||
SimStudioClient(api_key: str, base_url: str = "https://simstudio.ai")
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `api_key` (str): Your Sim Studio API key
|
||||
- `base_url` (str, optional): Base URL for the Sim Studio API
|
||||
|
||||
#### Methods
|
||||
|
||||
##### execute_workflow()
|
||||
|
||||
Execute a workflow with optional input data.
|
||||
|
||||
```python
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"message": "Hello, world!"},
|
||||
timeout=30.0 # 30 seconds
|
||||
)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `workflow_id` (str): The ID of the workflow to execute
|
||||
- `input_data` (dict, optional): Input data to pass to the workflow
|
||||
- `timeout` (float, optional): Timeout in seconds (default: 30.0)
|
||||
|
||||
**Returns:** `WorkflowExecutionResult`
|
||||
|
||||
##### get_workflow_status()
|
||||
|
||||
Get the status of a workflow (deployment status, etc.).
|
||||
|
||||
```python
|
||||
status = client.get_workflow_status("workflow-id")
|
||||
print("Is deployed:", status.is_deployed)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `workflow_id` (str): The ID of the workflow
|
||||
|
||||
**Returns:** `WorkflowStatus`
|
||||
|
||||
##### validate_workflow()
|
||||
|
||||
Validate that a workflow is ready for execution.
|
||||
|
||||
```python
|
||||
is_ready = client.validate_workflow("workflow-id")
|
||||
if is_ready:
|
||||
# Workflow is deployed and ready
|
||||
pass
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `workflow_id` (str): The ID of the workflow
|
||||
|
||||
**Returns:** `bool`
|
||||
|
||||
##### execute_workflow_sync()
|
||||
|
||||
<Callout type="info">
|
||||
Currently, this method is identical to `execute_workflow()` since all executions are synchronous. This method is provided for future compatibility when asynchronous execution is added.
|
||||
</Callout>
|
||||
|
||||
Execute a workflow (currently synchronous, same as `execute_workflow()`).
|
||||
|
||||
```python
|
||||
result = client.execute_workflow_sync(
|
||||
"workflow-id",
|
||||
input_data={"data": "some input"},
|
||||
timeout=60.0
|
||||
)
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `workflow_id` (str): The ID of the workflow to execute
|
||||
- `input_data` (dict, optional): Input data to pass to the workflow
|
||||
- `timeout` (float): Timeout for the initial request in seconds
|
||||
|
||||
**Returns:** `WorkflowExecutionResult`
|
||||
|
||||
##### set_api_key()
|
||||
|
||||
Update the API key.
|
||||
|
||||
```python
|
||||
client.set_api_key("new-api-key")
|
||||
```
|
||||
|
||||
##### set_base_url()
|
||||
|
||||
Update the base URL.
|
||||
|
||||
```python
|
||||
client.set_base_url("https://my-custom-domain.com")
|
||||
```
|
||||
|
||||
##### close()
|
||||
|
||||
Close the underlying HTTP session.
|
||||
|
||||
```python
|
||||
client.close()
|
||||
```
|
||||
|
||||
## Data Classes
|
||||
|
||||
### WorkflowExecutionResult
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class WorkflowExecutionResult:
|
||||
success: bool
|
||||
output: Optional[Any] = None
|
||||
error: Optional[str] = None
|
||||
logs: Optional[List[Any]] = None
|
||||
metadata: Optional[Dict[str, Any]] = None
|
||||
trace_spans: Optional[List[Any]] = None
|
||||
total_duration: Optional[float] = None
|
||||
```
|
||||
|
||||
### WorkflowStatus
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class WorkflowStatus:
|
||||
is_deployed: bool
|
||||
deployed_at: Optional[str] = None
|
||||
is_published: bool = False
|
||||
needs_redeployment: bool = False
|
||||
```
|
||||
|
||||
### SimStudioError
|
||||
|
||||
```python
|
||||
class SimStudioError(Exception):
|
||||
def __init__(self, message: str, code: Optional[str] = None, status: Optional[int] = None):
|
||||
super().__init__(message)
|
||||
self.code = code
|
||||
self.status = status
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Workflow Execution
|
||||
|
||||
<Steps>
|
||||
<Step title="Initialize the client">
|
||||
Set up the SimStudioClient with your API key.
|
||||
</Step>
|
||||
<Step title="Validate the workflow">
|
||||
Check if the workflow is deployed and ready for execution.
|
||||
</Step>
|
||||
<Step title="Execute the workflow">
|
||||
Run the workflow with your input data.
|
||||
</Step>
|
||||
<Step title="Handle the result">
|
||||
Process the execution result and handle any errors.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIMSTUDIO_API_KEY"))
|
||||
|
||||
def run_workflow():
|
||||
try:
|
||||
# Check if workflow is ready
|
||||
is_ready = client.validate_workflow("my-workflow-id")
|
||||
if not is_ready:
|
||||
raise Exception("Workflow is not deployed or ready")
|
||||
|
||||
# Execute the workflow
|
||||
result = client.execute_workflow(
|
||||
"my-workflow-id",
|
||||
input_data={
|
||||
"message": "Process this data",
|
||||
"user_id": "12345"
|
||||
}
|
||||
)
|
||||
|
||||
if result.success:
|
||||
print("Output:", result.output)
|
||||
print("Duration:", result.metadata.get("duration") if result.metadata else None)
|
||||
else:
|
||||
print("Workflow failed:", result.error)
|
||||
|
||||
except Exception as error:
|
||||
print("Error:", error)
|
||||
|
||||
run_workflow()
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
Handle different types of errors that may occur during workflow execution:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient, SimStudioError
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIMSTUDIO_API_KEY"))
|
||||
|
||||
def execute_with_error_handling():
|
||||
try:
|
||||
result = client.execute_workflow("workflow-id")
|
||||
return result
|
||||
except SimStudioError as error:
|
||||
if error.code == "UNAUTHORIZED":
|
||||
print("Invalid API key")
|
||||
elif error.code == "TIMEOUT":
|
||||
print("Workflow execution timed out")
|
||||
elif error.code == "USAGE_LIMIT_EXCEEDED":
|
||||
print("Usage limit exceeded")
|
||||
elif error.code == "INVALID_JSON":
|
||||
print("Invalid JSON in request body")
|
||||
else:
|
||||
print(f"Workflow error: {error}")
|
||||
raise
|
||||
except Exception as error:
|
||||
print(f"Unexpected error: {error}")
|
||||
raise
|
||||
```
|
||||
|
||||
### Context Manager Usage
|
||||
|
||||
Use the client as a context manager to automatically handle resource cleanup:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
# Using context manager to automatically close the session
|
||||
with SimStudioClient(api_key=os.getenv("SIMSTUDIO_API_KEY")) as client:
|
||||
result = client.execute_workflow("workflow-id")
|
||||
print("Result:", result)
|
||||
# Session is automatically closed here
|
||||
```
|
||||
|
||||
### Batch Workflow Execution
|
||||
|
||||
Execute multiple workflows efficiently:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIMSTUDIO_API_KEY"))
|
||||
|
||||
def execute_workflows_batch(workflow_data_pairs):
|
||||
"""Execute multiple workflows with different input data."""
|
||||
results = []
|
||||
|
||||
for workflow_id, input_data in workflow_data_pairs:
|
||||
try:
|
||||
# Validate workflow before execution
|
||||
if not client.validate_workflow(workflow_id):
|
||||
print(f"Skipping {workflow_id}: not deployed")
|
||||
continue
|
||||
|
||||
result = client.execute_workflow(workflow_id, input_data)
|
||||
results.append({
|
||||
"workflow_id": workflow_id,
|
||||
"success": result.success,
|
||||
"output": result.output,
|
||||
"error": result.error
|
||||
})
|
||||
|
||||
except Exception as error:
|
||||
results.append({
|
||||
"workflow_id": workflow_id,
|
||||
"success": False,
|
||||
"error": str(error)
|
||||
})
|
||||
|
||||
return results
|
||||
|
||||
# Example usage
|
||||
workflows = [
|
||||
("workflow-1", {"type": "analysis", "data": "sample1"}),
|
||||
("workflow-2", {"type": "processing", "data": "sample2"}),
|
||||
]
|
||||
|
||||
results = execute_workflows_batch(workflows)
|
||||
for result in results:
|
||||
print(f"Workflow {result['workflow_id']}: {'Success' if result['success'] else 'Failed'}")
|
||||
```
|
||||
|
||||
### Environment Configuration
|
||||
|
||||
Configure the client using environment variables:
|
||||
|
||||
<Tabs items={['Development', 'Production']}>
|
||||
<Tab value="Development">
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Development configuration
|
||||
client = SimStudioClient(
|
||||
api_key=os.getenv("SIMSTUDIO_API_KEY"),
|
||||
base_url=os.getenv("SIMSTUDIO_BASE_URL", "https://simstudio.ai")
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Production">
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Production configuration with error handling
|
||||
api_key = os.getenv("SIMSTUDIO_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("SIMSTUDIO_API_KEY environment variable is required")
|
||||
|
||||
client = SimStudioClient(
|
||||
api_key=api_key,
|
||||
base_url=os.getenv("SIMSTUDIO_BASE_URL", "https://simstudio.ai")
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Getting Your API Key
|
||||
|
||||
<Steps>
|
||||
<Step title="Log in to Sim Studio">
|
||||
Navigate to [Sim Studio](https://simstudio.ai) and log in to your account.
|
||||
</Step>
|
||||
<Step title="Open your workflow">
|
||||
Navigate to the workflow you want to execute programmatically.
|
||||
</Step>
|
||||
<Step title="Deploy your workflow">
|
||||
Click on "Deploy" to deploy your workflow if it hasn't been deployed yet.
|
||||
</Step>
|
||||
<Step title="Create or select an API key">
|
||||
During the deployment process, select or create an API key.
|
||||
</Step>
|
||||
<Step title="Copy the API key">
|
||||
Copy the API key to use in your Python application.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Callout type="warning">
|
||||
Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management.
|
||||
</Callout>
|
||||
|
||||
## Requirements
|
||||
|
||||
- Python 3.8+
|
||||
- requests >= 2.25.0
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
598
apps/docs/content/docs/sdks/typescript.mdx
Normal file
598
apps/docs/content/docs/sdks/typescript.mdx
Normal file
@@ -0,0 +1,598 @@
|
||||
---
|
||||
title: TypeScript/JavaScript SDK
|
||||
description: The official TypeScript/JavaScript SDK for Sim Studio
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Card, Cards } from 'fumadocs-ui/components/card'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
|
||||
The official TypeScript/JavaScript SDK for Sim Studio allows you to execute workflows programmatically from your Node.js applications, web applications, and other JavaScript environments.
|
||||
|
||||
<Callout type="info">
|
||||
The TypeScript SDK provides full type safety and supports both Node.js and browser environments. All workflow executions are currently synchronous.
|
||||
</Callout>
|
||||
|
||||
## Installation
|
||||
|
||||
Install the SDK using your preferred package manager:
|
||||
|
||||
<Tabs items={['npm', 'yarn', 'bun']}>
|
||||
<Tab value="npm">
|
||||
```bash
|
||||
npm install simstudio-ts-sdk
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="yarn">
|
||||
```bash
|
||||
yarn add simstudio-ts-sdk
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="bun">
|
||||
```bash
|
||||
bun add simstudio-ts-sdk
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Quick Start
|
||||
|
||||
Here's a simple example to get you started:
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
|
||||
// Initialize the client
|
||||
const client = new SimStudioClient({
|
||||
apiKey: 'your-api-key-here',
|
||||
baseUrl: 'https://simstudio.ai' // optional, defaults to https://simstudio.ai
|
||||
});
|
||||
|
||||
// Execute a workflow
|
||||
try {
|
||||
const result = await client.executeWorkflow('workflow-id');
|
||||
console.log('Workflow executed successfully:', result);
|
||||
} catch (error) {
|
||||
console.error('Workflow execution failed:', error);
|
||||
}
|
||||
```
|
||||
|
||||
## API Reference
|
||||
|
||||
### SimStudioClient
|
||||
|
||||
#### Constructor
|
||||
|
||||
```typescript
|
||||
new SimStudioClient(config: SimStudioConfig)
|
||||
```
|
||||
|
||||
**Configuration:**
|
||||
- `config.apiKey` (string): Your Sim Studio API key
|
||||
- `config.baseUrl` (string, optional): Base URL for the Sim Studio API (defaults to `https://simstudio.ai`)
|
||||
|
||||
#### Methods
|
||||
|
||||
##### executeWorkflow()
|
||||
|
||||
Execute a workflow with optional input data.
|
||||
|
||||
```typescript
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: { message: 'Hello, world!' },
|
||||
timeout: 30000 // 30 seconds
|
||||
});
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `workflowId` (string): The ID of the workflow to execute
|
||||
- `options` (ExecutionOptions, optional):
|
||||
- `input` (any): Input data to pass to the workflow
|
||||
- `timeout` (number): Timeout in milliseconds (default: 30000)
|
||||
|
||||
**Returns:** `Promise<WorkflowExecutionResult>`
|
||||
|
||||
##### getWorkflowStatus()
|
||||
|
||||
Get the status of a workflow (deployment status, etc.).
|
||||
|
||||
```typescript
|
||||
const status = await client.getWorkflowStatus('workflow-id');
|
||||
console.log('Is deployed:', status.isDeployed);
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `workflowId` (string): The ID of the workflow
|
||||
|
||||
**Returns:** `Promise<WorkflowStatus>`
|
||||
|
||||
##### validateWorkflow()
|
||||
|
||||
Validate that a workflow is ready for execution.
|
||||
|
||||
```typescript
|
||||
const isReady = await client.validateWorkflow('workflow-id');
|
||||
if (isReady) {
|
||||
// Workflow is deployed and ready
|
||||
}
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `workflowId` (string): The ID of the workflow
|
||||
|
||||
**Returns:** `Promise<boolean>`
|
||||
|
||||
##### executeWorkflowSync()
|
||||
|
||||
<Callout type="info">
|
||||
Currently, this method is identical to `executeWorkflow()` since all executions are synchronous. This method is provided for future compatibility when asynchronous execution is added.
|
||||
</Callout>
|
||||
|
||||
Execute a workflow (currently synchronous, same as `executeWorkflow()`).
|
||||
|
||||
```typescript
|
||||
const result = await client.executeWorkflowSync('workflow-id', {
|
||||
input: { data: 'some input' },
|
||||
timeout: 60000
|
||||
});
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `workflowId` (string): The ID of the workflow to execute
|
||||
- `options` (ExecutionOptions, optional):
|
||||
- `input` (any): Input data to pass to the workflow
|
||||
- `timeout` (number): Timeout for the initial request in milliseconds
|
||||
|
||||
**Returns:** `Promise<WorkflowExecutionResult>`
|
||||
|
||||
##### setApiKey()
|
||||
|
||||
Update the API key.
|
||||
|
||||
```typescript
|
||||
client.setApiKey('new-api-key');
|
||||
```
|
||||
|
||||
##### setBaseUrl()
|
||||
|
||||
Update the base URL.
|
||||
|
||||
```typescript
|
||||
client.setBaseUrl('https://my-custom-domain.com');
|
||||
```
|
||||
|
||||
## Types
|
||||
|
||||
### WorkflowExecutionResult
|
||||
|
||||
```typescript
|
||||
interface WorkflowExecutionResult {
|
||||
success: boolean;
|
||||
output?: any;
|
||||
error?: string;
|
||||
logs?: any[];
|
||||
metadata?: {
|
||||
duration?: number;
|
||||
executionId?: string;
|
||||
[key: string]: any;
|
||||
};
|
||||
traceSpans?: any[];
|
||||
totalDuration?: number;
|
||||
}
|
||||
```
|
||||
|
||||
### WorkflowStatus
|
||||
|
||||
```typescript
|
||||
interface WorkflowStatus {
|
||||
isDeployed: boolean;
|
||||
deployedAt?: string;
|
||||
isPublished: boolean;
|
||||
needsRedeployment: boolean;
|
||||
}
|
||||
```
|
||||
|
||||
### SimStudioError
|
||||
|
||||
```typescript
|
||||
class SimStudioError extends Error {
|
||||
code?: string;
|
||||
status?: number;
|
||||
}
|
||||
```
|
||||
|
||||
## Examples
|
||||
|
||||
### Basic Workflow Execution
|
||||
|
||||
<Steps>
|
||||
<Step title="Initialize the client">
|
||||
Set up the SimStudioClient with your API key.
|
||||
</Step>
|
||||
<Step title="Validate the workflow">
|
||||
Check if the workflow is deployed and ready for execution.
|
||||
</Step>
|
||||
<Step title="Execute the workflow">
|
||||
Run the workflow with your input data.
|
||||
</Step>
|
||||
<Step title="Handle the result">
|
||||
Process the execution result and handle any errors.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.SIMSTUDIO_API_KEY!
|
||||
});
|
||||
|
||||
async function runWorkflow() {
|
||||
try {
|
||||
// Check if workflow is ready
|
||||
const isReady = await client.validateWorkflow('my-workflow-id');
|
||||
if (!isReady) {
|
||||
throw new Error('Workflow is not deployed or ready');
|
||||
}
|
||||
|
||||
// Execute the workflow
|
||||
const result = await client.executeWorkflow('my-workflow-id', {
|
||||
input: {
|
||||
message: 'Process this data',
|
||||
userId: '12345'
|
||||
}
|
||||
});
|
||||
|
||||
if (result.success) {
|
||||
console.log('Output:', result.output);
|
||||
console.log('Duration:', result.metadata?.duration);
|
||||
} else {
|
||||
console.error('Workflow failed:', result.error);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
runWorkflow();
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
|
||||
Handle different types of errors that may occur during workflow execution:
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.SIMSTUDIO_API_KEY!
|
||||
});
|
||||
|
||||
async function executeWithErrorHandling() {
|
||||
try {
|
||||
const result = await client.executeWorkflow('workflow-id');
|
||||
return result;
|
||||
} catch (error) {
|
||||
if (error instanceof SimStudioError) {
|
||||
switch (error.code) {
|
||||
case 'UNAUTHORIZED':
|
||||
console.error('Invalid API key');
|
||||
break;
|
||||
case 'TIMEOUT':
|
||||
console.error('Workflow execution timed out');
|
||||
break;
|
||||
case 'USAGE_LIMIT_EXCEEDED':
|
||||
console.error('Usage limit exceeded');
|
||||
break;
|
||||
case 'INVALID_JSON':
|
||||
console.error('Invalid JSON in request body');
|
||||
break;
|
||||
default:
|
||||
console.error('Workflow error:', error.message);
|
||||
}
|
||||
} else {
|
||||
console.error('Unexpected error:', error);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Environment Configuration
|
||||
|
||||
Configure the client using environment variables:
|
||||
|
||||
<Tabs items={['Development', 'Production']}>
|
||||
<Tab value="Development">
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
|
||||
// Development configuration
|
||||
const apiKey = process.env.SIMSTUDIO_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error('SIMSTUDIO_API_KEY environment variable is required');
|
||||
}
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey,
|
||||
baseUrl: process.env.SIMSTUDIO_BASE_URL // optional
|
||||
});
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Production">
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
|
||||
// Production configuration with validation
|
||||
const apiKey = process.env.SIMSTUDIO_API_KEY;
|
||||
if (!apiKey) {
|
||||
throw new Error('SIMSTUDIO_API_KEY environment variable is required');
|
||||
}
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey,
|
||||
baseUrl: process.env.SIMSTUDIO_BASE_URL || 'https://simstudio.ai'
|
||||
});
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
### Node.js Express Integration
|
||||
|
||||
Integrate with an Express.js server:
|
||||
|
||||
```typescript
|
||||
import express from 'express';
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
|
||||
const app = express();
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.SIMSTUDIO_API_KEY!
|
||||
});
|
||||
|
||||
app.use(express.json());
|
||||
|
||||
app.post('/execute-workflow', async (req, res) => {
|
||||
try {
|
||||
const { workflowId, input } = req.body;
|
||||
|
||||
const result = await client.executeWorkflow(workflowId, {
|
||||
input,
|
||||
timeout: 60000
|
||||
});
|
||||
|
||||
res.json({
|
||||
success: true,
|
||||
data: result
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Workflow execution error:', error);
|
||||
res.status(500).json({
|
||||
success: false,
|
||||
error: error instanceof Error ? error.message : 'Unknown error'
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
app.listen(3000, () => {
|
||||
console.log('Server running on port 3000');
|
||||
});
|
||||
```
|
||||
|
||||
### Next.js API Route
|
||||
|
||||
Use with Next.js API routes:
|
||||
|
||||
```typescript
|
||||
// pages/api/workflow.ts or app/api/workflow/route.ts
|
||||
import { NextApiRequest, NextApiResponse } from 'next';
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.SIMSTUDIO_API_KEY!
|
||||
});
|
||||
|
||||
export default async function handler(
|
||||
req: NextApiRequest,
|
||||
res: NextApiResponse
|
||||
) {
|
||||
if (req.method !== 'POST') {
|
||||
return res.status(405).json({ error: 'Method not allowed' });
|
||||
}
|
||||
|
||||
try {
|
||||
const { workflowId, input } = req.body;
|
||||
|
||||
const result = await client.executeWorkflow(workflowId, {
|
||||
input,
|
||||
timeout: 30000
|
||||
});
|
||||
|
||||
res.status(200).json(result);
|
||||
} catch (error) {
|
||||
console.error('Error executing workflow:', error);
|
||||
res.status(500).json({
|
||||
error: 'Failed to execute workflow'
|
||||
});
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Browser Usage
|
||||
|
||||
Use in the browser (with proper CORS configuration):
|
||||
|
||||
```typescript
|
||||
import { SimStudioClient } from 'simstudio-ts-sdk';
|
||||
|
||||
// Note: In production, use a proxy server to avoid exposing API keys
|
||||
const client = new SimStudioClient({
|
||||
apiKey: 'your-public-api-key', // Use with caution in browser
|
||||
baseUrl: 'https://simstudio.ai'
|
||||
});
|
||||
|
||||
async function executeClientSideWorkflow() {
|
||||
try {
|
||||
const result = await client.executeWorkflow('workflow-id', {
|
||||
input: {
|
||||
userInput: 'Hello from browser'
|
||||
}
|
||||
});
|
||||
|
||||
console.log('Workflow result:', result);
|
||||
|
||||
// Update UI with result
|
||||
document.getElementById('result')!.textContent =
|
||||
JSON.stringify(result.output, null, 2);
|
||||
} catch (error) {
|
||||
console.error('Error:', error);
|
||||
}
|
||||
}
|
||||
|
||||
// Attach to button click
|
||||
document.getElementById('executeBtn')?.addEventListener('click', executeClientSideWorkflow);
|
||||
```
|
||||
|
||||
<Callout type="warning">
|
||||
When using the SDK in the browser, be careful not to expose sensitive API keys. Consider using a backend proxy or public API keys with limited permissions.
|
||||
</Callout>
|
||||
|
||||
### React Hook Example
|
||||
|
||||
Create a custom React hook for workflow execution:
|
||||
|
||||
```typescript
|
||||
import { useState, useCallback } from 'react';
|
||||
import { SimStudioClient, WorkflowExecutionResult } from 'simstudio-ts-sdk';
|
||||
|
||||
const client = new SimStudioClient({
|
||||
apiKey: process.env.NEXT_PUBLIC_SIMSTUDIO_API_KEY!
|
||||
});
|
||||
|
||||
interface UseWorkflowResult {
|
||||
result: WorkflowExecutionResult | null;
|
||||
loading: boolean;
|
||||
error: Error | null;
|
||||
executeWorkflow: (workflowId: string, input?: any) => Promise<void>;
|
||||
}
|
||||
|
||||
export function useWorkflow(): UseWorkflowResult {
|
||||
const [result, setResult] = useState<WorkflowExecutionResult | null>(null);
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [error, setError] = useState<Error | null>(null);
|
||||
|
||||
const executeWorkflow = useCallback(async (workflowId: string, input?: any) => {
|
||||
setLoading(true);
|
||||
setError(null);
|
||||
setResult(null);
|
||||
|
||||
try {
|
||||
const workflowResult = await client.executeWorkflow(workflowId, {
|
||||
input,
|
||||
timeout: 30000
|
||||
});
|
||||
setResult(workflowResult);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err : new Error('Unknown error'));
|
||||
} finally {
|
||||
setLoading(false);
|
||||
}
|
||||
}, []);
|
||||
|
||||
return {
|
||||
result,
|
||||
loading,
|
||||
error,
|
||||
executeWorkflow
|
||||
};
|
||||
}
|
||||
|
||||
// Usage in component
|
||||
function WorkflowComponent() {
|
||||
const { result, loading, error, executeWorkflow } = useWorkflow();
|
||||
|
||||
const handleExecute = () => {
|
||||
executeWorkflow('my-workflow-id', {
|
||||
message: 'Hello from React!'
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div>
|
||||
<button onClick={handleExecute} disabled={loading}>
|
||||
{loading ? 'Executing...' : 'Execute Workflow'}
|
||||
</button>
|
||||
|
||||
{error && <div>Error: {error.message}</div>}
|
||||
{result && (
|
||||
<div>
|
||||
<h3>Result:</h3>
|
||||
<pre>{JSON.stringify(result, null, 2)}</pre>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## Getting Your API Key
|
||||
|
||||
<Steps>
|
||||
<Step title="Log in to Sim Studio">
|
||||
Navigate to [Sim Studio](https://simstudio.ai) and log in to your account.
|
||||
</Step>
|
||||
<Step title="Open your workflow">
|
||||
Navigate to the workflow you want to execute programmatically.
|
||||
</Step>
|
||||
<Step title="Deploy your workflow">
|
||||
Click on "Deploy" to deploy your workflow if it hasn't been deployed yet.
|
||||
</Step>
|
||||
<Step title="Create or select an API key">
|
||||
During the deployment process, select or create an API key.
|
||||
</Step>
|
||||
<Step title="Copy the API key">
|
||||
Copy the API key to use in your TypeScript/JavaScript application.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
<Callout type="warning">
|
||||
Keep your API key secure and never commit it to version control. Use environment variables or secure configuration management.
|
||||
</Callout>
|
||||
|
||||
## Requirements
|
||||
|
||||
- Node.js 16+
|
||||
- TypeScript 5.0+ (for TypeScript projects)
|
||||
|
||||
## TypeScript Support
|
||||
|
||||
The SDK is written in TypeScript and provides full type safety:
|
||||
|
||||
```typescript
|
||||
import {
|
||||
SimStudioClient,
|
||||
WorkflowExecutionResult,
|
||||
WorkflowStatus,
|
||||
SimStudioError
|
||||
} from 'simstudio-ts-sdk';
|
||||
|
||||
// Type-safe client initialization
|
||||
const client: SimStudioClient = new SimStudioClient({
|
||||
apiKey: process.env.SIMSTUDIO_API_KEY!
|
||||
});
|
||||
|
||||
// Type-safe workflow execution
|
||||
const result: WorkflowExecutionResult = await client.executeWorkflow('workflow-id', {
|
||||
input: {
|
||||
message: 'Hello, TypeScript!'
|
||||
}
|
||||
});
|
||||
|
||||
// Type-safe status checking
|
||||
const status: WorkflowStatus = await client.getWorkflowStatus('workflow-id');
|
||||
```
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
@@ -90,7 +90,7 @@ In Sim Studio, the Google Calendar integration enables your agents to programmat
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
Integrate Google Calendar functionality to create, read, update, and list calendar events within your workflow. Automate scheduling, check availability, and manage events using OAuth authentication.
|
||||
Integrate Google Calendar functionality to create, read, update, and list calendar events within your workflow. Automate scheduling, check availability, and manage events using OAuth authentication. Email invitations are sent asynchronously and delivery depends on recipients
|
||||
|
||||
|
||||
|
||||
@@ -180,6 +180,38 @@ Create events from natural language text
|
||||
| --------- | ---- |
|
||||
| `content` | string |
|
||||
|
||||
### `google_calendar_invite`
|
||||
|
||||
Invite attendees to an existing Google Calendar event
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `accessToken` | string | Yes | Access token for Google Calendar API |
|
||||
| `calendarId` | string | No | Calendar ID \(defaults to primary\) |
|
||||
| `eventId` | string | Yes | Event ID to invite attendees to |
|
||||
| `attendees` | array | Yes | Array of attendee email addresses to invite |
|
||||
| `sendUpdates` | string | No | How to send updates to attendees: all, externalOnly, or none |
|
||||
| `replaceExisting` | boolean | No | Whether to replace existing attendees or add to them \(defaults to false\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type |
|
||||
| --------- | ---- |
|
||||
| `metadata` | string |
|
||||
| `htmlLink` | string |
|
||||
| `status` | string |
|
||||
| `summary` | string |
|
||||
| `description` | string |
|
||||
| `location` | string |
|
||||
| `start` | string |
|
||||
| `end` | string |
|
||||
| `attendees` | string |
|
||||
| `creator` | string |
|
||||
| `organizer` | string |
|
||||
| `content` | string |
|
||||
|
||||
|
||||
|
||||
## Block Configuration
|
||||
|
||||
127
apps/docs/content/docs/tools/huggingface.mdx
Normal file
127
apps/docs/content/docs/tools/huggingface.mdx
Normal file
File diff suppressed because one or more lines are too long
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: Knowledge
|
||||
description: Search knowledge
|
||||
description: Use vector search
|
||||
---
|
||||
|
||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||
@@ -49,7 +49,7 @@ In Sim Studio, the Knowledge Base block enables your agents to perform intellige
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
Perform semantic vector search across your knowledge base to find the most relevant content. Uses advanced AI embeddings to understand meaning and context, returning the most similar documents to your search query.
|
||||
Perform semantic vector search across one or more knowledge bases or upload new chunks to documents. Uses advanced AI embeddings to understand meaning and context for search operations.
|
||||
|
||||
|
||||
|
||||
@@ -57,13 +57,13 @@ Perform semantic vector search across your knowledge base to find the most relev
|
||||
|
||||
### `knowledge_search`
|
||||
|
||||
Search for similar content in a knowledge base using vector similarity
|
||||
Search for similar content in one or more knowledge bases using vector similarity
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `knowledgeBaseId` | string | Yes | ID of the knowledge base to search in |
|
||||
| `knowledgeBaseIds` | string | Yes | ID of the knowledge base to search in, or comma-separated IDs for multiple knowledge bases |
|
||||
| `query` | string | Yes | Search query text |
|
||||
| `topK` | number | No | Number of most similar results to return \(1-100\) |
|
||||
|
||||
@@ -73,10 +73,32 @@ Search for similar content in a knowledge base using vector similarity
|
||||
| --------- | ---- |
|
||||
| `results` | string |
|
||||
| `query` | string |
|
||||
| `knowledgeBaseId` | string |
|
||||
| `topK` | string |
|
||||
| `totalResults` | string |
|
||||
| `message` | string |
|
||||
|
||||
### `knowledge_upload_chunk`
|
||||
|
||||
Upload a new chunk to a document in a knowledge base
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `knowledgeBaseId` | string | Yes | ID of the knowledge base containing the document |
|
||||
| `documentId` | string | Yes | ID of the document to upload the chunk to |
|
||||
| `content` | string | Yes | Content of the chunk to upload |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type |
|
||||
| --------- | ---- |
|
||||
| `data` | string |
|
||||
| `chunkIndex` | string |
|
||||
| `content` | string |
|
||||
| `contentLength` | string |
|
||||
| `tokenCount` | string |
|
||||
| `enabled` | string |
|
||||
| `createdAt` | string |
|
||||
| `updatedAt` | string |
|
||||
|
||||
|
||||
|
||||
@@ -86,7 +108,7 @@ Search for similar content in a knowledge base using vector similarity
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `knowledgeBaseId` | string | Yes | Knowledge Base - Select knowledge base |
|
||||
| `operation` | string | Yes | Operation |
|
||||
|
||||
|
||||
|
||||
@@ -97,10 +119,7 @@ Search for similar content in a knowledge base using vector similarity
|
||||
| `response` | object | Output from response |
|
||||
| ↳ `results` | json | results of the response |
|
||||
| ↳ `query` | string | query of the response |
|
||||
| ↳ `knowledgeBaseId` | string | knowledgeBaseId of the response |
|
||||
| ↳ `topK` | number | topK of the response |
|
||||
| ↳ `totalResults` | number | totalResults of the response |
|
||||
| ↳ `message` | string | message of the response |
|
||||
|
||||
|
||||
## Notes
|
||||
|
||||
@@ -19,6 +19,7 @@
|
||||
"google_search",
|
||||
"google_sheets",
|
||||
"guesty",
|
||||
"huggingface",
|
||||
"image_generator",
|
||||
"jina",
|
||||
"jira",
|
||||
|
||||
BIN
apps/docs/public/static/dark/response-dark.png
Normal file
BIN
apps/docs/public/static/dark/response-dark.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
BIN
apps/docs/public/static/dark/workflow-dark.png
Normal file
BIN
apps/docs/public/static/dark/workflow-dark.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 38 KiB |
BIN
apps/docs/public/static/light/response-light.png
Normal file
BIN
apps/docs/public/static/light/response-light.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 25 KiB |
BIN
apps/docs/public/static/light/workflow-light.png
Normal file
BIN
apps/docs/public/static/light/workflow-light.png
Normal file
Binary file not shown.
|
After Width: | Height: | Size: 26 KiB |
Reference in New Issue
Block a user