mirror of
https://github.com/simstudioai/sim.git
synced 2026-03-15 03:00:33 -04:00
Compare commits
39 Commits
v0.5.102
...
improvemen
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
fc5df60d8f | ||
|
|
adea9db89d | ||
|
|
94abc424be | ||
|
|
c1c6ed66d1 | ||
|
|
a71304200e | ||
|
|
a4d581c76f | ||
|
|
f1efc598d1 | ||
|
|
244cf4ff7e | ||
|
|
ae887185a1 | ||
|
|
06c88441f8 | ||
|
|
127968d467 | ||
|
|
2722f0efbf | ||
|
|
4f45f705a5 | ||
|
|
d640fa0852 | ||
|
|
28f8e0fd97 | ||
|
|
cc38ecaf12 | ||
|
|
0a6a2ee694 | ||
|
|
8579beb199 | ||
|
|
115b4581a5 | ||
|
|
fcdcaed00d | ||
|
|
04fa31864b | ||
|
|
6b355e9b54 | ||
|
|
127994f077 | ||
|
|
efc1aeed70 | ||
|
|
46065983f6 | ||
|
|
2c79d0249f | ||
|
|
1cf7fdfc8c | ||
|
|
37bdffeda0 | ||
|
|
6fa4b9b410 | ||
|
|
f0ee492ada | ||
|
|
a8e0203a92 | ||
|
|
ebb9a2bdd3 | ||
|
|
61a447aba5 | ||
|
|
e91ab6260a | ||
|
|
afaa361801 | ||
|
|
cd88706ea4 | ||
|
|
79bb4e5ad8 | ||
|
|
ee20e119de | ||
|
|
3788660366 |
@@ -20,6 +20,7 @@ When the user asks you to create a block:
|
||||
import { {ServiceName}Icon } from '@/components/icons'
|
||||
import type { BlockConfig } from '@/blocks/types'
|
||||
import { AuthMode } from '@/blocks/types'
|
||||
import { getScopesForService } from '@/lib/oauth/utils'
|
||||
|
||||
export const {ServiceName}Block: BlockConfig = {
|
||||
type: '{service}', // snake_case identifier
|
||||
@@ -115,12 +116,17 @@ export const {ServiceName}Block: BlockConfig = {
|
||||
id: 'credential',
|
||||
title: 'Account',
|
||||
type: 'oauth-input',
|
||||
serviceId: '{service}', // Must match OAuth provider
|
||||
serviceId: '{service}', // Must match OAuth provider service key
|
||||
requiredScopes: getScopesForService('{service}'), // Import from @/lib/oauth/utils
|
||||
placeholder: 'Select account',
|
||||
required: true,
|
||||
}
|
||||
```
|
||||
|
||||
**Scopes:** Always use `getScopesForService(serviceId)` from `@/lib/oauth/utils` for `requiredScopes`. Never hardcode scope arrays — the single source of truth is `OAUTH_PROVIDERS` in `lib/oauth/oauth.ts`.
|
||||
|
||||
**Scope descriptions:** When adding a new OAuth provider, also add human-readable descriptions for all scopes in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts`.
|
||||
|
||||
### Selectors (with dynamic options)
|
||||
```typescript
|
||||
// Channel selector (Slack, Discord, etc.)
|
||||
@@ -624,6 +630,7 @@ export const registry: Record<string, BlockConfig> = {
|
||||
import { ServiceIcon } from '@/components/icons'
|
||||
import type { BlockConfig } from '@/blocks/types'
|
||||
import { AuthMode } from '@/blocks/types'
|
||||
import { getScopesForService } from '@/lib/oauth/utils'
|
||||
|
||||
export const ServiceBlock: BlockConfig = {
|
||||
type: 'service',
|
||||
@@ -654,6 +661,7 @@ export const ServiceBlock: BlockConfig = {
|
||||
title: 'Service Account',
|
||||
type: 'oauth-input',
|
||||
serviceId: 'service',
|
||||
requiredScopes: getScopesForService('service'),
|
||||
placeholder: 'Select account',
|
||||
required: true,
|
||||
},
|
||||
@@ -792,7 +800,8 @@ All tool IDs referenced in `tools.access` and returned by `tools.config.tool` MU
|
||||
- [ ] Conditions use correct syntax (field, value, not, and)
|
||||
- [ ] DependsOn set for fields that need other values
|
||||
- [ ] Required fields marked correctly (boolean or condition)
|
||||
- [ ] OAuth inputs have correct `serviceId`
|
||||
- [ ] OAuth inputs have correct `serviceId` and `requiredScopes: getScopesForService(serviceId)`
|
||||
- [ ] Scope descriptions added to `SCOPE_DESCRIPTIONS` in `lib/oauth/utils.ts` for any new scopes
|
||||
- [ ] Tools.access lists all tool IDs (snake_case)
|
||||
- [ ] Tools.config.tool returns correct tool ID (snake_case)
|
||||
- [ ] Outputs match tool outputs
|
||||
|
||||
@@ -114,6 +114,7 @@ export const {service}{Action}Tool: ToolConfig<Params, Response> = {
|
||||
import { {Service}Icon } from '@/components/icons'
|
||||
import type { BlockConfig } from '@/blocks/types'
|
||||
import { AuthMode } from '@/blocks/types'
|
||||
import { getScopesForService } from '@/lib/oauth/utils'
|
||||
|
||||
export const {Service}Block: BlockConfig = {
|
||||
type: '{service}',
|
||||
@@ -144,6 +145,7 @@ export const {Service}Block: BlockConfig = {
|
||||
title: '{Service} Account',
|
||||
type: 'oauth-input',
|
||||
serviceId: '{service}',
|
||||
requiredScopes: getScopesForService('{service}'),
|
||||
required: true,
|
||||
},
|
||||
// Conditional fields per operation
|
||||
@@ -409,7 +411,7 @@ If creating V2 versions (API-aligned outputs):
|
||||
### Block
|
||||
- [ ] Created `blocks/blocks/{service}.ts`
|
||||
- [ ] Defined operation dropdown with all operations
|
||||
- [ ] Added credential field (oauth-input or short-input)
|
||||
- [ ] Added credential field with `requiredScopes: getScopesForService('{service}')`
|
||||
- [ ] Added conditional fields per operation
|
||||
- [ ] Set up dependsOn for cascading selectors
|
||||
- [ ] Configured tools.access with all tool IDs
|
||||
@@ -419,6 +421,12 @@ If creating V2 versions (API-aligned outputs):
|
||||
- [ ] If triggers: set `triggers.enabled` and `triggers.available`
|
||||
- [ ] If triggers: spread trigger subBlocks with `getTrigger()`
|
||||
|
||||
### OAuth Scopes (if OAuth service)
|
||||
- [ ] Defined scopes in `lib/oauth/oauth.ts` under `OAUTH_PROVIDERS`
|
||||
- [ ] Added scope descriptions in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts`
|
||||
- [ ] Used `getCanonicalScopesForProvider()` in `auth.ts` (never hardcode)
|
||||
- [ ] Used `getScopesForService()` in block `requiredScopes` (never hardcode)
|
||||
|
||||
### Icon
|
||||
- [ ] Asked user to provide SVG
|
||||
- [ ] Added icon to `components/icons.tsx`
|
||||
@@ -717,6 +725,25 @@ Use `wandConfig` for fields that are hard to fill out manually:
|
||||
}
|
||||
```
|
||||
|
||||
### OAuth Scopes (Centralized System)
|
||||
|
||||
Scopes are maintained in a single source of truth and reused everywhere:
|
||||
|
||||
1. **Define scopes** in `lib/oauth/oauth.ts` under `OAUTH_PROVIDERS[provider].services[service].scopes`
|
||||
2. **Add descriptions** in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts` for the OAuth modal UI
|
||||
3. **Reference in auth.ts** using `getCanonicalScopesForProvider(providerId)` from `@/lib/oauth/utils`
|
||||
4. **Reference in blocks** using `getScopesForService(serviceId)` from `@/lib/oauth/utils`
|
||||
|
||||
**Never hardcode scope arrays** in `auth.ts` or block `requiredScopes`. Always import from the centralized source.
|
||||
|
||||
```typescript
|
||||
// In auth.ts (Better Auth config)
|
||||
scopes: getCanonicalScopesForProvider('{service}'),
|
||||
|
||||
// In block credential sub-block
|
||||
requiredScopes: getScopesForService('{service}'),
|
||||
```
|
||||
|
||||
### Common Gotchas
|
||||
|
||||
1. **OAuth serviceId must match** - The `serviceId` in oauth-input must match the OAuth provider configuration
|
||||
@@ -729,3 +756,5 @@ Use `wandConfig` for fields that are hard to fill out manually:
|
||||
8. **Always handle legacy file params** - Keep hidden `fileContent` params for backwards compatibility
|
||||
9. **Optional fields use advanced mode** - Set `mode: 'advanced'` on rarely-used optional fields
|
||||
10. **Complex inputs need wandConfig** - Timestamps, JSON arrays, and other hard-to-type values should have `wandConfig` enabled
|
||||
11. **Never hardcode scopes** - Use `getScopesForService()` in blocks and `getCanonicalScopesForProvider()` in auth.ts
|
||||
12. **Always add scope descriptions** - New scopes must have entries in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts`
|
||||
|
||||
@@ -26,8 +26,9 @@ apps/sim/blocks/blocks/{service}.ts # Block definition
|
||||
apps/sim/tools/registry.ts # Tool registry entries for this service
|
||||
apps/sim/blocks/registry.ts # Block registry entry for this service
|
||||
apps/sim/components/icons.tsx # Icon definition
|
||||
apps/sim/lib/auth/auth.ts # OAuth scopes (if OAuth service)
|
||||
apps/sim/lib/oauth/oauth.ts # OAuth provider config (if OAuth service)
|
||||
apps/sim/lib/auth/auth.ts # OAuth config — should use getCanonicalScopesForProvider()
|
||||
apps/sim/lib/oauth/oauth.ts # OAuth provider config — single source of truth for scopes
|
||||
apps/sim/lib/oauth/utils.ts # Scope utilities, SCOPE_DESCRIPTIONS for modal UI
|
||||
```
|
||||
|
||||
## Step 2: Pull API Documentation
|
||||
@@ -199,11 +200,14 @@ For **each tool** in `tools.access`:
|
||||
|
||||
## Step 5: Validate OAuth Scopes (if OAuth service)
|
||||
|
||||
- [ ] `auth.ts` scopes include ALL scopes needed by ALL tools in the integration
|
||||
- [ ] `oauth.ts` provider config scopes match `auth.ts` scopes
|
||||
- [ ] Block `requiredScopes` (if defined) matches `auth.ts` scopes
|
||||
Scopes are centralized — the single source of truth is `OAUTH_PROVIDERS` in `lib/oauth/oauth.ts`.
|
||||
|
||||
- [ ] Scopes defined in `lib/oauth/oauth.ts` under `OAUTH_PROVIDERS[provider].services[service].scopes`
|
||||
- [ ] `auth.ts` uses `getCanonicalScopesForProvider(providerId)` — NOT a hardcoded array
|
||||
- [ ] Block `requiredScopes` uses `getScopesForService(serviceId)` — NOT a hardcoded array
|
||||
- [ ] No hardcoded scope arrays in `auth.ts` or block files (should all use utility functions)
|
||||
- [ ] Each scope has a human-readable description in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts`
|
||||
- [ ] No excess scopes that aren't needed by any tool
|
||||
- [ ] Each scope has a human-readable description in `oauth-required-modal.tsx`'s `SCOPE_DESCRIPTIONS`
|
||||
|
||||
## Step 6: Validate Pagination Consistency
|
||||
|
||||
@@ -244,7 +248,8 @@ Group findings by severity:
|
||||
- Missing `.trim()` on ID fields in request URLs
|
||||
- Missing `?? null` on nullable response fields
|
||||
- Block condition array missing an operation that uses that field
|
||||
- Missing scope description in `oauth-required-modal.tsx`
|
||||
- Hardcoded scope arrays instead of using `getScopesForService()` / `getCanonicalScopesForProvider()`
|
||||
- Missing scope description in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts`
|
||||
|
||||
**Suggestion** (minor improvements):
|
||||
- Better description text
|
||||
@@ -273,7 +278,8 @@ After fixing, confirm:
|
||||
- [ ] Validated wandConfig on timestamps and complex inputs
|
||||
- [ ] Validated tools.config mapping, tool selector, and type coercions
|
||||
- [ ] Validated block outputs match what tools return, with typed JSON where possible
|
||||
- [ ] Validated OAuth scopes alignment across auth.ts, oauth.ts, block, and modal (if OAuth)
|
||||
- [ ] Validated OAuth scopes use centralized utilities (getScopesForService, getCanonicalScopesForProvider) — no hardcoded arrays
|
||||
- [ ] Validated scope descriptions exist in `SCOPE_DESCRIPTIONS` within `lib/oauth/utils.ts` for all scopes
|
||||
- [ ] Validated pagination consistency across tools and block
|
||||
- [ ] Validated error handling (error checks, meaningful messages)
|
||||
- [ ] Validated registry entries (tools and block, alphabetical, correct imports)
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM oven/bun:1.3.9-alpine
|
||||
FROM oven/bun:1.3.10-alpine
|
||||
|
||||
# Install necessary packages for development
|
||||
RUN apk add --no-cache \
|
||||
|
||||
2
.github/workflows/docs-embeddings.yml
vendored
2
.github/workflows/docs-embeddings.yml
vendored
@@ -20,7 +20,7 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.9
|
||||
bun-version: 1.3.10
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
|
||||
4
.github/workflows/i18n.yml
vendored
4
.github/workflows/i18n.yml
vendored
@@ -23,7 +23,7 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.9
|
||||
bun-version: 1.3.10
|
||||
|
||||
- name: Cache Bun dependencies
|
||||
uses: actions/cache@v4
|
||||
@@ -122,7 +122,7 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.9
|
||||
bun-version: 1.3.10
|
||||
|
||||
- name: Cache Bun dependencies
|
||||
uses: actions/cache@v4
|
||||
|
||||
2
.github/workflows/migrations.yml
vendored
2
.github/workflows/migrations.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.9
|
||||
bun-version: 1.3.10
|
||||
|
||||
- name: Cache Bun dependencies
|
||||
uses: actions/cache@v4
|
||||
|
||||
2
.github/workflows/publish-cli.yml
vendored
2
.github/workflows/publish-cli.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.9
|
||||
bun-version: 1.3.10
|
||||
|
||||
- name: Setup Node.js for npm publishing
|
||||
uses: actions/setup-node@v4
|
||||
|
||||
2
.github/workflows/publish-ts-sdk.yml
vendored
2
.github/workflows/publish-ts-sdk.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.9
|
||||
bun-version: 1.3.10
|
||||
|
||||
- name: Setup Node.js for npm publishing
|
||||
uses: actions/setup-node@v4
|
||||
|
||||
12
.github/workflows/test-build.yml
vendored
12
.github/workflows/test-build.yml
vendored
@@ -19,7 +19,7 @@ jobs:
|
||||
- name: Setup Bun
|
||||
uses: oven-sh/setup-bun@v2
|
||||
with:
|
||||
bun-version: 1.3.9
|
||||
bun-version: 1.3.10
|
||||
|
||||
- name: Setup Node
|
||||
uses: actions/setup-node@v4
|
||||
@@ -90,6 +90,16 @@ jobs:
|
||||
|
||||
echo "✅ All feature flags are properly configured"
|
||||
|
||||
- name: Check subblock ID stability
|
||||
run: |
|
||||
if [ "${{ github.event_name }}" = "pull_request" ]; then
|
||||
BASE_REF="origin/${{ github.base_ref }}"
|
||||
git fetch --depth=1 origin "${{ github.base_ref }}" 2>/dev/null || true
|
||||
else
|
||||
BASE_REF="HEAD~1"
|
||||
fi
|
||||
bun run apps/sim/scripts/check-subblock-id-stability.ts "$BASE_REF"
|
||||
|
||||
- name: Lint code
|
||||
run: bun run lint:check
|
||||
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
import type React from 'react'
|
||||
import type { Root } from 'fumadocs-core/page-tree'
|
||||
import { findNeighbour } from 'fumadocs-core/page-tree'
|
||||
import type { ApiPageProps } from 'fumadocs-openapi/ui'
|
||||
import { createAPIPage } from 'fumadocs-openapi/ui'
|
||||
import { Pre } from 'fumadocs-ui/components/codeblock'
|
||||
import defaultMdxComponents from 'fumadocs-ui/mdx'
|
||||
import { DocsBody, DocsDescription, DocsPage, DocsTitle } from 'fumadocs-ui/page'
|
||||
@@ -12,28 +15,75 @@ import { LLMCopyButton } from '@/components/page-actions'
|
||||
import { StructuredData } from '@/components/structured-data'
|
||||
import { CodeBlock } from '@/components/ui/code-block'
|
||||
import { Heading } from '@/components/ui/heading'
|
||||
import { ResponseSection } from '@/components/ui/response-section'
|
||||
import { i18n } from '@/lib/i18n'
|
||||
import { getApiSpecContent, openapi } from '@/lib/openapi'
|
||||
import { type PageData, source } from '@/lib/source'
|
||||
|
||||
const SUPPORTED_LANGUAGES: Set<string> = new Set(i18n.languages)
|
||||
const BASE_URL = 'https://docs.sim.ai'
|
||||
|
||||
function resolveLangAndSlug(params: { slug?: string[]; lang: string }) {
|
||||
const isValidLang = SUPPORTED_LANGUAGES.has(params.lang)
|
||||
const lang = isValidLang ? params.lang : 'en'
|
||||
const slug = isValidLang ? params.slug : [params.lang, ...(params.slug ?? [])]
|
||||
return { lang, slug }
|
||||
}
|
||||
|
||||
const APIPage = createAPIPage(openapi, {
|
||||
playground: { enabled: false },
|
||||
content: {
|
||||
renderOperationLayout: async (slots) => {
|
||||
return (
|
||||
<div className='flex @4xl:flex-row flex-col @4xl:items-start gap-x-6 gap-y-4'>
|
||||
<div className='min-w-0 flex-1'>
|
||||
{slots.header}
|
||||
{slots.apiPlayground}
|
||||
{slots.authSchemes && <div className='api-section-divider'>{slots.authSchemes}</div>}
|
||||
{slots.paremeters}
|
||||
{slots.body && <div className='api-section-divider'>{slots.body}</div>}
|
||||
<ResponseSection>{slots.responses}</ResponseSection>
|
||||
{slots.callbacks}
|
||||
</div>
|
||||
<div className='@4xl:sticky @4xl:top-[calc(var(--fd-docs-row-1,2rem)+1rem)] @4xl:w-[400px]'>
|
||||
{slots.apiExample}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
},
|
||||
},
|
||||
})
|
||||
|
||||
export default async function Page(props: { params: Promise<{ slug?: string[]; lang: string }> }) {
|
||||
const params = await props.params
|
||||
const page = source.getPage(params.slug, params.lang)
|
||||
const { lang, slug } = resolveLangAndSlug(params)
|
||||
const page = source.getPage(slug, lang)
|
||||
if (!page) notFound()
|
||||
|
||||
const data = page.data as PageData
|
||||
const MDX = data.body
|
||||
const baseUrl = 'https://docs.sim.ai'
|
||||
const markdownContent = await data.getText('processed')
|
||||
const data = page.data as unknown as PageData & {
|
||||
_openapi?: { method?: string }
|
||||
getAPIPageProps?: () => ApiPageProps
|
||||
}
|
||||
const isOpenAPI = '_openapi' in data && data._openapi != null
|
||||
const isApiReference = slug?.some((s) => s === 'api-reference') ?? false
|
||||
|
||||
const pageTreeRecord = source.pageTree as Record<string, any>
|
||||
const pageTree =
|
||||
pageTreeRecord[params.lang] ?? pageTreeRecord.en ?? Object.values(pageTreeRecord)[0]
|
||||
const neighbours = pageTree ? findNeighbour(pageTree, page.url) : null
|
||||
const pageTreeRecord = source.pageTree as Record<string, Root>
|
||||
const pageTree = pageTreeRecord[lang] ?? pageTreeRecord.en ?? Object.values(pageTreeRecord)[0]
|
||||
const rawNeighbours = pageTree ? findNeighbour(pageTree, page.url) : null
|
||||
const neighbours = isApiReference
|
||||
? {
|
||||
previous: rawNeighbours?.previous?.url.includes('/api-reference/')
|
||||
? rawNeighbours.previous
|
||||
: undefined,
|
||||
next: rawNeighbours?.next?.url.includes('/api-reference/') ? rawNeighbours.next : undefined,
|
||||
}
|
||||
: rawNeighbours
|
||||
|
||||
const generateBreadcrumbs = () => {
|
||||
const breadcrumbs: Array<{ name: string; url: string }> = [
|
||||
{
|
||||
name: 'Home',
|
||||
url: baseUrl,
|
||||
url: BASE_URL,
|
||||
},
|
||||
]
|
||||
|
||||
@@ -41,7 +91,7 @@ export default async function Page(props: { params: Promise<{ slug?: string[]; l
|
||||
let currentPath = ''
|
||||
|
||||
urlParts.forEach((part, index) => {
|
||||
if (index === 0 && ['en', 'es', 'fr', 'de', 'ja', 'zh'].includes(part)) {
|
||||
if (index === 0 && SUPPORTED_LANGUAGES.has(part)) {
|
||||
currentPath = `/${part}`
|
||||
return
|
||||
}
|
||||
@@ -56,12 +106,12 @@ export default async function Page(props: { params: Promise<{ slug?: string[]; l
|
||||
if (index === urlParts.length - 1) {
|
||||
breadcrumbs.push({
|
||||
name: data.title,
|
||||
url: `${baseUrl}${page.url}`,
|
||||
url: `${BASE_URL}${page.url}`,
|
||||
})
|
||||
} else {
|
||||
breadcrumbs.push({
|
||||
name: name,
|
||||
url: `${baseUrl}${currentPath}`,
|
||||
url: `${BASE_URL}${currentPath}`,
|
||||
})
|
||||
}
|
||||
})
|
||||
@@ -73,7 +123,6 @@ export default async function Page(props: { params: Promise<{ slug?: string[]; l
|
||||
|
||||
const CustomFooter = () => (
|
||||
<div className='mt-12'>
|
||||
{/* Navigation links */}
|
||||
<div className='flex items-center justify-between py-8'>
|
||||
{neighbours?.previous ? (
|
||||
<Link
|
||||
@@ -100,10 +149,8 @@ export default async function Page(props: { params: Promise<{ slug?: string[]; l
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Divider line */}
|
||||
<div className='border-border border-t' />
|
||||
|
||||
{/* Social icons */}
|
||||
<div className='flex items-center gap-4 py-6'>
|
||||
<Link
|
||||
href='https://x.com/simdotai'
|
||||
@@ -169,13 +216,69 @@ export default async function Page(props: { params: Promise<{ slug?: string[]; l
|
||||
</div>
|
||||
)
|
||||
|
||||
if (isOpenAPI && data.getAPIPageProps) {
|
||||
const apiProps = data.getAPIPageProps()
|
||||
const apiPageContent = getApiSpecContent(
|
||||
data.title,
|
||||
data.description,
|
||||
apiProps.operations ?? []
|
||||
)
|
||||
|
||||
return (
|
||||
<>
|
||||
<StructuredData
|
||||
title={data.title}
|
||||
description={data.description || ''}
|
||||
url={`${BASE_URL}${page.url}`}
|
||||
lang={lang}
|
||||
breadcrumb={breadcrumbs}
|
||||
/>
|
||||
<DocsPage
|
||||
toc={data.toc}
|
||||
breadcrumb={{
|
||||
enabled: false,
|
||||
}}
|
||||
tableOfContent={{
|
||||
style: 'clerk',
|
||||
enabled: false,
|
||||
}}
|
||||
tableOfContentPopover={{
|
||||
style: 'clerk',
|
||||
enabled: false,
|
||||
}}
|
||||
footer={{
|
||||
enabled: true,
|
||||
component: <CustomFooter />,
|
||||
}}
|
||||
>
|
||||
<div className='api-page-header relative mt-6 sm:mt-0'>
|
||||
<div className='absolute top-1 right-0 flex items-center gap-2'>
|
||||
<div className='hidden sm:flex'>
|
||||
<LLMCopyButton content={apiPageContent} />
|
||||
</div>
|
||||
<PageNavigationArrows previous={neighbours?.previous} next={neighbours?.next} />
|
||||
</div>
|
||||
<DocsTitle>{data.title}</DocsTitle>
|
||||
<DocsDescription>{data.description}</DocsDescription>
|
||||
</div>
|
||||
<DocsBody>
|
||||
<APIPage {...apiProps} />
|
||||
</DocsBody>
|
||||
</DocsPage>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
const MDX = data.body
|
||||
const markdownContent = await data.getText('processed')
|
||||
|
||||
return (
|
||||
<>
|
||||
<StructuredData
|
||||
title={data.title}
|
||||
description={data.description || ''}
|
||||
url={`${baseUrl}${page.url}`}
|
||||
lang={params.lang}
|
||||
url={`${BASE_URL}${page.url}`}
|
||||
lang={lang}
|
||||
breadcrumb={breadcrumbs}
|
||||
/>
|
||||
<DocsPage
|
||||
@@ -252,14 +355,14 @@ export async function generateMetadata(props: {
|
||||
params: Promise<{ slug?: string[]; lang: string }>
|
||||
}) {
|
||||
const params = await props.params
|
||||
const page = source.getPage(params.slug, params.lang)
|
||||
const { lang, slug } = resolveLangAndSlug(params)
|
||||
const page = source.getPage(slug, lang)
|
||||
if (!page) notFound()
|
||||
|
||||
const data = page.data as PageData
|
||||
const baseUrl = 'https://docs.sim.ai'
|
||||
const fullUrl = `${baseUrl}${page.url}`
|
||||
const data = page.data as unknown as PageData
|
||||
const fullUrl = `${BASE_URL}${page.url}`
|
||||
|
||||
const ogImageUrl = `${baseUrl}/api/og?title=${encodeURIComponent(data.title)}`
|
||||
const ogImageUrl = `${BASE_URL}/api/og?title=${encodeURIComponent(data.title)}`
|
||||
|
||||
return {
|
||||
title: data.title,
|
||||
@@ -286,10 +389,10 @@ export async function generateMetadata(props: {
|
||||
url: fullUrl,
|
||||
siteName: 'Sim Documentation',
|
||||
type: 'article',
|
||||
locale: params.lang === 'en' ? 'en_US' : `${params.lang}_${params.lang.toUpperCase()}`,
|
||||
locale: lang === 'en' ? 'en_US' : `${lang}_${lang.toUpperCase()}`,
|
||||
alternateLocale: ['en', 'es', 'fr', 'de', 'ja', 'zh']
|
||||
.filter((lang) => lang !== params.lang)
|
||||
.map((lang) => (lang === 'en' ? 'en_US' : `${lang}_${lang.toUpperCase()}`)),
|
||||
.filter((l) => l !== lang)
|
||||
.map((l) => (l === 'en' ? 'en_US' : `${l}_${l.toUpperCase()}`)),
|
||||
images: [
|
||||
{
|
||||
url: ogImageUrl,
|
||||
@@ -323,13 +426,13 @@ export async function generateMetadata(props: {
|
||||
alternates: {
|
||||
canonical: fullUrl,
|
||||
languages: {
|
||||
'x-default': `${baseUrl}${page.url.replace(`/${params.lang}`, '')}`,
|
||||
en: `${baseUrl}${page.url.replace(`/${params.lang}`, '')}`,
|
||||
es: `${baseUrl}/es${page.url.replace(`/${params.lang}`, '')}`,
|
||||
fr: `${baseUrl}/fr${page.url.replace(`/${params.lang}`, '')}`,
|
||||
de: `${baseUrl}/de${page.url.replace(`/${params.lang}`, '')}`,
|
||||
ja: `${baseUrl}/ja${page.url.replace(`/${params.lang}`, '')}`,
|
||||
zh: `${baseUrl}/zh${page.url.replace(`/${params.lang}`, '')}`,
|
||||
'x-default': `${BASE_URL}${page.url.replace(`/${lang}`, '')}`,
|
||||
en: `${BASE_URL}${page.url.replace(`/${lang}`, '')}`,
|
||||
es: `${BASE_URL}/es${page.url.replace(`/${lang}`, '')}`,
|
||||
fr: `${BASE_URL}/fr${page.url.replace(`/${lang}`, '')}`,
|
||||
de: `${BASE_URL}/de${page.url.replace(`/${lang}`, '')}`,
|
||||
ja: `${BASE_URL}/ja${page.url.replace(`/${lang}`, '')}`,
|
||||
zh: `${BASE_URL}/zh${page.url.replace(`/${lang}`, '')}`,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
@@ -55,8 +55,11 @@ type LayoutProps = {
|
||||
params: Promise<{ lang: string }>
|
||||
}
|
||||
|
||||
const SUPPORTED_LANGUAGES: Set<string> = new Set(i18n.languages)
|
||||
|
||||
export default async function Layout({ children, params }: LayoutProps) {
|
||||
const { lang } = await params
|
||||
const { lang: rawLang } = await params
|
||||
const lang = SUPPORTED_LANGUAGES.has(rawLang) ? rawLang : 'en'
|
||||
|
||||
const structuredData = {
|
||||
'@context': 'https://schema.org',
|
||||
@@ -107,6 +110,7 @@ export default async function Layout({ children, params }: LayoutProps) {
|
||||
title: <SimLogoFull className='h-7 w-auto' />,
|
||||
}}
|
||||
sidebar={{
|
||||
tabs: false,
|
||||
defaultOpenLevel: 0,
|
||||
collapsible: false,
|
||||
footer: null,
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
@import "tailwindcss";
|
||||
@import "fumadocs-ui/css/neutral.css";
|
||||
@import "fumadocs-ui/css/preset.css";
|
||||
@import "fumadocs-openapi/css/preset.css";
|
||||
|
||||
/* Prevent overscroll bounce effect on the page */
|
||||
html,
|
||||
@@ -8,18 +9,12 @@ body {
|
||||
overscroll-behavior: none;
|
||||
}
|
||||
|
||||
/* Reserve scrollbar space to prevent layout jitter between pages */
|
||||
html {
|
||||
scrollbar-gutter: stable;
|
||||
}
|
||||
|
||||
@theme {
|
||||
--color-fd-primary: #33c482; /* Green from Sim logo */
|
||||
--font-geist-sans: var(--font-geist-sans);
|
||||
--font-geist-mono: var(--font-geist-mono);
|
||||
}
|
||||
|
||||
/* Ensure primary color is set in both light and dark modes */
|
||||
:root {
|
||||
--color-fd-primary: #33c482;
|
||||
}
|
||||
|
||||
.dark {
|
||||
--color-fd-primary: #33c482;
|
||||
}
|
||||
|
||||
@@ -34,12 +29,6 @@ body {
|
||||
"Liberation Mono", "Courier New", monospace;
|
||||
}
|
||||
|
||||
/* Target any potential border classes */
|
||||
* {
|
||||
--fd-border-sidebar: transparent !important;
|
||||
}
|
||||
|
||||
/* Override any CSS custom properties for borders */
|
||||
:root {
|
||||
--fd-border: transparent !important;
|
||||
--fd-border-sidebar: transparent !important;
|
||||
@@ -86,7 +75,6 @@ body {
|
||||
[data-sidebar-container],
|
||||
#nd-sidebar {
|
||||
background: transparent !important;
|
||||
background-color: transparent !important;
|
||||
border: none !important;
|
||||
--color-fd-muted: transparent !important;
|
||||
--color-fd-card: transparent !important;
|
||||
@@ -96,9 +84,7 @@ body {
|
||||
aside[data-sidebar],
|
||||
aside#nd-sidebar {
|
||||
background: transparent !important;
|
||||
background-color: transparent !important;
|
||||
border: none !important;
|
||||
border-right: none !important;
|
||||
}
|
||||
|
||||
/* Fumadocs v16: Add sidebar placeholder styling for grid area */
|
||||
@@ -157,7 +143,6 @@ aside#nd-sidebar {
|
||||
#nd-sidebar > div {
|
||||
padding: 0.5rem 12px 12px;
|
||||
background: transparent !important;
|
||||
background-color: transparent !important;
|
||||
}
|
||||
|
||||
/* Override sidebar item styling to match Raindrop */
|
||||
@@ -434,10 +419,6 @@ aside[data-sidebar],
|
||||
#nd-sidebar,
|
||||
#nd-sidebar * {
|
||||
border: none !important;
|
||||
border-right: none !important;
|
||||
border-left: none !important;
|
||||
border-top: none !important;
|
||||
border-bottom: none !important;
|
||||
}
|
||||
|
||||
/* Override fumadocs background colors for sidebar */
|
||||
@@ -447,7 +428,6 @@ aside[data-sidebar],
|
||||
--color-fd-muted: transparent !important;
|
||||
--color-fd-secondary: transparent !important;
|
||||
background: transparent !important;
|
||||
background-color: transparent !important;
|
||||
}
|
||||
|
||||
/* Force normal text flow in sidebar */
|
||||
@@ -564,16 +544,682 @@ main[data-main] {
|
||||
padding-top: 1.5rem !important;
|
||||
}
|
||||
|
||||
/* Override Fumadocs default content padding */
|
||||
article[data-content],
|
||||
div[data-content] {
|
||||
padding-top: 1.5rem !important;
|
||||
}
|
||||
|
||||
/* Remove any unwanted borders/outlines from video elements */
|
||||
/* Remove any unwanted outlines from video elements */
|
||||
video {
|
||||
outline: none !important;
|
||||
border-style: solid !important;
|
||||
}
|
||||
|
||||
/* API Reference Pages — Mintlify-style overrides */
|
||||
|
||||
/* OpenAPI pages: span main + TOC grid columns for wide two-column layout.
|
||||
The grid has columns: spacer | sidebar | main | toc | spacer.
|
||||
By spanning columns 3-4, the article fills both main and toc areas,
|
||||
while the grid structure stays identical to non-OpenAPI pages (no jitter). */
|
||||
#nd-page:has(.api-page-header) {
|
||||
grid-column: 3 / span 2 !important;
|
||||
max-width: 1400px !important;
|
||||
}
|
||||
|
||||
/* Hide the empty TOC aside on OpenAPI pages so it doesn't overlay content */
|
||||
#nd-docs-layout:has(#nd-page .api-page-header) #nd-toc {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Hide the default "Response Body" heading rendered by fumadocs-openapi */
|
||||
.response-section-wrapper > .response-section-content > h2,
|
||||
.response-section-wrapper > .response-section-content > h3 {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Hide default accordion triggers (status code rows) — we show our own dropdown */
|
||||
.response-section-wrapper [data-orientation="vertical"] > [data-state] > h3 {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Ensure API reference pages use the same font as the rest of the docs */
|
||||
#nd-page:has(.api-page-header),
|
||||
#nd-page:has(.api-page-header) h2,
|
||||
#nd-page:has(.api-page-header) h3,
|
||||
#nd-page:has(.api-page-header) h4,
|
||||
#nd-page:has(.api-page-header) p,
|
||||
#nd-page:has(.api-page-header) span,
|
||||
#nd-page:has(.api-page-header) div,
|
||||
#nd-page:has(.api-page-header) label,
|
||||
#nd-page:has(.api-page-header) button {
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont,
|
||||
"Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
|
||||
}
|
||||
|
||||
/* Method badge pills in page content — colored background pills */
|
||||
#nd-page span.font-mono.font-medium[class*="text-green"] {
|
||||
background-color: rgb(220 252 231 / 0.6);
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
html.dark #nd-page span.font-mono.font-medium[class*="text-green"] {
|
||||
background-color: rgb(34 197 94 / 0.15);
|
||||
}
|
||||
|
||||
#nd-page span.font-mono.font-medium[class*="text-blue"] {
|
||||
background-color: rgb(219 234 254 / 0.6);
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
html.dark #nd-page span.font-mono.font-medium[class*="text-blue"] {
|
||||
background-color: rgb(59 130 246 / 0.15);
|
||||
}
|
||||
|
||||
#nd-page span.font-mono.font-medium[class*="text-orange"] {
|
||||
background-color: rgb(255 237 213 / 0.6);
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
html.dark #nd-page span.font-mono.font-medium[class*="text-orange"] {
|
||||
background-color: rgb(249 115 22 / 0.15);
|
||||
}
|
||||
|
||||
#nd-page span.font-mono.font-medium[class*="text-red"] {
|
||||
background-color: rgb(254 226 226 / 0.6);
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.75rem;
|
||||
}
|
||||
html.dark #nd-page span.font-mono.font-medium[class*="text-red"] {
|
||||
background-color: rgb(239 68 68 / 0.15);
|
||||
}
|
||||
|
||||
/* Sidebar links with method badges — flex for vertical centering */
|
||||
#nd-sidebar a:has(span.font-mono.font-medium) {
|
||||
display: flex !important;
|
||||
align-items: center !important;
|
||||
gap: 6px;
|
||||
}
|
||||
|
||||
/* Sidebar method badges — ensure proper inline flex display */
|
||||
#nd-sidebar a span.font-mono.font-medium {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
min-width: 2.25rem;
|
||||
font-size: 10px !important;
|
||||
line-height: 1 !important;
|
||||
padding: 2.5px 4px;
|
||||
border-radius: 3px;
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
/* Sidebar GET badges */
|
||||
#nd-sidebar a span.font-mono.font-medium[class*="text-green"] {
|
||||
background-color: rgb(220 252 231 / 0.6);
|
||||
}
|
||||
html.dark #nd-sidebar a span.font-mono.font-medium[class*="text-green"] {
|
||||
background-color: rgb(34 197 94 / 0.15);
|
||||
}
|
||||
|
||||
/* Sidebar POST badges */
|
||||
#nd-sidebar a span.font-mono.font-medium[class*="text-blue"] {
|
||||
background-color: rgb(219 234 254 / 0.6);
|
||||
}
|
||||
html.dark #nd-sidebar a span.font-mono.font-medium[class*="text-blue"] {
|
||||
background-color: rgb(59 130 246 / 0.15);
|
||||
}
|
||||
|
||||
/* Sidebar PUT badges */
|
||||
#nd-sidebar a span.font-mono.font-medium[class*="text-orange"] {
|
||||
background-color: rgb(255 237 213 / 0.6);
|
||||
}
|
||||
html.dark #nd-sidebar a span.font-mono.font-medium[class*="text-orange"] {
|
||||
background-color: rgb(249 115 22 / 0.15);
|
||||
}
|
||||
|
||||
/* Sidebar DELETE badges */
|
||||
#nd-sidebar a span.font-mono.font-medium[class*="text-red"] {
|
||||
background-color: rgb(254 226 226 / 0.6);
|
||||
}
|
||||
html.dark #nd-sidebar a span.font-mono.font-medium[class*="text-red"] {
|
||||
background-color: rgb(239 68 68 / 0.15);
|
||||
}
|
||||
|
||||
/* Code block containers — match regular docs styling */
|
||||
#nd-page:has(.api-page-header) figure.shiki {
|
||||
border-radius: 0.75rem !important;
|
||||
background-color: var(--color-fd-card) !important;
|
||||
}
|
||||
|
||||
/* Hide "Filter Properties" search bar everywhere — main page and popovers */
|
||||
input[placeholder="Filter Properties"] {
|
||||
display: none !important;
|
||||
}
|
||||
div:has(> input[placeholder="Filter Properties"]) {
|
||||
display: none !important;
|
||||
}
|
||||
/* Remove top border on first visible property after hidden Filter Properties */
|
||||
div:has(> input[placeholder="Filter Properties"]) + .text-sm.border-t {
|
||||
border-top: none !important;
|
||||
}
|
||||
|
||||
/* Hide "TypeScript Definitions" copy panel on API pages */
|
||||
#nd-page:has(.api-page-header) div.not-prose.rounded-xl.border.p-3.mb-4 {
|
||||
display: none !important;
|
||||
}
|
||||
#nd-page:has(.api-page-header) div.not-prose.rounded-xl.border.p-3:has(> div > p.font-medium) {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Hide info tags (Format, Default, etc.) everywhere — main page and popovers */
|
||||
div.flex.flex-row.gap-2.flex-wrap.not-prose:has(> div.bg-fd-secondary) {
|
||||
display: none !important;
|
||||
}
|
||||
div.flex.flex-row.items-start.bg-fd-secondary.border.rounded-lg.text-xs {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Method+path bar — cleaner, lighter styling like Gumloop.
|
||||
Override bg-fd-card CSS variable directly for reliability. */
|
||||
#nd-page:has(.api-page-header) div.flex.flex-row.items-center.rounded-xl.border.not-prose {
|
||||
--color-fd-card: rgb(249 250 251) !important;
|
||||
background-color: rgb(249 250 251) !important;
|
||||
border-color: rgb(229 231 235) !important;
|
||||
}
|
||||
html.dark
|
||||
#nd-page:has(.api-page-header)
|
||||
div.flex.flex-row.items-center.rounded-xl.border.not-prose {
|
||||
--color-fd-card: rgb(24 24 27) !important;
|
||||
background-color: rgb(24 24 27) !important;
|
||||
border-color: rgb(63 63 70) !important;
|
||||
}
|
||||
/* Method badge inside path bar — cleaner sans-serif, softer colors */
|
||||
#nd-page:has(.api-page-header)
|
||||
div.flex.flex-row.items-center.rounded-xl.border.not-prose
|
||||
span.font-mono.font-medium {
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif !important;
|
||||
font-weight: 600 !important;
|
||||
font-size: 0.6875rem !important;
|
||||
letter-spacing: 0.025em;
|
||||
text-transform: uppercase;
|
||||
}
|
||||
/* POST — softer blue */
|
||||
#nd-page:has(.api-page-header)
|
||||
div.flex.flex-row.items-center.rounded-xl.border.not-prose
|
||||
span.font-mono.font-medium[class*="text-blue"] {
|
||||
color: rgb(37 99 235) !important;
|
||||
background-color: rgb(219 234 254 / 0.7) !important;
|
||||
}
|
||||
html.dark
|
||||
#nd-page:has(.api-page-header)
|
||||
div.flex.flex-row.items-center.rounded-xl.border.not-prose
|
||||
span.font-mono.font-medium[class*="text-blue"] {
|
||||
color: rgb(96 165 250) !important;
|
||||
background-color: rgb(59 130 246 / 0.15) !important;
|
||||
}
|
||||
/* GET — softer green */
|
||||
#nd-page:has(.api-page-header)
|
||||
div.flex.flex-row.items-center.rounded-xl.border.not-prose
|
||||
span.font-mono.font-medium[class*="text-green"] {
|
||||
color: rgb(22 163 74) !important;
|
||||
background-color: rgb(220 252 231 / 0.7) !important;
|
||||
}
|
||||
html.dark
|
||||
#nd-page:has(.api-page-header)
|
||||
div.flex.flex-row.items-center.rounded-xl.border.not-prose
|
||||
span.font-mono.font-medium[class*="text-green"] {
|
||||
color: rgb(74 222 128) !important;
|
||||
background-color: rgb(34 197 94 / 0.15) !important;
|
||||
}
|
||||
|
||||
/* Path text inside method+path bar — monospace, bright like Gumloop */
|
||||
#nd-page:has(.api-page-header) div.flex.flex-row.items-center.rounded-xl.border.not-prose code {
|
||||
color: rgb(55 65 81) !important;
|
||||
background: none !important;
|
||||
border: none !important;
|
||||
padding: 0 !important;
|
||||
font-size: 0.8125rem !important;
|
||||
}
|
||||
html.dark
|
||||
#nd-page:has(.api-page-header)
|
||||
div.flex.flex-row.items-center.rounded-xl.border.not-prose
|
||||
code {
|
||||
color: rgb(229 231 235) !important;
|
||||
}
|
||||
|
||||
/* Inline code in API pages — neutral color instead of red.
|
||||
Exclude code inside the method+path bar (handled above). */
|
||||
#nd-page:has(.api-page-header) .prose :not(pre) > code {
|
||||
color: rgb(79 70 229) !important;
|
||||
}
|
||||
html.dark #nd-page:has(.api-page-header) .prose :not(pre) > code {
|
||||
color: rgb(165 180 252) !important;
|
||||
}
|
||||
|
||||
/* Response Section — custom dropdown-based rendering (Mintlify style) */
|
||||
|
||||
/* Hide divider lines between accordion items */
|
||||
.response-section-wrapper [data-orientation="vertical"].divide-y > * {
|
||||
border-top-width: 0 !important;
|
||||
border-bottom-width: 0 !important;
|
||||
}
|
||||
.response-section-wrapper [data-orientation="vertical"].divide-y {
|
||||
border-top: none !important;
|
||||
}
|
||||
|
||||
/* Remove content type labels inside accordion items (we show one in the header) */
|
||||
.response-section-wrapper [data-orientation="vertical"] p.not-prose:has(code.text-xs) {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Hide the top-level response description (e.g. "Execution was successfully cancelled.")
|
||||
but NOT field descriptions inside Schema which also use prose-no-margin.
|
||||
The response description is a direct child of AccordionContent (role=region) with mb-2. */
|
||||
.response-section-wrapper [data-orientation="vertical"] [role="region"] > .prose-no-margin.mb-2,
|
||||
.response-section-wrapper
|
||||
[data-orientation="vertical"]
|
||||
[role="region"]
|
||||
> div
|
||||
> .prose-no-margin.mb-2 {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Remove left padding on accordion content so it aligns with Path Parameters */
|
||||
.response-section-wrapper [data-orientation="vertical"] [role="region"] {
|
||||
padding-inline-start: 0 !important;
|
||||
}
|
||||
|
||||
/* Response section header */
|
||||
.response-section-header {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
margin-top: 1.75rem;
|
||||
margin-bottom: 0.5rem;
|
||||
}
|
||||
|
||||
.response-section-title {
|
||||
font-size: 1.5rem;
|
||||
font-weight: 600;
|
||||
margin: 0;
|
||||
color: var(--color-fd-foreground);
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, -apple-system, sans-serif;
|
||||
}
|
||||
|
||||
.response-section-meta {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
margin-left: auto;
|
||||
}
|
||||
|
||||
/* Status code dropdown */
|
||||
.response-section-dropdown-wrapper {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.response-section-dropdown-trigger {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
padding: 0.125rem 0.25rem;
|
||||
font-size: 0.875rem;
|
||||
font-weight: 500;
|
||||
color: var(--color-fd-muted-foreground);
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
border-radius: 0.25rem;
|
||||
transition: color 0.15s;
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
.response-section-dropdown-trigger:hover {
|
||||
color: var(--color-fd-foreground);
|
||||
}
|
||||
|
||||
.response-section-chevron {
|
||||
width: 0.75rem;
|
||||
height: 0.75rem;
|
||||
transition: transform 0.15s;
|
||||
}
|
||||
.response-section-chevron-open {
|
||||
transform: rotate(180deg);
|
||||
}
|
||||
|
||||
.response-section-dropdown-menu {
|
||||
position: absolute;
|
||||
top: calc(100% + 0.25rem);
|
||||
left: 0;
|
||||
z-index: 50;
|
||||
min-width: 5rem;
|
||||
background-color: white;
|
||||
border: 1px solid rgb(229 231 235);
|
||||
border-radius: 0.5rem;
|
||||
box-shadow:
|
||||
0 4px 6px -1px rgb(0 0 0 / 0.1),
|
||||
0 2px 4px -2px rgb(0 0 0 / 0.1);
|
||||
padding: 0.25rem;
|
||||
overflow: hidden;
|
||||
}
|
||||
html.dark .response-section-dropdown-menu {
|
||||
background-color: rgb(24 24 27);
|
||||
border-color: rgb(63 63 70);
|
||||
box-shadow: 0 4px 6px -1px rgb(0 0 0 / 0.3);
|
||||
}
|
||||
|
||||
.response-section-dropdown-item {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
width: 100%;
|
||||
padding: 0.375rem 0.5rem;
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-fd-muted-foreground);
|
||||
background: none;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
border-radius: 0.25rem;
|
||||
transition:
|
||||
background-color 0.1s,
|
||||
color 0.1s;
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
.response-section-dropdown-item:hover {
|
||||
background-color: rgb(243 244 246);
|
||||
color: var(--color-fd-foreground);
|
||||
}
|
||||
html.dark .response-section-dropdown-item:hover {
|
||||
background-color: rgb(39 39 42);
|
||||
}
|
||||
.response-section-dropdown-item-selected {
|
||||
color: var(--color-fd-foreground);
|
||||
}
|
||||
|
||||
.response-section-check {
|
||||
width: 0.875rem;
|
||||
height: 0.875rem;
|
||||
}
|
||||
|
||||
.response-section-content-type {
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-fd-muted-foreground);
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
|
||||
/* Response schema container — remove border to match Path Parameters style */
|
||||
.response-section-wrapper [data-orientation="vertical"] .border.px-3.py-2.rounded-lg {
|
||||
border: none !important;
|
||||
padding: 0 !important;
|
||||
border-radius: 0 !important;
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
/* Property row — reorder: name (1) → type badge (2) → required badge (3) */
|
||||
#nd-page:has(.api-page-header) .flex.flex-wrap.items-center.gap-3.not-prose {
|
||||
display: flex;
|
||||
flex-wrap: wrap;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
/* Name span — order 1 */
|
||||
#nd-page:has(.api-page-header)
|
||||
.flex.flex-wrap.items-center.gap-3.not-prose
|
||||
> span.font-medium.font-mono.text-fd-primary {
|
||||
order: 1;
|
||||
}
|
||||
|
||||
/* Type badge — order 2, grey pill like Mintlify */
|
||||
#nd-page:has(.api-page-header)
|
||||
.flex.flex-wrap.items-center.gap-3.not-prose
|
||||
> span.text-sm.font-mono.text-fd-muted-foreground {
|
||||
order: 2;
|
||||
background-color: rgb(240 240 243);
|
||||
color: rgb(100 100 110);
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.6875rem;
|
||||
line-height: 1.25rem;
|
||||
font-weight: 500;
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
html.dark
|
||||
#nd-page:has(.api-page-header)
|
||||
.flex.flex-wrap.items-center.gap-3.not-prose
|
||||
> span.text-sm.font-mono.text-fd-muted-foreground {
|
||||
background-color: rgb(39 39 42);
|
||||
color: rgb(212 212 216);
|
||||
}
|
||||
|
||||
/* Hide the "*" inside the name span — we'll add "required" as a ::after on the flex row */
|
||||
#nd-page:has(.api-page-header) span.font-medium.font-mono.text-fd-primary > span.text-red-400 {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Required badge — order 3, light red pill */
|
||||
#nd-page:has(.api-page-header)
|
||||
.flex.flex-wrap.items-center.gap-3.not-prose:has(span.text-red-400)::after {
|
||||
content: "required";
|
||||
order: 3;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
background-color: rgb(254 235 235);
|
||||
color: rgb(220 38 38);
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.6875rem;
|
||||
line-height: 1.25rem;
|
||||
font-weight: 500;
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
html.dark
|
||||
#nd-page:has(.api-page-header)
|
||||
.flex.flex-wrap.items-center.gap-3.not-prose:has(span.text-red-400)::after {
|
||||
background-color: rgb(127 29 29 / 0.2);
|
||||
color: rgb(252 165 165);
|
||||
}
|
||||
|
||||
/* Optional "?" indicator — hide it */
|
||||
#nd-page:has(.api-page-header)
|
||||
span.font-medium.font-mono.text-fd-primary
|
||||
> span.text-fd-muted-foreground {
|
||||
display: none;
|
||||
}
|
||||
|
||||
/* Hide the auth scheme type label (e.g. "apiKey") next to Authorization heading */
|
||||
#nd-page:has(.api-page-header) .flex.items-start.justify-between.gap-2 > div.not-prose {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Auth property — replace "<token>" with "string" badge, add "header" and "required" badges.
|
||||
Auth properties use my-4 (vs py-4 for regular properties). */
|
||||
|
||||
/* Auth property flex row — name: order 1, type: order 2, ::before "header": order 3, ::after "required": order 4 */
|
||||
#nd-page:has(.api-page-header)
|
||||
div.my-4
|
||||
> .flex.flex-wrap.items-center.gap-3.not-prose
|
||||
> span.font-medium.font-mono.text-fd-primary {
|
||||
order: 1;
|
||||
}
|
||||
#nd-page:has(.api-page-header)
|
||||
div.my-4
|
||||
> .flex.flex-wrap.items-center.gap-3.not-prose
|
||||
> span.text-sm.font-mono.text-fd-muted-foreground {
|
||||
order: 2;
|
||||
font-size: 0;
|
||||
padding: 0 !important;
|
||||
background: none !important;
|
||||
line-height: 0;
|
||||
}
|
||||
#nd-page:has(.api-page-header)
|
||||
div.my-4
|
||||
> .flex.flex-wrap.items-center.gap-3.not-prose
|
||||
> span.text-sm.font-mono.text-fd-muted-foreground::after {
|
||||
content: "string";
|
||||
font-size: 0.6875rem;
|
||||
line-height: 1.25rem;
|
||||
font-weight: 500;
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
background-color: rgb(240 240 243);
|
||||
color: rgb(100 100 110);
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
}
|
||||
html.dark
|
||||
#nd-page:has(.api-page-header)
|
||||
div.my-4
|
||||
> .flex.flex-wrap.items-center.gap-3.not-prose
|
||||
> span.text-sm.font-mono.text-fd-muted-foreground::after {
|
||||
background-color: rgb(39 39 42);
|
||||
color: rgb(212 212 216);
|
||||
}
|
||||
|
||||
/* "header" badge via ::before on the auth flex row */
|
||||
#nd-page:has(.api-page-header) div.my-4 > .flex.flex-wrap.items-center.gap-3.not-prose::before {
|
||||
content: "header";
|
||||
order: 3;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
background-color: rgb(240 240 243);
|
||||
color: rgb(100 100 110);
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.6875rem;
|
||||
line-height: 1.25rem;
|
||||
font-weight: 500;
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
html.dark
|
||||
#nd-page:has(.api-page-header)
|
||||
div.my-4
|
||||
> .flex.flex-wrap.items-center.gap-3.not-prose::before {
|
||||
background-color: rgb(39 39 42);
|
||||
color: rgb(212 212 216);
|
||||
}
|
||||
|
||||
/* "required" badge via ::after on the auth flex row — light red pill */
|
||||
#nd-page:has(.api-page-header) div.my-4 > .flex.flex-wrap.items-center.gap-3.not-prose::after {
|
||||
content: "required";
|
||||
order: 4;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
background-color: rgb(254 235 235);
|
||||
color: rgb(220 38 38);
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.6875rem;
|
||||
line-height: 1.25rem;
|
||||
font-weight: 500;
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
html.dark
|
||||
#nd-page:has(.api-page-header)
|
||||
div.my-4
|
||||
> .flex.flex-wrap.items-center.gap-3.not-prose::after {
|
||||
background-color: rgb(127 29 29 / 0.2);
|
||||
color: rgb(252 165 165);
|
||||
}
|
||||
|
||||
/* Hide "In: header" text below auth property — redundant with the header badge */
|
||||
#nd-page:has(.api-page-header) div.my-4 .prose-no-margin p:has(> code) {
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
/* Section dividers — bottom border after Authorization and Body sections. */
|
||||
.api-section-divider {
|
||||
padding-bottom: 0.5rem;
|
||||
border-bottom: 1px solid rgb(229 231 235 / 0.6);
|
||||
}
|
||||
html.dark .api-section-divider {
|
||||
border-bottom-color: rgb(255 255 255 / 0.07);
|
||||
}
|
||||
|
||||
/* Property rows — breathing room like Mintlify.
|
||||
Regular properties use border-t py-4; auth properties use border-t my-4. */
|
||||
#nd-page:has(.api-page-header) .text-sm.border-t.py-4 {
|
||||
padding-top: 1.25rem !important;
|
||||
padding-bottom: 1.25rem !important;
|
||||
}
|
||||
#nd-page:has(.api-page-header) .text-sm.border-t.my-4 {
|
||||
margin-top: 1.25rem !important;
|
||||
margin-bottom: 1.25rem !important;
|
||||
padding-top: 1.25rem;
|
||||
}
|
||||
|
||||
/* Divider lines between fields — very subtle like Mintlify */
|
||||
#nd-page:has(.api-page-header) .text-sm.border-t {
|
||||
border-color: rgb(229 231 235 / 0.6);
|
||||
}
|
||||
html.dark #nd-page:has(.api-page-header) .text-sm.border-t {
|
||||
border-color: rgb(255 255 255 / 0.07);
|
||||
}
|
||||
|
||||
/* Body/Callback section "application/json" label — remove inline code styling */
|
||||
#nd-page:has(.api-page-header) .flex.gap-2.items-center.justify-between p.not-prose code.text-xs,
|
||||
#nd-page:has(.api-page-header) .flex.justify-between.gap-2.items-end p.not-prose code.text-xs {
|
||||
background: none !important;
|
||||
border: none !important;
|
||||
padding: 0 !important;
|
||||
color: var(--color-fd-muted-foreground) !important;
|
||||
font-size: 0.875rem !important;
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif !important;
|
||||
}
|
||||
|
||||
/* Object/array type triggers in property rows — order 2 + badge chip styling */
|
||||
#nd-page:has(.api-page-header) .flex.flex-wrap.items-center.gap-3.not-prose > button,
|
||||
#nd-page:has(.api-page-header) .flex.flex-wrap.items-center.gap-3.not-prose > span:has(> button) {
|
||||
order: 2;
|
||||
background-color: rgb(240 240 243);
|
||||
color: rgb(100 100 110);
|
||||
padding: 0.125rem 0.5rem;
|
||||
border-radius: 0.375rem;
|
||||
font-size: 0.6875rem;
|
||||
line-height: 1.25rem;
|
||||
font-weight: 500;
|
||||
font-family: var(--font-geist-sans), ui-sans-serif, system-ui, sans-serif;
|
||||
}
|
||||
html.dark #nd-page:has(.api-page-header) .flex.flex-wrap.items-center.gap-3.not-prose > button,
|
||||
html.dark
|
||||
#nd-page:has(.api-page-header)
|
||||
.flex.flex-wrap.items-center.gap-3.not-prose
|
||||
> span:has(> button) {
|
||||
background-color: rgb(39 39 42);
|
||||
color: rgb(212 212 216);
|
||||
}
|
||||
|
||||
/* Section headings (Authorization, Path Parameters, etc.) — consistent top spacing */
|
||||
#nd-page:has(.api-page-header) .min-w-0.flex-1 h2 {
|
||||
margin-top: 1.75rem !important;
|
||||
margin-bottom: 0.25rem !important;
|
||||
}
|
||||
|
||||
/* Code examples in right column — wrap long lines instead of horizontal scroll */
|
||||
#nd-page:has(.api-page-header) pre {
|
||||
white-space: pre-wrap !important;
|
||||
word-break: break-all !important;
|
||||
}
|
||||
#nd-page:has(.api-page-header) pre code {
|
||||
width: 100% !important;
|
||||
word-break: break-all !important;
|
||||
overflow-wrap: break-word !important;
|
||||
}
|
||||
|
||||
/* API page header — constrain title/copy-page to left content column, not full width.
|
||||
Only applies on OpenAPI pages (which have the two-column layout). */
|
||||
@media (min-width: 1280px) {
|
||||
.api-page-header {
|
||||
max-width: calc(100% - 400px - 1.5rem);
|
||||
}
|
||||
}
|
||||
|
||||
/* Footer navigation — constrain to left content column on OpenAPI pages only.
|
||||
Target pages that contain the two-column layout via :has() selector. */
|
||||
#nd-page:has(.api-page-header) > div:last-child {
|
||||
max-width: calc(100% - 400px - 1.5rem);
|
||||
}
|
||||
@media (max-width: 1024px) {
|
||||
#nd-page:has(.api-page-header) > div:last-child {
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
|
||||
/* Tailwind v4 content sources */
|
||||
|
||||
@@ -1,21 +0,0 @@
|
||||
import type { BaseLayoutProps } from 'fumadocs-ui/layouts/shared'
|
||||
|
||||
/**
|
||||
* Shared layout configurations
|
||||
*
|
||||
* you can customise layouts individually from:
|
||||
* Home Layout: app/(home)/layout.tsx
|
||||
* Docs Layout: app/docs/layout.tsx
|
||||
*/
|
||||
export const baseOptions: BaseLayoutProps = {
|
||||
nav: {
|
||||
title: (
|
||||
<>
|
||||
<svg width='24' height='24' xmlns='http://www.w3.org/2000/svg' aria-label='Logo'>
|
||||
<circle cx={12} cy={12} r={12} fill='currentColor' />
|
||||
</svg>
|
||||
My App
|
||||
</>
|
||||
),
|
||||
},
|
||||
}
|
||||
@@ -52,15 +52,26 @@ export function SidebarItem({ item }: { item: Item }) {
|
||||
)
|
||||
}
|
||||
|
||||
function isApiReferenceFolder(node: Folder): boolean {
|
||||
if (node.index?.url.includes('/api-reference/')) return true
|
||||
for (const child of node.children) {
|
||||
if (child.type === 'page' && child.url.includes('/api-reference/')) return true
|
||||
if (child.type === 'folder' && isApiReferenceFolder(child)) return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
export function SidebarFolder({ item, children }: { item: Folder; children: ReactNode }) {
|
||||
const pathname = usePathname()
|
||||
const hasActiveChild = checkHasActiveChild(item, pathname)
|
||||
const isApiRef = isApiReferenceFolder(item)
|
||||
const isOnApiRefPage = stripLangPrefix(pathname).startsWith('/api-reference')
|
||||
const hasChildren = item.children.length > 0
|
||||
const [open, setOpen] = useState(hasActiveChild)
|
||||
const [open, setOpen] = useState(hasActiveChild || (isApiRef && isOnApiRefPage))
|
||||
|
||||
useEffect(() => {
|
||||
setOpen(hasActiveChild)
|
||||
}, [hasActiveChild])
|
||||
setOpen(hasActiveChild || (isApiRef && isOnApiRefPage))
|
||||
}, [hasActiveChild, isApiRef, isOnApiRefPage])
|
||||
|
||||
const active = item.index ? isActive(item.index.url, pathname, false) : false
|
||||
|
||||
@@ -157,16 +168,18 @@ export function SidebarFolder({ item, children }: { item: Folder; children: Reac
|
||||
{hasChildren && (
|
||||
<div
|
||||
className={cn(
|
||||
'overflow-hidden transition-all duration-200 ease-in-out',
|
||||
open ? 'max-h-[10000px] opacity-100' : 'max-h-0 opacity-0'
|
||||
'grid transition-[grid-template-rows,opacity] duration-200 ease-in-out',
|
||||
open ? 'grid-rows-[1fr] opacity-100' : 'grid-rows-[0fr] opacity-0'
|
||||
)}
|
||||
>
|
||||
{/* Mobile: simple indent */}
|
||||
<div className='ml-4 flex flex-col gap-0.5 lg:hidden'>{children}</div>
|
||||
{/* Desktop: styled with border */}
|
||||
<ul className='mt-0.5 ml-2 hidden space-y-[0.0625rem] border-gray-200/60 border-l pl-2.5 lg:block dark:border-gray-700/60'>
|
||||
{children}
|
||||
</ul>
|
||||
<div className='overflow-hidden'>
|
||||
{/* Mobile: simple indent */}
|
||||
<div className='ml-4 flex flex-col gap-0.5 lg:hidden'>{children}</div>
|
||||
{/* Desktop: styled with border */}
|
||||
<ul className='mt-0.5 ml-2 hidden space-y-[0.0625rem] border-gray-200/60 border-l pl-2.5 lg:block dark:border-gray-700/60'>
|
||||
{children}
|
||||
</ul>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,12 +1,9 @@
|
||||
'use client'
|
||||
|
||||
import { useState } from 'react'
|
||||
import { ArrowRight, ChevronRight } from 'lucide-react'
|
||||
import Link from 'next/link'
|
||||
|
||||
export function TOCFooter() {
|
||||
const [isHovered, setIsHovered] = useState(false)
|
||||
|
||||
return (
|
||||
<div className='sticky bottom-0 mt-6'>
|
||||
<div className='flex flex-col gap-2 rounded-lg border border-border bg-secondary p-6 text-sm'>
|
||||
@@ -21,18 +18,19 @@ export function TOCFooter() {
|
||||
href='https://sim.ai/signup'
|
||||
target='_blank'
|
||||
rel='noopener noreferrer'
|
||||
onMouseEnter={() => setIsHovered(true)}
|
||||
onMouseLeave={() => setIsHovered(false)}
|
||||
className='group mt-2 inline-flex h-8 w-fit items-center justify-center gap-1 whitespace-nowrap rounded-[10px] border border-[#2AAD6C] bg-gradient-to-b from-[#3ED990] to-[#2AAD6C] px-3 pr-[10px] pl-[12px] font-medium text-sm text-white shadow-[inset_0_2px_4px_0_#5EE8A8] outline-none transition-all hover:shadow-lg focus-visible:border-ring focus-visible:ring-[3px] focus-visible:ring-ring/50'
|
||||
aria-label='Get started with Sim - Sign up for free'
|
||||
>
|
||||
<span>Get started</span>
|
||||
<span className='inline-flex transition-transform duration-200 group-hover:translate-x-0.5'>
|
||||
{isHovered ? (
|
||||
<ArrowRight className='h-4 w-4' aria-hidden='true' />
|
||||
) : (
|
||||
<ChevronRight className='h-4 w-4' aria-hidden='true' />
|
||||
)}
|
||||
<span className='relative inline-flex h-4 w-4 transition-transform duration-200 group-hover:translate-x-0.5'>
|
||||
<ChevronRight
|
||||
className='absolute inset-0 h-4 w-4 transition-opacity duration-200 group-hover:opacity-0'
|
||||
aria-hidden='true'
|
||||
/>
|
||||
<ArrowRight
|
||||
className='absolute inset-0 h-4 w-4 opacity-0 transition-opacity duration-200 group-hover:opacity-100'
|
||||
aria-hidden='true'
|
||||
/>
|
||||
</span>
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
@@ -1209,6 +1209,17 @@ export function AlgoliaIcon(props: SVGProps<SVGSVGElement>) {
|
||||
)
|
||||
}
|
||||
|
||||
export function AmplitudeIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} xmlns='http://www.w3.org/2000/svg' viewBox='0 0 49 49'>
|
||||
<path
|
||||
fill='#FFFFFF'
|
||||
d='M23.4,15.3c0.6,1.8,1.2,4.1,1.9,6.7c-2.6,0-5.3-0.1-7.8-0.1h-1.3c1.5-5.7,3.2-10.1,4.6-11.1 c0.1-0.1,0.2-0.1,0.4-0.1c0.2,0,0.3,0.1,0.5,0.3C21.9,11.5,22.5,12.7,23.4,15.3z M49,24.5C49,38,38,49,24.5,49S0,38,0,24.5 S11,0,24.5,0S49,11,49,24.5z M42.7,23.9c0-0.6-0.4-1.2-1-1.3l0,0l0,0l0,0c-0.1,0-0.1,0-0.2,0h-0.2c-4.1-0.3-8.4-0.4-12.4-0.5l0,0 C27,14.8,24.5,7.4,21.3,7.4c-3,0-5.8,4.9-8.2,14.5c-1.7,0-3.2,0-4.6-0.1c-0.1,0-0.2,0-0.2,0c-0.3,0-0.5,0-0.5,0 c-0.8,0.1-1.4,0.9-1.4,1.7c0,0.8,0.6,1.6,1.5,1.7l0,0h4.6c-0.4,1.9-0.8,3.8-1.1,5.6l-0.1,0.8l0,0c0,0.6,0.5,1.1,1.1,1.1 c0.4,0,0.8-0.2,1-0.5l0,0l2.2-7.1h10.7c0.8,3.1,1.7,6.3,2.8,9.3c0.6,1.6,2,5.4,4.4,5.4l0,0c3.6,0,5-5.8,5.9-9.6 c0.2-0.8,0.4-1.5,0.5-2.1l0.1-0.2l0,0c0-0.1,0-0.2,0-0.3c-0.1-0.2-0.2-0.3-0.4-0.4c-0.3-0.1-0.5,0.1-0.6,0.4l0,0l-0.1,0.2 c-0.3,0.8-0.6,1.6-0.8,2.3v0.1c-1.6,4.4-2.3,6.4-3.7,6.4l0,0l0,0l0,0c-1.8,0-3.5-7.3-4.1-10.1c-0.1-0.5-0.2-0.9-0.3-1.3h11.7 c0.2,0,0.4-0.1,0.6-0.1l0,0c0,0,0,0,0.1,0c0,0,0,0,0.1,0l0,0c0,0,0.1,0,0.1-0.1l0,0C42.5,24.6,42.7,24.3,42.7,23.9z'
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function GoogleBooksIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} xmlns='http://www.w3.org/2000/svg' viewBox='0 0 478.633 540.068'>
|
||||
@@ -1700,167 +1711,42 @@ export function StagehandIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg
|
||||
{...props}
|
||||
width='108'
|
||||
height='159'
|
||||
viewBox='0 0 108 159'
|
||||
fill='none'
|
||||
xmlns='http://www.w3.org/2000/svg'
|
||||
width='256'
|
||||
height='352'
|
||||
viewBox='0 0 256 352'
|
||||
fill='none'
|
||||
>
|
||||
<path
|
||||
d='M15 26C22.8234 31.822 23.619 41.405 25.3125 50.3867C25.8461 53.1914 26.4211 55.9689 27.0625 58.75C27.7987 61.9868 28.4177 65.2319 29 68.5C29.332 70.3336 29.6653 72.1669 30 74C30.1418 74.7863 30.2836 75.5727 30.4297 76.3828C31.8011 83.2882 33.3851 90.5397 39.4375 94.75C40.3405 95.3069 40.3405 95.3069 41.2617 95.875C43.8517 97.5512 45.826 99.826 48 102C50.6705 102.89 52.3407 103.143 55.0898 103.211C55.8742 103.239 56.6586 103.268 57.4668 103.297C59.1098 103.349 60.7531 103.393 62.3965 103.43C65.8896 103.567 68.4123 103.705 71.5664 105.289C73 107 73 107 73 111C73.66 111 74.32 111 75 111C74.0759 106.912 74.0759 106.912 71.4766 103.828C67.0509 102.348 62.3634 102.64 57.7305 102.609C52.3632 102.449 49.2783 101.537 45 98C41.8212 94.0795 41.5303 90.9791 42 86C44.9846 83.0154 48.2994 83.6556 52.3047 83.6289C53.139 83.6199 53.9734 83.6108 54.833 83.6015C56.6067 83.587 58.3805 83.5782 60.1543 83.5745C62.8304 83.5627 65.5041 83.5137 68.1797 83.4629C81.1788 83.34 91.8042 85.3227 102 94C106.37 100.042 105.483 106.273 104.754 113.406C103.821 119.026 101.968 124.375 100.125 129.75C99.8806 130.471 99.6361 131.193 99.3843 131.936C97.7783 136.447 95.9466 140.206 93 144C92.34 144 91.68 144 91 144C91 144.66 91 145.32 91 146C79.0816 156.115 63.9798 156.979 49 156C36.6394 154.226 26.7567 148.879 19 139C11.0548 125.712 11.6846 105.465 11.3782 90.4719C11.0579 77.4745 8.03411 64.8142 5.4536 52.1135C5.04373 50.0912 4.64233 48.0673 4.24218 46.043C4.00354 44.8573 3.7649 43.6716 3.51903 42.45C2.14425 33.3121 2.14425 33.3121 4.87499 29.125C8.18297 25.817 10.3605 25.4542 15 26Z'
|
||||
fill='#FDFDFD'
|
||||
d='M 242.29,45.79 C 242.29,28.88 226.69,13.76 206.61,13.76 C 188.59,13.76 174.82,28.66 174.82,45.85 V 101.97 C 168.89,98.09 163.18,96.76 157.14,96.76 C 145.94,96.76 137.02,101.49 128.83,110.17 C 121.81,101.01 112.07,95.73 100.72,95.73 C 93.97,95.73 87.82,98.09 82.11,100.9 V 80.05 C 82.11,64.08 66.14,47.28 48.74,47.28 C 31.12,47.28 14.54,62.71 14.54,78.79 V 219.4 C 14.54,273.71 56.99,337.89 125.23,337.89 C 197.41,337.89 242.29,289.05 242.29,186.01 V 78.9 L 242.29,45.79 Z'
|
||||
fill='black'
|
||||
/>
|
||||
<path
|
||||
d='M91 0.999996C94.8466 2.96604 96.2332 5.08365 97.6091 9.03564C99.203 14.0664 99.4412 18.7459 99.4414 23.9922C99.4538 24.9285 99.4663 25.8647 99.4791 26.8294C99.5049 28.8198 99.5247 30.8103 99.539 32.8008C99.5785 37.9693 99.6682 43.1369 99.7578 48.3047C99.7747 49.3188 99.7917 50.3328 99.8091 51.3776C99.9603 59.6066 100.323 67.7921 100.937 76C101.012 77.0582 101.087 78.1163 101.164 79.2065C101.646 85.1097 102.203 90.3442 105.602 95.3672C107.492 98.9262 107.45 102.194 107.375 106.125C107.366 106.881 107.356 107.638 107.346 108.417C107.18 114.639 106.185 120.152 104 126C103.636 126.996 103.273 127.993 102.898 129.02C98.2182 141.022 92.6784 149.349 80.7891 155.062C67.479 160.366 49.4234 159.559 36 155C32.4272 153.286 29.2162 151.308 26 149C25.0719 148.361 24.1437 147.721 23.1875 147.062C8.32968 133.054 9.60387 109.231 8.73413 90.3208C8.32766 81.776 7.51814 73.4295 5.99999 65C5.82831 64.0338 5.65662 63.0675 5.47973 62.072C4.98196 59.3363 4.46395 56.6053 3.93749 53.875C3.76412 52.9572 3.59074 52.0394 3.4121 51.0938C2.75101 47.6388 2.11387 44.3416 0.999995 41C0.505898 36.899 0.0476353 32.7768 2.04687 29.0469C4.91881 25.5668 6.78357 24.117 11.25 23.6875C15.8364 24.0697 17.5999 24.9021 21 28C24.7763 34.3881 26.047 41.2626 27.1875 48.5C27.5111 50.4693 27.8377 52.4381 28.168 54.4062C28.3733 55.695 28.3733 55.695 28.5828 57.0098C28.8087 58.991 28.8087 58.991 30 60C30.3171 59.4947 30.6342 58.9894 30.9609 58.4688C33.1122 55.4736 34.7097 53.3284 38.3789 52.3945C44.352 52.203 48.1389 53.6183 53 57C53.0928 56.1338 53.0928 56.1338 53.1875 55.25C54.4089 51.8676 55.9015 50.8075 59 49C63.8651 48.104 66.9348 48.3122 71.1487 51.0332C72.0896 51.6822 73.0305 52.3313 74 53C73.9686 51.2986 73.9686 51.2986 73.9365 49.5627C73.8636 45.3192 73.818 41.0758 73.7803 36.8318C73.7603 35.0016 73.733 33.1715 73.6982 31.3415C73.6492 28.6976 73.6269 26.0545 73.6094 23.4102C73.5887 22.6035 73.5681 21.7969 73.5468 20.9658C73.5441 13.8444 75.5121 7.83341 80.25 2.4375C83.9645 0.495841 86.8954 0.209055 91 0.999996ZM3.99999 30C1.56925 34.8615 3.215 40.9393 4.24218 46.043C4.37061 46.6927 4.49905 47.3424 4.63137 48.0118C5.03968 50.0717 5.45687 52.1296 5.87499 54.1875C11.1768 80.6177 11.1768 80.6177 11.4375 93.375C11.7542 120.78 11.7542 120.78 23.5625 144.375C28.5565 149.002 33.5798 151.815 40 154C40.6922 154.244 41.3844 154.487 42.0977 154.738C55.6463 158.576 72.4909 156.79 84.8086 150.316C87.0103 148.994 89.0458 147.669 91 146C91 145.34 91 144.68 91 144C91.66 144 92.32 144 93 144C97.1202 138.98 99.3206 133.053 101.25 126.937C101.505 126.174 101.76 125.41 102.023 124.623C104.94 115.65 107.293 104.629 103.625 95.625C96.3369 88.3369 86.5231 83.6919 76.1988 83.6088C74.9905 83.6226 74.9905 83.6226 73.7578 83.6367C72.9082 83.6362 72.0586 83.6357 71.1833 83.6352C69.4034 83.6375 67.6235 83.6472 65.8437 83.6638C63.1117 83.6876 60.3806 83.6843 57.6484 83.6777C55.9141 83.6833 54.1797 83.6904 52.4453 83.6992C51.6277 83.6983 50.81 83.6974 49.9676 83.6964C45.5122 83.571 45.5122 83.571 42 86C41.517 90.1855 41.733 92.4858 43.6875 96.25C46.4096 99.4871 48.6807 101.674 53.0105 102.282C55.3425 102.411 57.6645 102.473 60 102.5C69.8847 102.612 69.8847 102.612 74 106C74.8125 108.687 74.8125 108.688 75 111C74.34 111 73.68 111 73 111C72.8969 110.216 72.7937 109.432 72.6875 108.625C72.224 105.67 72.224 105.67 69 104C65.2788 103.745 61.5953 103.634 57.8672 103.609C51.1596 103.409 46.859 101.691 41.875 97C41.2562 96.34 40.6375 95.68 40 95C39.175 94.4637 38.35 93.9275 37.5 93.375C30.9449 87.1477 30.3616 77.9789 29.4922 69.418C29.1557 66.1103 29.1557 66.1103 28.0352 63.625C26.5234 59.7915 26.1286 55.8785 25.5625 51.8125C23.9233 38.3 23.9233 38.3 17 27C11.7018 24.3509 7.9915 26.1225 3.99999 30Z'
|
||||
fill='#1F1F1F'
|
||||
d='M 224.94,46.23 C 224.94,36.76 215.91,28.66 205.91,28.66 C 196.75,28.66 189.9,36.11 189.9,45.14 V 152.72 C 202.88,153.38 214.08,155.96 224.94,166.19 V 78.79 L 224.94,46.23 Z'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
d='M89.0976 2.53906C91 3 91 3 93.4375 5.3125C96.1586 9.99276 96.178 14.1126 96.2461 19.3828C96.2778 21.1137 96.3098 22.8446 96.342 24.5754C96.3574 25.4822 96.3728 26.3889 96.3887 27.3232C96.6322 41.3036 96.9728 55.2117 98.3396 69.1353C98.9824 75.7746 99.0977 82.3308 99 89C96.5041 88.0049 94.0126 87.0053 91.5351 85.9648C90.3112 85.4563 90.3112 85.4563 89.0625 84.9375C87.8424 84.4251 87.8424 84.4251 86.5976 83.9023C83.7463 82.9119 80.9774 82.4654 78 82C76.7702 65.9379 75.7895 49.8907 75.7004 33.7775C75.6919 32.3138 75.6783 30.8501 75.6594 29.3865C75.5553 20.4082 75.6056 12.1544 80.6875 4.4375C83.6031 2.62508 85.7 2.37456 89.0976 2.53906Z'
|
||||
fill='#FBFBFB'
|
||||
d='M 157.21,113.21 C 146.12,113.21 137.93,122.02 137.93,131.76 V 154.62 C 142.24,153.05 145.95,152.61 149.83,152.61 H 174.71 V 131.76 C 174.71,122.35 166.73,113.21 157.21,113.21 Z'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
d='M97 13C97.99 13.495 97.99 13.495 99 14C99.0297 15.8781 99.0297 15.8781 99.0601 17.7942C99.4473 46.9184 99.4473 46.9184 100.937 76C101.012 77.0574 101.087 78.1149 101.164 79.2043C101.646 85.1082 102.203 90.3434 105.602 95.3672C107.492 98.9262 107.45 102.194 107.375 106.125C107.366 106.881 107.356 107.638 107.346 108.417C107.18 114.639 106.185 120.152 104 126C103.636 126.996 103.273 127.993 102.898 129.02C98.2182 141.022 92.6784 149.349 80.7891 155.062C67.479 160.366 49.4234 159.559 36 155C32.4272 153.286 29.2162 151.308 26 149C24.6078 148.041 24.6078 148.041 23.1875 147.062C13.5484 137.974 10.832 124.805 9.99999 112C9.91815 101.992 10.4358 91.9898 11 82C11.33 82 11.66 82 12 82C12.0146 82.6118 12.0292 83.2236 12.0442 83.854C11.5946 115.845 11.5946 115.845 24.0625 143.875C28.854 148.273 33.89 150.868 40 153C40.6935 153.245 41.387 153.49 42.1016 153.742C56.9033 157.914 73.8284 155.325 87 148C88.3301 147.327 89.6624 146.658 91 146C91 145.34 91 144.68 91 144C91.66 144 92.32 144 93 144C100.044 130.286 105.786 114.602 104 99C102.157 94.9722 100.121 93.0631 96.3125 90.875C95.5042 90.398 94.696 89.9211 93.8633 89.4297C85.199 85.1035 78.1558 84.4842 68.5 84.3125C67.2006 84.2783 65.9012 84.2442 64.5625 84.209C61.3751 84.127 58.1879 84.0577 55 84C55 83.67 55 83.34 55 83C58.9087 82.7294 62.8179 82.4974 66.7309 82.2981C68.7007 82.1902 70.6688 82.0535 72.6367 81.916C82.854 81.4233 90.4653 83.3102 99 89C98.8637 87.6094 98.8637 87.6094 98.7246 86.1907C96.96 67.8915 95.697 49.7051 95.75 31.3125C95.751 30.5016 95.7521 29.6908 95.7532 28.8554C95.7901 15.4198 95.7901 15.4198 97 13Z'
|
||||
fill='#262114'
|
||||
d='M 100.06,111.75 C 89.19,111.75 81.85,121.06 81.85,130.31 V 157.86 C 81.85,167.71 89.72,175.38 99.24,175.38 C 109.71,175.38 118.39,166.91 118.39,157.39 V 130.31 C 118.39,120.79 110.03,111.75 100.06,111.75 Z'
|
||||
fill='white'
|
||||
/>
|
||||
<path
|
||||
d='M68 51C72.86 54.06 74.644 56.5072 76 62C76.249 65.2763 76.2347 68.5285 76.1875 71.8125C76.1868 72.6833 76.1862 73.554 76.1855 74.4512C76.1406 80.8594 76.1406 80.8594 75 82C73.5113 82.0867 72.0185 82.107 70.5273 82.0976C69.6282 82.0944 68.7291 82.0912 67.8027 82.0879C66.8572 82.0795 65.9117 82.0711 64.9375 82.0625C63.9881 82.058 63.0387 82.0535 62.0605 82.0488C59.707 82.037 57.3535 82.0205 55 82C53.6352 77.2188 53.738 72.5029 53.6875 67.5625C53.6585 66.6208 53.6295 65.6792 53.5996 64.709C53.5591 60.2932 53.5488 57.7378 55.8945 53.9023C59.5767 50.5754 63.1766 50.211 68 51Z'
|
||||
fill='#F8F8F8'
|
||||
d='M 192.04,168.87 H 150.16 C 140.19,168.87 133.34,175.39 133.34,183.86 C 133.34,192.9 140.19,199.75 148.66,199.75 H 182.52 C 188.01,199.75 189.63,204.81 189.63,207.49 C 189.63,211.91 186.37,214.64 181.09,215.51 C 162.96,218.66 137.71,229.13 137.71,259.68 C 137.71,265.07 133.67,267.42 130.29,267.42 C 126.09,267.42 122.38,264.74 122.38,260.12 C 122.38,241.15 129.02,228.17 143.26,214.81 C 131.01,212.02 119.21,202.99 117.75,186.43 C 111.93,189.81 107.2,191.15 100.18,191.15 C 82.11,191.15 66.68,176.58 66.68,158.29 V 80.71 C 66.68,71.24 57.16,63.5 49.18,63.5 C 38.71,63.5 29.89,72.42 29.89,80.27 V 217.19 C 29.89,266.48 68.71,322.19 124.88,322.19 C 185.91,322.19 223.91,282.15 223.91,207.16 C 223.91,187.19 214.28,168.87 192.04,168.87 Z'
|
||||
fill='white'
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function BrandfetchIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} viewBox='0 0 29 31' fill='none' xmlns='http://www.w3.org/2000/svg'>
|
||||
<path
|
||||
d='M46 55C48.7557 57.1816 50.4359 58.8718 52 62C52.0837 63.5215 52.1073 65.0466 52.0977 66.5703C52.0944 67.4662 52.0912 68.3621 52.0879 69.2852C52.0795 70.2223 52.0711 71.1595 52.0625 72.125C52.058 73.0699 52.0535 74.0148 52.0488 74.9883C52.037 77.3256 52.0206 79.6628 52 82C50.9346 82.1992 50.9346 82.1992 49.8477 82.4023C48.9286 82.5789 48.0094 82.7555 47.0625 82.9375C46.146 83.1115 45.2294 83.2855 44.2852 83.4648C42.0471 83.7771 42.0471 83.7771 41 85C40.7692 86.3475 40.5885 87.7038 40.4375 89.0625C40.2931 90.3619 40.1487 91.6613 40 93C37 92 37 92 35.8672 90.1094C35.5398 89.3308 35.2123 88.5522 34.875 87.75C34.5424 86.9817 34.2098 86.2134 33.8672 85.4219C31.9715 80.1277 31.7884 75.065 31.75 69.5C31.7294 68.7536 31.7087 68.0073 31.6875 67.2383C31.6551 62.6607 32.0474 59.7266 35 56C38.4726 54.2637 42.2119 54.3981 46 55Z'
|
||||
fill='#FAFAFA'
|
||||
/>
|
||||
<path
|
||||
d='M97 13C97.66 13.33 98.32 13.66 99 14C99.0297 15.8781 99.0297 15.8781 99.0601 17.7942C99.4473 46.9184 99.4473 46.9184 100.937 76C101.012 77.0574 101.087 78.1149 101.164 79.2043C101.566 84.1265 102.275 88.3364 104 93C103.625 95.375 103.625 95.375 103 97C102.361 96.2781 101.721 95.5563 101.062 94.8125C94.4402 88.1902 85.5236 84.8401 76.2891 84.5859C75.0451 84.5473 73.8012 84.5086 72.5195 84.4688C71.2343 84.4378 69.9491 84.4069 68.625 84.375C66.6624 84.317 66.6624 84.317 64.6601 84.2578C61.4402 84.1638 58.2203 84.0781 55 84C55 83.67 55 83.34 55 83C58.9087 82.7294 62.8179 82.4974 66.7309 82.2981C68.7007 82.1902 70.6688 82.0535 72.6367 81.916C82.854 81.4233 90.4653 83.3102 99 89C98.9091 88.0729 98.8182 87.1458 98.7246 86.1907C96.96 67.8915 95.697 49.7051 95.75 31.3125C95.751 30.5016 95.7521 29.6908 95.7532 28.8554C95.7901 15.4198 95.7901 15.4198 97 13Z'
|
||||
fill='#423B28'
|
||||
/>
|
||||
<path
|
||||
d='M91 0.999996C94.3999 3.06951 96.8587 5.11957 98 9C97.625 12.25 97.625 12.25 97 15C95.804 12.6081 94.6146 10.2139 93.4375 7.8125C92.265 5.16236 92.265 5.16236 91 4C88.074 3.7122 85.8483 3.51695 83 4C79.1128 7.37574 78.178 11.0991 77 16C76.8329 18.5621 76.7615 21.1317 76.7695 23.6992C76.77 24.4155 76.7704 25.1318 76.7709 25.8698C76.7739 27.3783 76.7817 28.8868 76.7942 30.3953C76.8123 32.664 76.8147 34.9324 76.8144 37.2012C76.8329 44.6001 77.0765 51.888 77.7795 59.259C78.1413 63.7564 78.1068 68.2413 78.0625 72.75C78.058 73.6498 78.0535 74.5495 78.0488 75.4766C78.0373 77.6511 78.0193 79.8255 78 82C78.99 82.495 78.99 82.495 80 83C68.78 83.33 57.56 83.66 46 84C46.495 83.01 46.495 83.01 47 82C52.9349 80.7196 58.8909 80.8838 64.9375 80.9375C65.9075 80.942 66.8775 80.9465 67.8769 80.9512C70.2514 80.9629 72.6256 80.9793 75 81C75.0544 77.9997 75.0939 75.0005 75.125 72C75.1418 71.1608 75.1585 70.3216 75.1758 69.457C75.2185 63.9475 74.555 59.2895 73 54C73.66 54 74.32 54 75 54C74.9314 53.2211 74.8629 52.4422 74.7922 51.6396C74.1158 43.5036 73.7568 35.4131 73.6875 27.25C73.644 25.5194 73.644 25.5194 73.5996 23.7539C73.5376 15.3866 74.6189 8.85069 80.25 2.4375C83.9433 0.506911 86.9162 0.173322 91 0.999996Z'
|
||||
fill='#131311'
|
||||
/>
|
||||
<path
|
||||
d='M15 24C20.2332 26.3601 22.1726 29.3732 24.1875 34.5195C26.8667 42.6988 27.2651 50.4282 27 59C26.67 59 26.34 59 26 59C25.8945 58.436 25.7891 57.8721 25.6804 57.291C25.1901 54.6926 24.6889 52.0963 24.1875 49.5C24.0218 48.6131 23.8562 47.7262 23.6855 46.8125C21.7568 35.5689 21.7568 35.5689 15 27C12.0431 26.2498 12.0431 26.2498 8.99999 27C5.97965 28.9369 5.97965 28.9369 3.99999 32C3.67226 36.9682 4.31774 41.4911 5.27733 46.3594C5.40814 47.0304 5.53894 47.7015 5.67371 48.3929C5.94892 49.7985 6.22723 51.2035 6.50854 52.6079C6.93887 54.7569 7.35989 56.9075 7.77929 59.0586C9.09359 66.104 9.09359 66.104 11 73C11.0836 75.2109 11.1073 77.4243 11.0976 79.6367C11.0944 80.9354 11.0912 82.2342 11.0879 83.5723C11.0795 84.944 11.0711 86.3158 11.0625 87.6875C11.0575 89.071 11.0529 90.4544 11.0488 91.8379C11.037 95.2253 11.0206 98.6126 11 102C8.54975 99.5498 8.73228 98.8194 8.65624 95.4492C8.62812 94.53 8.60001 93.6108 8.57104 92.6638C8.54759 91.6816 8.52415 90.6994 8.49999 89.6875C8.20265 81.3063 7.58164 73.2485 5.99999 65C5.67135 63.2175 5.34327 61.435 5.01562 59.6523C4.31985 55.9098 3.62013 52.1681 2.90233 48.4297C2.75272 47.6484 2.60311 46.867 2.44897 46.062C1.99909 43.8187 1.99909 43.8187 0.999995 41C0.505898 36.899 0.0476353 32.7768 2.04687 29.0469C6.06003 24.1839 8.81126 23.4843 15 24Z'
|
||||
fill='#2A2311'
|
||||
/>
|
||||
<path
|
||||
d='M11 82C11.33 82 11.66 82 12 82C12.0146 82.6118 12.0292 83.2236 12.0442 83.854C11.5946 115.845 11.5946 115.845 24.0625 143.875C30.0569 149.404 36.9894 152.617 45 154C42 156 42 156 39.4375 156C29.964 153.244 20.8381 146.677 16 138C8.26993 120.062 9.92611 101.014 11 82Z'
|
||||
fill='#272214'
|
||||
/>
|
||||
<path
|
||||
d='M68 49C70.3478 50.1116 71.9703 51.3346 74 53C73.34 53.66 72.68 54.32 72 55C71.505 54.505 71.01 54.01 70.5 53.5C67.6718 51.8031 65.3662 51.5622 62.0976 51.4062C58.4026 52.4521 57.1992 53.8264 55 57C54.3826 61.2861 54.5302 65.4938 54.6875 69.8125C54.7101 70.9823 54.7326 72.1521 54.7559 73.3574C54.8147 76.2396 54.8968 79.1191 55 82C54.01 82 53.02 82 52 82C51.9854 81.4203 51.9708 80.8407 51.9558 80.2434C51.881 77.5991 51.7845 74.9561 51.6875 72.3125C51.6649 71.4005 51.6424 70.4885 51.6191 69.5488C51.4223 64.6292 51.2621 60.9548 48 57C45.6603 55.8302 44.1661 55.8339 41.5625 55.8125C40.78 55.7983 39.9976 55.7841 39.1914 55.7695C36.7079 55.8591 36.7079 55.8591 34 58C32.7955 60.5518 32.7955 60.5518 32 63C31.34 63 30.68 63 30 63C30.2839 59.6879 31.0332 57.9518 32.9375 55.1875C36.7018 52.4987 38.9555 52.3484 43.4844 52.5586C47.3251 53.2325 49.8148 54.7842 53 57C53.0928 56.1338 53.0928 56.1338 53.1875 55.25C55.6091 48.544 61.7788 47.8649 68 49Z'
|
||||
fill='#1F1A0F'
|
||||
/>
|
||||
<path
|
||||
d='M99 60C99.33 60 99.66 60 100 60C100.05 60.7865 100.1 61.573 100.152 62.3833C100.385 65.9645 100.63 69.5447 100.875 73.125C100.954 74.3625 101.032 75.6 101.113 76.875C101.197 78.0738 101.281 79.2727 101.367 80.5078C101.44 81.6075 101.514 82.7073 101.589 83.8403C102.013 87.1 102.94 89.8988 104 93C103.625 95.375 103.625 95.375 103 97C102.361 96.2781 101.721 95.5563 101.062 94.8125C94.4402 88.1902 85.5236 84.8401 76.2891 84.5859C74.4231 84.5279 74.4231 84.5279 72.5195 84.4688C71.2343 84.4378 69.9491 84.4069 68.625 84.375C67.3166 84.3363 66.0082 84.2977 64.6601 84.2578C61.4402 84.1638 58.2203 84.0781 55 84C55 83.67 55 83.34 55 83C58.9087 82.7294 62.8179 82.4974 66.7309 82.2981C68.7007 82.1902 70.6688 82.0535 72.6367 81.916C82.854 81.4233 90.4653 83.3102 99 89C98.9162 87.912 98.8324 86.8241 98.7461 85.7031C98.1266 77.012 97.9127 68.6814 99 60Z'
|
||||
fill='#332E22'
|
||||
/>
|
||||
<path
|
||||
d='M15 24C20.2332 26.3601 22.1726 29.3732 24.1875 34.5195C26.8667 42.6988 27.2651 50.4282 27 59C26.67 59 26.34 59 26 59C25.8945 58.436 25.7891 57.8721 25.6804 57.291C25.1901 54.6926 24.6889 52.0963 24.1875 49.5C24.0218 48.6131 23.8562 47.7262 23.6855 46.8125C21.7568 35.5689 21.7568 35.5689 15 27C12.0431 26.2498 12.0431 26.2498 8.99999 27C5.2818 29.7267 4.15499 31.2727 3.18749 35.8125C3.12562 36.8644 3.06374 37.9163 2.99999 39C2.33999 39 1.67999 39 0.999992 39C0.330349 31.2321 0.330349 31.2321 3.37499 27.5625C7.31431 23.717 9.51597 23.543 15 24Z'
|
||||
fill='#1D180A'
|
||||
/>
|
||||
<path
|
||||
d='M91 0.999996C94.3999 3.06951 96.8587 5.11957 98 9C97.625 12.25 97.625 12.25 97 15C95.804 12.6081 94.6146 10.2139 93.4375 7.8125C92.265 5.16236 92.265 5.16236 91 4C85.4345 3.33492 85.4345 3.33491 80.6875 5.75C78.5543 9.85841 77.6475 13.9354 76.7109 18.4531C76.4763 19.2936 76.2417 20.1341 76 21C75.34 21.33 74.68 21.66 74 22C73.5207 15.4102 74.5846 10.6998 78 5C81.755 0.723465 85.5463 -0.103998 91 0.999996Z'
|
||||
fill='#16130D'
|
||||
/>
|
||||
<path
|
||||
d='M42 93C42.5569 93.7631 43.1137 94.5263 43.6875 95.3125C46.4238 98.4926 48.7165 100.679 53.0105 101.282C55.3425 101.411 57.6646 101.473 60 101.5C70.6207 101.621 70.6207 101.621 75 106C75.0406 107.666 75.0427 109.334 75 111C74.34 111 73.68 111 73 111C72.7112 110.196 72.4225 109.391 72.125 108.562C71.2674 105.867 71.2674 105.867 69 105C65.3044 104.833 61.615 104.703 57.916 104.658C52.1631 104.454 48.7484 103.292 44 100C41.5625 97.25 41.5625 97.25 40 95C40.66 95 41.32 95 42 95C42 94.34 42 93.68 42 93Z'
|
||||
fill='#2B2B2B'
|
||||
/>
|
||||
<path
|
||||
d='M11 82C11.33 82 11.66 82 12 82C12.1682 86.6079 12.3287 91.216 12.4822 95.8245C12.5354 97.3909 12.5907 98.9574 12.6482 100.524C12.7306 102.78 12.8055 105.036 12.8789 107.293C12.9059 107.989 12.933 108.685 12.9608 109.402C13.0731 113.092 12.9015 116.415 12 120C11.67 120 11.34 120 11 120C9.63778 112.17 10.1119 104.4 10.4375 96.5C10.4908 95.0912 10.5436 93.6823 10.5957 92.2734C10.7247 88.8487 10.8596 85.4243 11 82Z'
|
||||
fill='#4D483B'
|
||||
/>
|
||||
<path
|
||||
d='M43.4844 52.5586C47.3251 53.2325 49.8148 54.7842 53 57C52 59 52 59 50 60C49.5256 59.34 49.0512 58.68 48.5625 58C45.2656 55.4268 43.184 55.5955 39.1211 55.6641C36.7043 55.8955 36.7043 55.8955 34 58C32.7955 60.5518 32.7955 60.5518 32 63C31.34 63 30.68 63 30 63C30.2839 59.6879 31.0332 57.9518 32.9375 55.1875C36.7018 52.4987 38.9555 52.3484 43.4844 52.5586Z'
|
||||
fill='#221F16'
|
||||
/>
|
||||
<path
|
||||
d='M76 73C76.33 73 76.66 73 77 73C77 75.97 77 78.94 77 82C78.485 82.495 78.485 82.495 80 83C68.78 83.33 57.56 83.66 46 84C46.33 83.34 46.66 82.68 47 82C52.9349 80.7196 58.8909 80.8838 64.9375 80.9375C65.9075 80.942 66.8775 80.9465 67.8769 80.9512C70.2514 80.9629 72.6256 80.9793 75 81C75.33 78.36 75.66 75.72 76 73Z'
|
||||
fill='#040404'
|
||||
/>
|
||||
<path
|
||||
d='M27 54C27.33 54 27.66 54 28 54C28.33 56.97 28.66 59.94 29 63C29.99 63 30.98 63 32 63C32 66.96 32 70.92 32 75C31.01 74.67 30.02 74.34 29 74C28.8672 73.2523 28.7344 72.5047 28.5977 71.7344C28.421 70.7495 28.2444 69.7647 28.0625 68.75C27.8885 67.7755 27.7144 66.8009 27.5352 65.7969C27.0533 63.087 27.0533 63.087 26.4062 60.8125C25.8547 58.3515 26.3956 56.4176 27 54Z'
|
||||
fill='#434039'
|
||||
/>
|
||||
<path
|
||||
d='M78 5C78.99 5.33 79.98 5.66 81 6C80.3194 6.92812 80.3194 6.92812 79.625 7.875C77.7233 11.532 77.1555 14.8461 76.5273 18.8906C76.3533 19.5867 76.1793 20.2828 76 21C75.34 21.33 74.68 21.66 74 22C73.5126 15.2987 74.9229 10.9344 78 5Z'
|
||||
fill='#2A2313'
|
||||
/>
|
||||
<path
|
||||
d='M12 115C12.99 115.495 12.99 115.495 14 116C14.5334 118.483 14.9326 120.864 15.25 123.375C15.3531 124.061 15.4562 124.747 15.5625 125.453C16.0763 129.337 16.2441 130.634 14 134C12.6761 127.57 11.752 121.571 12 115Z'
|
||||
fill='#2F2C22'
|
||||
/>
|
||||
<path
|
||||
d='M104 95C107 98 107 98 107.363 101.031C107.347 102.176 107.33 103.321 107.312 104.5C107.309 105.645 107.305 106.789 107.301 107.969C107 111 107 111 105 114C104.67 107.73 104.34 101.46 104 95Z'
|
||||
fill='#120F05'
|
||||
/>
|
||||
<path
|
||||
d='M56 103C58.6048 102.919 61.2071 102.86 63.8125 102.812C64.5505 102.787 65.2885 102.762 66.0488 102.736C71.4975 102.662 71.4975 102.662 74 104.344C75.374 106.619 75.2112 108.396 75 111C74.34 111 73.68 111 73 111C72.7112 110.196 72.4225 109.391 72.125 108.562C71.2674 105.867 71.2674 105.867 69 105C66.7956 104.77 64.5861 104.589 62.375 104.438C61.1865 104.354 59.998 104.27 58.7734 104.184C57.4006 104.093 57.4006 104.093 56 104C56 103.67 56 103.34 56 103Z'
|
||||
fill='#101010'
|
||||
/>
|
||||
<path
|
||||
d='M23 40C23.66 40 24.32 40 25 40C27.3084 46.3482 27.1982 52.2948 27 59C26.67 59 26.34 59 26 59C25.01 52.73 24.02 46.46 23 40Z'
|
||||
fill='#191409'
|
||||
/>
|
||||
<path
|
||||
d='M47 83C46.3606 83.3094 45.7212 83.6187 45.0625 83.9375C41.9023 87.0977 42.181 90.6833 42 95C41.01 94.67 40.02 94.34 39 94C39.3463 85.7409 39.3463 85.7409 41.875 82.875C44 82 44 82 47 83Z'
|
||||
fill='#171717'
|
||||
/>
|
||||
<path
|
||||
d='M53 61C53.33 61 53.66 61 54 61C54.33 67.93 54.66 74.86 55 82C54.01 82 53.02 82 52 82C52.33 75.07 52.66 68.14 53 61Z'
|
||||
fill='#444444'
|
||||
/>
|
||||
<path
|
||||
d='M81 154C78.6696 156.33 77.8129 156.39 74.625 156.75C73.4687 156.897 73.4687 156.897 72.2891 157.047C69.6838 156.994 68.2195 156.317 66 155C67.7478 154.635 69.4984 154.284 71.25 153.938C72.7118 153.642 72.7118 153.642 74.2031 153.34C76.8681 153.016 78.4887 153.145 81 154Z'
|
||||
fill='#332F23'
|
||||
/>
|
||||
<path
|
||||
d='M19 28C19.66 28 20.32 28 21 28C21.6735 29.4343 22.3386 30.8726 23 32.3125C23.5569 33.5133 23.5569 33.5133 24.125 34.7383C25 37 25 37 25 40C22 39 22 39 21.0508 37.2578C20.8071 36.554 20.5635 35.8502 20.3125 35.125C20.0611 34.4263 19.8098 33.7277 19.5508 33.0078C19 31 19 31 19 28Z'
|
||||
fill='#282213'
|
||||
/>
|
||||
<path
|
||||
d='M102 87C104.429 93.2857 104.429 93.2857 103 97C100.437 94.75 100.437 94.75 98 92C98.0625 89.75 98.0625 89.75 99 88C101 87 101 87 102 87Z'
|
||||
fill='#37301F'
|
||||
/>
|
||||
<path
|
||||
d='M53 56C53.33 56 53.66 56 54 56C53.67 62.27 53.34 68.54 53 75C52.67 75 52.34 75 52 75C51.7788 72.2088 51.5726 69.4179 51.375 66.625C51.3105 65.8309 51.2461 65.0369 51.1797 64.2188C51.0394 62.1497 51.0124 60.0737 51 58C51.66 57.34 52.32 56.68 53 56Z'
|
||||
fill='#030303'
|
||||
/>
|
||||
<path
|
||||
d='M100 129C100.33 129 100.66 129 101 129C100.532 133.776 99.7567 137.045 97 141C96.34 140.67 95.68 140.34 95 140C96.65 136.37 98.3 132.74 100 129Z'
|
||||
fill='#1E1A12'
|
||||
/>
|
||||
<path
|
||||
d='M15 131C17.7061 132.353 17.9618 133.81 19.125 136.562C19.4782 137.389 19.8314 138.215 20.1953 139.066C20.4609 139.704 20.7264 140.343 21 141C20.01 141 19.02 141 18 141C15.9656 137.27 15 135.331 15 131Z'
|
||||
fill='#1C1912'
|
||||
/>
|
||||
<path
|
||||
d='M63 49C69.4 49.4923 69.4 49.4923 72.4375 52.0625C73.2109 53.0216 73.2109 53.0216 74 54C70.8039 54 69.5828 53.4533 66.8125 52C66.0971 51.6288 65.3816 51.2575 64.6445 50.875C64.1018 50.5863 63.5591 50.2975 63 50C63 49.67 63 49.34 63 49Z'
|
||||
fill='#13110C'
|
||||
/>
|
||||
<path
|
||||
d='M0.999992 39C1.98999 39 2.97999 39 3.99999 39C5.24999 46.625 5.24999 46.625 2.99999 50C2.33999 46.37 1.67999 42.74 0.999992 39Z'
|
||||
fill='#312C1E'
|
||||
/>
|
||||
<path
|
||||
d='M94 5C94.66 5 95.32 5 96 5C97.8041 7.75924 98.0127 8.88972 97.625 12.25C97.4187 13.1575 97.2125 14.065 97 15C95.1161 11.7345 94.5071 8.71888 94 5Z'
|
||||
fill='#292417'
|
||||
/>
|
||||
<path
|
||||
d='M20 141C23.3672 142.393 24.9859 143.979 27 147C24.625 146.812 24.625 146.812 22 146C20.6875 143.438 20.6875 143.438 20 141Z'
|
||||
fill='#373328'
|
||||
/>
|
||||
<path
|
||||
d='M86 83C86.33 83.99 86.66 84.98 87 86C83.37 85.34 79.74 84.68 76 84C80.3553 81.8223 81.4663 81.9696 86 83Z'
|
||||
fill='#2F2F2F'
|
||||
/>
|
||||
<path
|
||||
d='M42 93C46 97.625 46 97.625 46 101C44.02 99.35 42.04 97.7 40 96C40.66 95.67 41.32 95.34 42 95C42 94.34 42 93.68 42 93Z'
|
||||
fill='#232323'
|
||||
/>
|
||||
<path
|
||||
d='M34 55C34.66 55.33 35.32 55.66 36 56C35.5256 56.7838 35.0512 57.5675 34.5625 58.375C33.661 59.8895 32.7882 61.4236 32 63C31.34 63 30.68 63 30 63C30.4983 59.3125 31.1007 57.3951 34 55Z'
|
||||
fill='#110F0A'
|
||||
d='M29 7.54605C29 9.47222 28.316 11.1378 26.9481 12.5428C25.5802 13.9251 23.5852 14.9222 20.9634 15.534C22.377 15.9192 23.4484 16.5537 24.1781 17.4375C24.9077 18.2987 25.2724 19.2956 25.2724 20.4287C25.2724 22.2189 24.7025 23.7713 23.5625 25.0855C22.4454 26.3998 20.8039 27.4195 18.638 28.1447C16.4721 28.8472 13.8616 29.1985 10.8066 29.1985C9.66666 29.1985 8.75472 29.1645 8.07075 29.0965C8.04796 29.7309 7.77438 30.2068 7.25 30.5241C6.72562 30.8414 6.05307 31 5.23231 31C4.41156 31 3.84159 30.8187 3.52241 30.4561C3.22603 30.0936 3.10062 29.561 3.14623 28.8586C3.35141 25.686 3.75039 22.3662 4.34316 18.8991C4.93593 15.4094 5.68829 12.0442 6.60024 8.80373C6.75982 8.23721 7.07901 7.84064 7.55778 7.61404C8.03656 7.38743 8.66353 7.27412 9.43868 7.27412C10.8294 7.27412 11.5248 7.65936 11.5248 8.42983C11.5248 8.74708 11.4564 9.10965 11.3196 9.51754C10.7268 11.2851 10.134 13.6871 9.54127 16.7237C8.9485 19.7375 8.52674 22.6156 8.27594 25.3575C9.37028 25.448 10.2594 25.4934 10.9434 25.4934C14.1352 25.4934 16.4721 25.0401 17.954 24.1338C19.4587 23.2046 20.2111 22.0263 20.2111 20.5987C20.2111 19.6016 19.778 18.7632 18.9116 18.0833C18.0681 17.4035 16.6431 17.0296 14.6368 16.9616C14.1808 16.939 13.8616 16.8257 13.6792 16.6217C13.4968 16.4178 13.4057 16.0892 13.4057 15.636C13.4057 14.9788 13.5425 14.4463 13.816 14.0384C14.0896 13.6305 14.5912 13.4152 15.3208 13.3925C16.9395 13.3472 18.3986 13.1093 19.6981 12.6787C21.0204 12.2482 22.0578 11.6477 22.8101 10.8772C23.5625 10.0841 23.9387 9.1663 23.9387 8.1239C23.9387 6.80958 23.2889 5.77851 21.9894 5.0307C20.6899 4.26024 18.6949 3.875 16.0047 3.875C13.5652 3.875 11.2056 4.19226 8.92571 4.82676C6.64584 5.4386 4.70793 6.2204 3.11203 7.17215C2.38246 7.6027 1.7669 7.81798 1.26533 7.81798C0.854953 7.81798 0.53577 7.68202 0.307783 7.41009C0.102594 7.1155 0 6.75292 0 6.32237C0 5.75585 0.113994 5.26864 0.341981 4.86075C0.592768 4.45285 1.17414 3.98831 2.08608 3.46711C4.00118 2.37939 6.24685 1.52961 8.82311 0.917763C11.3994 0.305921 14.0326 0 16.7229 0C20.8494 0 23.9272 0.691156 25.9564 2.07347C27.9855 3.45577 29 5.27998 29 7.54605Z'
|
||||
fill='currentColor'
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
@@ -1938,13 +1824,11 @@ export function ElevenLabsIcon(props: SVGProps<SVGSVGElement>) {
|
||||
|
||||
export function LinkupIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} xmlns='http://www.w3.org/2000/svg' viewBox='0 0 24 24'>
|
||||
<g transform='translate(12, 12) scale(1.3) translate(-12, -12)'>
|
||||
<path
|
||||
d='M20.2 14.1c-.4-.3-1.6-.4-2.9-.2.5-1.4 1.3-3.9.1-5-.6-.5-1.5-.7-2.6-.5-.3 0-.6.1-1 .2-1.1-1.6-2.4-2.5-3.8-2.5-1.6 0-3.1 1-4.1 2.9-1.2 2.1-1.9 5.1-1.9 8.8v.03l.4.3c3-.9 7.5-2.3 10.7-2.9 0 .9.1 1.9.1 2.8v.03l.4.3c.1 0 5.4-1.7 5.3-3.3 0-.2-.1-.5-.3-.7zM19.9 14.7c.03.4-1.7 1.4-4 2.3.5-.7 1-1.6 1.3-2.5 1.4-.1 2.4-.1 2.7.2zM16.4 14.6c-.3.7-.7 1.4-1.2 2-.02-.6-.1-1.2-.2-1.8.4-.1.9-.1 1.4-.2zM16.5 9.4c.8.7.9 2.4.1 5.1-.5.1-1 .1-1.5.2-.3-2-.9-3.8-1.7-5.3.3-.1.6-.2.8-.2.9-.1 1.7.05 2.3.2zM9.5 6.8c1.2 0 2.3.7 3.2 2.1-2.8 1.1-5.9 3.4-8.4 7.8.2-5.1 1.9-9.9 5.2-9.9zM4.7 17c3.4-4.9 6.4-6.8 8.4-7.8.7 1.3 1.2 2.9 1.5 4.8-3.2.6-7.3 1.8-9.9 3z'
|
||||
fill='#000000'
|
||||
/>
|
||||
</g>
|
||||
<svg {...props} xmlns='http://www.w3.org/2000/svg' viewBox='0 0 154 107' fill='none'>
|
||||
<path
|
||||
d='M150.677 72.7113C146.612 70.2493 137.909 69.542 124.794 70.6076C128.992 57.6776 133.757 35.3911 121.323 25.1527C115.886 20.6743 107.471 19.0437 97.6162 20.5594C94.6758 21.0142 91.5752 21.7445 88.3878 22.732C78.8667 8.28165 66.2954 0 53.8613 0C39.4288 0 26.1304 9.3381 16.4081 26.2872C5.67515 45.014 0 71.9626 0 104.23V104.533L3.60356 106.94L3.88251 106.825C30.5754 95.5628 67.5759 85.0718 100.593 79.4037C101.604 87.644 102.116 95.9945 102.116 104.235V104.52L105.491 107L105.761 106.913C106.255 106.752 155.159 90.8822 153.979 77.5894C153.856 76.2022 153.183 74.2271 150.677 72.7113ZM148.409 78.09C148.715 81.5442 133.236 91.0568 111.838 98.8883C115.968 92.0995 119.818 84.1715 122.777 76.3584C135.659 75.1411 144.531 75.5545 147.792 77.5296C148.377 77.8833 148.409 78.09 148.409 78.09ZM116.668 77.0106C114.084 83.3769 110.951 89.6329 107.54 95.2458C107.334 89.5135 106.913 83.8821 106.296 78.4621C109.922 77.8971 113.407 77.4102 116.668 77.0106ZM117.774 29.4979C125.379 35.7585 125.782 51.3205 118.867 71.1772C114.747 71.6319 110.284 72.2382 105.596 72.9777C103.049 55.1742 98.2839 39.966 91.4243 27.7525C94.566 26.8155 96.9669 26.3469 98.4622 26.1127C106.721 24.8404 113.581 26.0438 117.774 29.4979ZM53.8567 5.62215C65.0561 5.62215 74.8882 12.0022 83.0922 24.5923C57.7027 34.5413 30.3193 59.4092 5.78032 94.8003C7.43119 51.4813 23.0299 5.62215 53.8613 5.62215M10.1933 98.2406C40.7504 53.9341 68.2024 36.4429 86.0739 29.5852C92.4487 41.2383 97.2046 56.5522 99.8433 73.9331C70.5209 79.0316 35.6377 88.4983 10.1933 98.2406Z'
|
||||
fill='#000000'
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
@@ -2453,6 +2337,17 @@ export function OutlookIcon(props: SVGProps<SVGSVGElement>) {
|
||||
)
|
||||
}
|
||||
|
||||
export function PagerDutyIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} xmlns='http://www.w3.org/2000/svg' viewBox='0 0 64 64' fill='none'>
|
||||
<path
|
||||
d='M6.704 59.217H0v-33.65c0-3.455 1.418-5.544 2.604-6.704 2.63-2.58 6.2-2.656 6.782-2.656h10.546c3.765 0 5.93 1.52 7.117 2.8 2.346 2.553 2.372 5.853 2.32 6.73v12.687c0 3.662-1.496 5.828-2.733 6.988-2.553 2.398-5.93 2.45-6.73 2.424H6.704zm13.46-18.102c.36 0 1.367-.103 1.908-.62.413-.387.62-1.083.62-2.1v-13.02c0-.36-.077-1.315-.593-1.857-.5-.516-1.444-.62-2.166-.62h-10.6c-2.63 0-2.63 1.985-2.63 2.656v15.55zM57.296 4.783H64V38.46c0 3.455-1.418 5.544-2.604 6.704-2.63 2.58-6.2 2.656-6.782 2.656H44.068c-3.765 0-5.93-1.52-7.117-2.8-2.346-2.553-2.372-5.853-2.32-6.73V25.62c0-3.662 1.496-5.828 2.733-6.988 2.553-2.398 5.93-2.45 6.73-2.424h13.202zM43.836 22.9c-.36 0-1.367.103-1.908.62-.413.387-.62 1.083-.62 2.1v13.02c0 .36.077 1.315.593 1.857.5.516 1.444.62 2.166.62h10.598c2.656-.026 2.656-2 2.656-2.682V22.9z'
|
||||
fill='#FFFFFF'
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function MicrosoftExcelIcon(props: SVGProps<SVGSVGElement>) {
|
||||
const id = useId()
|
||||
const gradientId = `excel_gradient_${id}`
|
||||
@@ -3996,10 +3891,10 @@ export function IntercomIcon(props: SVGProps<SVGSVGElement>) {
|
||||
|
||||
export function LoopsIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} viewBox='0 0 256 256' fill='none' xmlns='http://www.w3.org/2000/svg'>
|
||||
<svg {...props} viewBox='0 0 214 186' fill='none' xmlns='http://www.w3.org/2000/svg'>
|
||||
<path
|
||||
fill='#FD4E00'
|
||||
d='M192.352 88.042c0-7.012-5.685-12.697-12.697-12.697s-12.697 5.685-12.697 12.697c0 .634.052 1.255.142 1.866a25.248 25.248 0 0 0-4.9-.49c-14.006 0-25.36 11.354-25.36 25.36 0 1.63.16 3.222.456 4.765a37.8 37.8 0 0 0-9.296-1.173c-20.95 0-37.935 16.985-37.935 37.935S107.05 194.24 128 194.24s37.935-16.985 37.935-37.935a37.7 37.7 0 0 0-3.78-16.555 25.2 25.2 0 0 0 12.487-3.336 25.2 25.2 0 0 0 4.558 3.336v.02c14.006 0 25.36-11.354 25.36-25.36 0-12.48-9.018-22.855-20.888-24.996a12.6 12.6 0 0 0 8.68-11.972m-77.05 68.263c0-7.012 5.685-12.697 12.697-12.697s12.697 5.685 12.697 12.697c0 7.013-5.685 12.697-12.697 12.697s-12.697-5.685-12.697-12.697'
|
||||
d='M122.19,0 H90.27 C40.51,0 0,39.88 0,92.95 C0,141.07 38.93,183.77 90.27,183.77 H122.19 C172.61,183.77 213.31,142.82 213.31,92.95 C213.31,43.29 173.09,0 122.19,0 Z M10.82,92.54 C10.82,50.19 45.91,11.49 91.96,11.49 C138.73,11.49 172.69,50.33 172.69,92.13 C172.69,117.76 154.06,139.09 129.02,143.31 C145.16,131.15 155.48,112.73 155.48,92.4 C155.48,59.09 127.44,28.82 92.37,28.82 C57.23,28.82 28.51,57.23 28.51,92.91 C28.51,122.63 43.61,151.08 69.99,168.21 L71.74,169.33 C35.99,161.39 10.82,130.11 10.82,92.54 Z M106.33,42.76 C128.88,50.19 143.91,68.92 143.91,92.26 C143.91,114.23 128.68,134.63 106.12,141.71 C105.44,141.96 105.17,141.96 105.17,141.96 C83.91,135.76 69.29,116.38 69.29,92.71 C69.29,69.91 83.71,50.33 106.33,42.76 Z M120.91,172.13 C76.11,172.13 40.09,137.21 40.09,93.32 C40.09,67.03 57.17,46.11 83.98,41.33 C67.04,53.83 57.3,71.71 57.3,92.71 C57.3,125.75 82.94,155.33 120.77,155.33 C155.01,155.33 184.31,125.2 184.31,92.47 C184.31,62.34 169.96,34.06 141.92,14.55 L141.65,14.34 C175.81,23.68 202.26,54.11 202.26,92.81 C202.26,135.69 166.38,172.13 120.91,172.13 Z'
|
||||
fill='#FB5001'
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
@@ -4776,6 +4671,22 @@ export function GoogleGroupsIcon(props: SVGProps<SVGSVGElement>) {
|
||||
)
|
||||
}
|
||||
|
||||
export function GoogleMeetIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 87.5 72'>
|
||||
<path fill='#00832d' d='M49.5 36l8.53 9.75 11.47 7.33 2-17.02-2-16.64-11.69 6.44z' />
|
||||
<path fill='#0066da' d='M0 51.5V66c0 3.315 2.685 6 6 6h14.5l3-10.96-3-9.54-9.95-3z' />
|
||||
<path fill='#e94235' d='M20.5 0L0 20.5l10.55 3 9.95-3 2.95-9.41z' />
|
||||
<path fill='#2684fc' d='M20.5 20.5H0v31h20.5z' />
|
||||
<path
|
||||
fill='#00ac47'
|
||||
d='M82.6 8.68L69.5 19.42v33.66l13.16 10.79c1.97 1.54 4.85.135 4.85-2.37V11c0-2.535-2.945-3.925-4.91-2.32zM49.5 36v15.5h-29V72h43c3.315 0 6-2.685 6-6V53.08z'
|
||||
/>
|
||||
<path fill='#ffba00' d='M63.5 0h-43v20.5h29V36l20-16.57V6c0-3.315-2.685-6-6-6z' />
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function CursorIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} xmlns='http://www.w3.org/2000/svg' viewBox='0 0 546 546' fill='currentColor'>
|
||||
@@ -4784,6 +4695,19 @@ export function CursorIcon(props: SVGProps<SVGSVGElement>) {
|
||||
)
|
||||
}
|
||||
|
||||
export function DubIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} viewBox='0 0 64 64' fill='none' xmlns='http://www.w3.org/2000/svg'>
|
||||
<path
|
||||
fillRule='evenodd'
|
||||
clipRule='evenodd'
|
||||
d='M32 64c17.673 0 32-14.327 32-32 0-11.844-6.435-22.186-16-27.719V48h-8v-2.14A15.9 15.9 0 0 1 32 48c-8.837 0-16-7.163-16-16s7.163-16 16-16c2.914 0 5.647.78 8 2.14V1.008A32 32 0 0 0 32 0C14.327 0 0 14.327 0 32s14.327 32 32 32'
|
||||
fill='currentColor'
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function DuckDuckGoIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} xmlns='http://www.w3.org/2000/svg' viewBox='-108 -108 216 216'>
|
||||
@@ -5578,6 +5502,35 @@ export function GoogleMapsIcon(props: SVGProps<SVGSVGElement>) {
|
||||
)
|
||||
}
|
||||
|
||||
export function GooglePagespeedIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} viewBox='-1.74 -1.81 285.55 266.85' xmlns='http://www.w3.org/2000/svg'>
|
||||
<path
|
||||
d='M272.73 37.23v179.68a18.58 18.58 0 0 1-18.57 18.59H18.65A18.58 18.58 0 0 1 .06 216.94V37.23z'
|
||||
fill='#e1e1e1'
|
||||
/>
|
||||
<path
|
||||
d='M18.65 0h235.5a18.58 18.58 0 0 1 18.58 18.56v18.67H.07V18.59A18.58 18.58 0 0 1 18.64 0z'
|
||||
fill='#c2c2c2'
|
||||
/>
|
||||
<path
|
||||
d='M136.3 92.96a99 99 0 0 0-99 99v.13c0 2.08-.12 4.64 0 6.2h43.25a54.87 54.87 0 0 1 0-6.2 55.81 55.81 0 0 1 85.06-47.45l31.12-31.12a98.76 98.76 0 0 0-60.44-20.57z'
|
||||
fill='#4285f4'
|
||||
/>
|
||||
<path
|
||||
d='M196.73 113.46l-31.14 31.14a55.74 55.74 0 0 1 26.56 47.45 54.87 54.87 0 0 1 0 6.2h43.39c.12-1.48 0-4.12 0-6.2a99 99 0 0 0-38.81-78.59z'
|
||||
fill='#f44336'
|
||||
/>
|
||||
<circle cx='24.85' cy='18.59' fill='#eee' r='6.2' />
|
||||
<circle cx='49.65' cy='18.59' fill='#eee' r='6.2' />
|
||||
<path
|
||||
d='M197.01 117.23a3.05 3.05 0 0 0 .59-1.81 3.11 3.11 0 0 0-3.1-3.1 3 3 0 0 0-1.91.68l-67.56 52a18.58 18.58 0 1 0 27.24 24.33l44.73-72.1z'
|
||||
fill='#9e9e9e'
|
||||
/>
|
||||
</svg>
|
||||
)
|
||||
}
|
||||
|
||||
export function GoogleTranslateIcon(props: SVGProps<SVGSVGElement>) {
|
||||
return (
|
||||
<svg {...props} xmlns='http://www.w3.org/2000/svg' viewBox='0 0 998.1 998.3'>
|
||||
|
||||
@@ -1,12 +1,17 @@
|
||||
'use client'
|
||||
|
||||
import Link from 'next/link'
|
||||
import { usePathname } from 'next/navigation'
|
||||
import { LanguageDropdown } from '@/components/ui/language-dropdown'
|
||||
import { SearchTrigger } from '@/components/ui/search-trigger'
|
||||
import { SimLogoFull } from '@/components/ui/sim-logo'
|
||||
import { ThemeToggle } from '@/components/ui/theme-toggle'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
export function Navbar() {
|
||||
const pathname = usePathname()
|
||||
const isApiReference = pathname.includes('/api-reference')
|
||||
|
||||
return (
|
||||
<nav className='sticky top-0 z-50 border-border/50 border-b bg-background/80 backdrop-blur-md backdrop-saturate-150'>
|
||||
{/* Desktop: Single row layout */}
|
||||
@@ -31,16 +36,30 @@ export function Navbar() {
|
||||
</div>
|
||||
|
||||
{/* Right cluster aligns with TOC edge */}
|
||||
<div className='flex items-center gap-4'>
|
||||
<div className='flex items-center gap-1'>
|
||||
<Link
|
||||
href='/introduction'
|
||||
className={cn(
|
||||
'rounded-xl px-3 py-2 font-normal text-[0.9375rem] leading-[1.4] transition-colors hover:bg-foreground/8 hover:text-foreground',
|
||||
!isApiReference ? 'text-foreground' : 'text-foreground/60'
|
||||
)}
|
||||
>
|
||||
Documentation
|
||||
</Link>
|
||||
<Link
|
||||
href='/api-reference/getting-started'
|
||||
className={cn(
|
||||
'rounded-xl px-3 py-2 font-normal text-[0.9375rem] leading-[1.4] transition-colors hover:bg-foreground/8 hover:text-foreground',
|
||||
isApiReference ? 'text-foreground' : 'text-foreground/60'
|
||||
)}
|
||||
>
|
||||
API
|
||||
</Link>
|
||||
<Link
|
||||
href='https://sim.ai'
|
||||
target='_blank'
|
||||
rel='noopener noreferrer'
|
||||
className='rounded-xl px-3 py-2 font-normal text-[0.9375rem] text-foreground/60 leading-[1.4] transition-colors hover:bg-foreground/8 hover:text-foreground'
|
||||
style={{
|
||||
fontFamily:
|
||||
'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif',
|
||||
}}
|
||||
>
|
||||
Platform
|
||||
</Link>
|
||||
|
||||
@@ -25,8 +25,8 @@ export function StructuredData({
|
||||
headline: title,
|
||||
description: description,
|
||||
url: url,
|
||||
datePublished: dateModified || new Date().toISOString(),
|
||||
dateModified: dateModified || new Date().toISOString(),
|
||||
...(dateModified && { datePublished: dateModified }),
|
||||
...(dateModified && { dateModified }),
|
||||
author: {
|
||||
'@type': 'Organization',
|
||||
name: 'Sim Team',
|
||||
@@ -91,12 +91,6 @@ export function StructuredData({
|
||||
inLanguage: ['en', 'es', 'fr', 'de', 'ja', 'zh'],
|
||||
}
|
||||
|
||||
const faqStructuredData = title.toLowerCase().includes('faq') && {
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'FAQPage',
|
||||
mainEntity: [],
|
||||
}
|
||||
|
||||
const softwareStructuredData = {
|
||||
'@context': 'https://schema.org',
|
||||
'@type': 'SoftwareApplication',
|
||||
@@ -151,15 +145,6 @@ export function StructuredData({
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{faqStructuredData && (
|
||||
<Script
|
||||
id='faq-structured-data'
|
||||
type='application/ld+json'
|
||||
dangerouslySetInnerHTML={{
|
||||
__html: JSON.stringify(faqStructuredData),
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
{url === baseUrl && (
|
||||
<Script
|
||||
id='software-structured-data'
|
||||
|
||||
@@ -9,6 +9,7 @@ import {
|
||||
AirtableIcon,
|
||||
AirweaveIcon,
|
||||
AlgoliaIcon,
|
||||
AmplitudeIcon,
|
||||
ApifyIcon,
|
||||
ApolloIcon,
|
||||
ArxivIcon,
|
||||
@@ -16,6 +17,7 @@ import {
|
||||
AshbyIcon,
|
||||
AttioIcon,
|
||||
BrainIcon,
|
||||
BrandfetchIcon,
|
||||
BrowserUseIcon,
|
||||
CalComIcon,
|
||||
CalendlyIcon,
|
||||
@@ -32,6 +34,7 @@ import {
|
||||
DocumentIcon,
|
||||
DropboxIcon,
|
||||
DsPyIcon,
|
||||
DubIcon,
|
||||
DuckDuckGoIcon,
|
||||
DynamoDBIcon,
|
||||
ElasticsearchIcon,
|
||||
@@ -56,6 +59,8 @@ import {
|
||||
GoogleGroupsIcon,
|
||||
GoogleIcon,
|
||||
GoogleMapsIcon,
|
||||
GoogleMeetIcon,
|
||||
GooglePagespeedIcon,
|
||||
GoogleSheetsIcon,
|
||||
GoogleSlidesIcon,
|
||||
GoogleTasksIcon,
|
||||
@@ -102,6 +107,7 @@ import {
|
||||
OpenAIIcon,
|
||||
OutlookIcon,
|
||||
PackageSearchIcon,
|
||||
PagerDutyIcon,
|
||||
ParallelIcon,
|
||||
PerplexityIcon,
|
||||
PineconeIcon,
|
||||
@@ -167,12 +173,14 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
|
||||
airtable: AirtableIcon,
|
||||
airweave: AirweaveIcon,
|
||||
algolia: AlgoliaIcon,
|
||||
amplitude: AmplitudeIcon,
|
||||
apify: ApifyIcon,
|
||||
apollo: ApolloIcon,
|
||||
arxiv: ArxivIcon,
|
||||
asana: AsanaIcon,
|
||||
ashby: AshbyIcon,
|
||||
attio: AttioIcon,
|
||||
brandfetch: BrandfetchIcon,
|
||||
browser_use: BrowserUseIcon,
|
||||
calcom: CalComIcon,
|
||||
calendly: CalendlyIcon,
|
||||
@@ -188,6 +196,7 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
|
||||
discord: DiscordIcon,
|
||||
dropbox: DropboxIcon,
|
||||
dspy: DsPyIcon,
|
||||
dub: DubIcon,
|
||||
duckduckgo: DuckDuckGoIcon,
|
||||
dynamodb: DynamoDBIcon,
|
||||
elasticsearch: ElasticsearchIcon,
|
||||
@@ -211,6 +220,8 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
|
||||
google_forms: GoogleFormsIcon,
|
||||
google_groups: GoogleGroupsIcon,
|
||||
google_maps: GoogleMapsIcon,
|
||||
google_meet: GoogleMeetIcon,
|
||||
google_pagespeed: GooglePagespeedIcon,
|
||||
google_search: GoogleIcon,
|
||||
google_sheets_v2: GoogleSheetsIcon,
|
||||
google_slides_v2: GoogleSlidesIcon,
|
||||
@@ -258,6 +269,7 @@ export const blockTypeToIconMap: Record<string, IconComponent> = {
|
||||
onepassword: OnePasswordIcon,
|
||||
openai: OpenAIIcon,
|
||||
outlook: OutlookIcon,
|
||||
pagerduty: PagerDutyIcon,
|
||||
parallel_ai: ParallelIcon,
|
||||
perplexity: PerplexityIcon,
|
||||
pinecone: PineconeIcon,
|
||||
|
||||
169
apps/docs/components/ui/response-section.tsx
Normal file
169
apps/docs/components/ui/response-section.tsx
Normal file
@@ -0,0 +1,169 @@
|
||||
'use client'
|
||||
|
||||
import { useEffect, useRef, useState } from 'react'
|
||||
import { ChevronDown } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
interface ResponseSectionProps {
|
||||
children: React.ReactNode
|
||||
}
|
||||
|
||||
export function ResponseSection({ children }: ResponseSectionProps) {
|
||||
const containerRef = useRef<HTMLDivElement>(null)
|
||||
const [statusCodes, setStatusCodes] = useState<string[]>([])
|
||||
const [selectedCode, setSelectedCode] = useState<string>('')
|
||||
const [isOpen, setIsOpen] = useState(false)
|
||||
const dropdownRef = useRef<HTMLDivElement>(null)
|
||||
|
||||
function getAccordionItems() {
|
||||
const root = containerRef.current?.querySelector('[data-orientation="vertical"]')
|
||||
if (!root) return []
|
||||
return Array.from(root.children).filter(
|
||||
(el) => el.getAttribute('data-state') !== null
|
||||
) as HTMLElement[]
|
||||
}
|
||||
|
||||
function showStatusCode(code: string) {
|
||||
const items = getAccordionItems()
|
||||
for (const item of items) {
|
||||
const triggerBtn = item.querySelector('h3 button') as HTMLButtonElement | null
|
||||
const text = triggerBtn?.textContent?.trim() ?? ''
|
||||
const itemCode = text.match(/^\d{3}/)?.[0]
|
||||
|
||||
if (itemCode === code) {
|
||||
item.style.display = ''
|
||||
if (item.getAttribute('data-state') === 'closed' && triggerBtn) {
|
||||
triggerBtn.click()
|
||||
}
|
||||
} else {
|
||||
item.style.display = 'none'
|
||||
if (item.getAttribute('data-state') === 'open' && triggerBtn) {
|
||||
triggerBtn.click()
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Detect when the fumadocs accordion children mount via MutationObserver,
|
||||
* then extract status codes and show the first one.
|
||||
* Replaces the previous approach that used `children` as a dependency
|
||||
* (which triggered on every render since children is a new object each time).
|
||||
*/
|
||||
useEffect(() => {
|
||||
const container = containerRef.current
|
||||
if (!container) return
|
||||
|
||||
const initialize = () => {
|
||||
const items = getAccordionItems()
|
||||
if (items.length === 0) return false
|
||||
|
||||
const codes: string[] = []
|
||||
const seen = new Set<string>()
|
||||
|
||||
for (const item of items) {
|
||||
const triggerBtn = item.querySelector('h3 button')
|
||||
if (triggerBtn) {
|
||||
const text = triggerBtn.textContent?.trim() ?? ''
|
||||
const code = text.match(/^\d{3}/)?.[0]
|
||||
if (code && !seen.has(code)) {
|
||||
seen.add(code)
|
||||
codes.push(code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (codes.length > 0) {
|
||||
setStatusCodes(codes)
|
||||
setSelectedCode(codes[0])
|
||||
showStatusCode(codes[0])
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
if (initialize()) return
|
||||
|
||||
const observer = new MutationObserver(() => {
|
||||
if (initialize()) {
|
||||
observer.disconnect()
|
||||
}
|
||||
})
|
||||
observer.observe(container, { childList: true, subtree: true })
|
||||
|
||||
return () => observer.disconnect()
|
||||
}, []) // eslint-disable-line react-hooks/exhaustive-deps
|
||||
|
||||
function handleSelectCode(code: string) {
|
||||
setSelectedCode(code)
|
||||
setIsOpen(false)
|
||||
showStatusCode(code)
|
||||
}
|
||||
|
||||
useEffect(() => {
|
||||
function handleClickOutside(event: MouseEvent) {
|
||||
if (dropdownRef.current && !dropdownRef.current.contains(event.target as Node)) {
|
||||
setIsOpen(false)
|
||||
}
|
||||
}
|
||||
document.addEventListener('mousedown', handleClickOutside)
|
||||
return () => document.removeEventListener('mousedown', handleClickOutside)
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div ref={containerRef} className='response-section-wrapper'>
|
||||
{statusCodes.length > 0 && (
|
||||
<div className='response-section-header'>
|
||||
<h2 className='response-section-title'>Response</h2>
|
||||
<div className='response-section-meta'>
|
||||
<div ref={dropdownRef} className='response-section-dropdown-wrapper'>
|
||||
<button
|
||||
type='button'
|
||||
className='response-section-dropdown-trigger'
|
||||
onClick={() => setIsOpen(!isOpen)}
|
||||
>
|
||||
<span>{selectedCode}</span>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
'response-section-chevron',
|
||||
isOpen && 'response-section-chevron-open'
|
||||
)}
|
||||
/>
|
||||
</button>
|
||||
{isOpen && (
|
||||
<div className='response-section-dropdown-menu'>
|
||||
{statusCodes.map((code) => (
|
||||
<button
|
||||
key={code}
|
||||
type='button'
|
||||
className={cn(
|
||||
'response-section-dropdown-item',
|
||||
code === selectedCode && 'response-section-dropdown-item-selected'
|
||||
)}
|
||||
onClick={() => handleSelectCode(code)}
|
||||
>
|
||||
<span>{code}</span>
|
||||
{code === selectedCode && (
|
||||
<svg
|
||||
className='response-section-check'
|
||||
viewBox='0 0 24 24'
|
||||
fill='none'
|
||||
stroke='currentColor'
|
||||
strokeWidth='2'
|
||||
>
|
||||
<polyline points='20 6 9 17 4 12' />
|
||||
</svg>
|
||||
)}
|
||||
</button>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<span className='response-section-content-type'>application/json</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
<div className='response-section-content'>{children}</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
94
apps/docs/content/docs/de/api-reference/authentication.mdx
Normal file
94
apps/docs/content/docs/de/api-reference/authentication.mdx
Normal file
@@ -0,0 +1,94 @@
|
||||
---
|
||||
title: Authentication
|
||||
description: API key types, generation, and how to authenticate requests
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
|
||||
To access the Sim API, you need an API key. Sim supports two types of API keys — **personal keys** and **workspace keys** — each with different billing and access behaviors.
|
||||
|
||||
## Key Types
|
||||
|
||||
| | **Personal Keys** | **Workspace Keys** |
|
||||
| --- | --- | --- |
|
||||
| **Billed to** | Your individual account | Workspace owner |
|
||||
| **Scope** | Across workspaces you have access to | Shared across the workspace |
|
||||
| **Managed by** | Each user individually | Workspace admins |
|
||||
| **Permissions** | Must be enabled at workspace level | Require admin permissions |
|
||||
|
||||
<Callout type="info">
|
||||
Workspace admins can disable personal API key usage for their workspace. If disabled, only workspace keys can be used.
|
||||
</Callout>
|
||||
|
||||
## Generating API Keys
|
||||
|
||||
To generate a key, open the Sim dashboard and navigate to **Settings**, then go to **Sim Keys** and click **Create**.
|
||||
|
||||
<Callout type="warn">
|
||||
API keys are only shown once when generated. Store your key securely — you will not be able to view it again.
|
||||
</Callout>
|
||||
|
||||
## Using API Keys
|
||||
|
||||
Pass your API key in the `X-API-Key` header with every request:
|
||||
|
||||
<Tabs items={['curl', 'TypeScript', 'Python']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch(
|
||||
'https://www.sim.ai/api/workflows/{workflowId}/execute',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': process.env.SIM_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify({ inputs: {} }),
|
||||
}
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
```python
|
||||
import requests
|
||||
|
||||
response = requests.post(
|
||||
"https://www.sim.ai/api/workflows/{workflowId}/execute",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": os.environ["SIM_API_KEY"],
|
||||
},
|
||||
json={"inputs": {}},
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Where Keys Are Used
|
||||
|
||||
API keys authenticate access to:
|
||||
|
||||
- **Workflow execution** — run deployed workflows via the API
|
||||
- **Logs API** — query workflow execution logs and metrics
|
||||
- **MCP servers** — authenticate connections to deployed MCP servers
|
||||
- **SDKs** — the [Python](/api-reference/python) and [TypeScript](/api-reference/typescript) SDKs use API keys for all operations
|
||||
|
||||
## Security
|
||||
|
||||
- Keys use the `sk-sim-` prefix and are encrypted at rest
|
||||
- Keys can be revoked at any time from the dashboard
|
||||
- Use environment variables to store keys — never hardcode them in source code
|
||||
- For browser-based applications, use a backend proxy to avoid exposing keys to the client
|
||||
|
||||
<Callout type="warn">
|
||||
Never expose your API key in client-side code. Use a server-side proxy to make authenticated requests on behalf of your frontend.
|
||||
</Callout>
|
||||
210
apps/docs/content/docs/de/api-reference/getting-started.mdx
Normal file
210
apps/docs/content/docs/de/api-reference/getting-started.mdx
Normal file
@@ -0,0 +1,210 @@
|
||||
---
|
||||
title: Getting Started
|
||||
description: Base URL, first API call, response format, error handling, and pagination
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
|
||||
## Base URL
|
||||
|
||||
All API requests are made to:
|
||||
|
||||
```
|
||||
https://www.sim.ai
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step>
|
||||
### Get your API key
|
||||
|
||||
Go to the Sim dashboard and navigate to **Settings → Sim Keys**, then click **Create**. See [Authentication](/api-reference/authentication) for details on key types.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Find your workflow ID
|
||||
|
||||
Open a workflow in the Sim editor. The workflow ID is in the URL:
|
||||
|
||||
```
|
||||
https://www.sim.ai/workspace/{workspaceId}/w/{workflowId}
|
||||
```
|
||||
|
||||
You can also use the [List Workflows](/api-reference/workflows/listWorkflows) endpoint to get all workflow IDs in a workspace.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Deploy your workflow
|
||||
|
||||
A workflow must be deployed before it can be executed via the API. Click the **Deploy** button in the editor toolbar.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Make your first request
|
||||
|
||||
<Tabs items={['curl', 'TypeScript', 'Python']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch(
|
||||
`https://www.sim.ai/api/workflows/${workflowId}/execute`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': process.env.SIM_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify({ inputs: {} }),
|
||||
}
|
||||
)
|
||||
|
||||
const data = await response.json()
|
||||
console.log(data.output)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
```python
|
||||
import requests
|
||||
import os
|
||||
|
||||
response = requests.post(
|
||||
f"https://www.sim.ai/api/workflows/{workflow_id}/execute",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": os.environ["SIM_API_KEY"],
|
||||
},
|
||||
json={"inputs": {}},
|
||||
)
|
||||
|
||||
data = response.json()
|
||||
print(data["output"])
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## Sync vs Async Execution
|
||||
|
||||
By default, workflow executions are **synchronous** — the API blocks until the workflow completes and returns the result directly.
|
||||
|
||||
For long-running workflows, use **asynchronous execution** by passing `async: true`:
|
||||
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}, "async": true}'
|
||||
```
|
||||
|
||||
This returns immediately with a `taskId`:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"taskId": "job_abc123",
|
||||
"status": "queued"
|
||||
}
|
||||
```
|
||||
|
||||
Poll the [Get Job Status](/api-reference/workflows/getJobStatus) endpoint until the status is `completed` or `failed`:
|
||||
|
||||
```bash
|
||||
curl https://www.sim.ai/api/jobs/{taskId} \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
```
|
||||
|
||||
<Callout type="info">
|
||||
Job status transitions follow: `queued` → `processing` → `completed` or `failed`. The `output` field is only present when status is `completed`.
|
||||
</Callout>
|
||||
|
||||
## Response Format
|
||||
|
||||
Successful responses include an `output` object with your workflow results and a `limits` object with your current rate limit and usage status:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"output": {
|
||||
"result": "Hello, world!"
|
||||
},
|
||||
"limits": {
|
||||
"workflowExecutionRateLimit": {
|
||||
"sync": {
|
||||
"requestsPerMinute": 60,
|
||||
"maxBurst": 10,
|
||||
"remaining": 59,
|
||||
"resetAt": "2025-01-01T00:01:00Z"
|
||||
},
|
||||
"async": {
|
||||
"requestsPerMinute": 30,
|
||||
"maxBurst": 5,
|
||||
"remaining": 30,
|
||||
"resetAt": "2025-01-01T00:01:00Z"
|
||||
}
|
||||
},
|
||||
"usage": {
|
||||
"currentPeriodCost": 1.25,
|
||||
"limit": 50.00,
|
||||
"plan": "pro",
|
||||
"isExceeded": false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The API uses standard HTTP status codes. Error responses include a human-readable `error` message:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Workflow not found"
|
||||
}
|
||||
```
|
||||
|
||||
| Status | Meaning | What to do |
|
||||
| --- | --- | --- |
|
||||
| `400` | Invalid request parameters | Check the `details` array for specific field errors |
|
||||
| `401` | Missing or invalid API key | Verify your `X-API-Key` header |
|
||||
| `403` | Access denied | Check you have permission for this resource |
|
||||
| `404` | Resource not found | Verify the ID exists and belongs to your workspace |
|
||||
| `429` | Rate limit exceeded | Wait for the duration in the `Retry-After` header |
|
||||
|
||||
<Callout type="info">
|
||||
Use the [Get Usage Limits](/api-reference/usage/getUsageLimits) endpoint to check your current rate limit status and billing usage at any time.
|
||||
</Callout>
|
||||
|
||||
## Rate Limits
|
||||
|
||||
Rate limits depend on your subscription plan and apply separately to synchronous and asynchronous executions. Every execution response includes a `limits` object showing your current rate limit status.
|
||||
|
||||
When rate limited, the API returns a `429` response with a `Retry-After` header indicating how many seconds to wait before retrying.
|
||||
|
||||
## Pagination
|
||||
|
||||
List endpoints (workflows, logs, audit logs) use **cursor-based pagination**:
|
||||
|
||||
```bash
|
||||
# First page
|
||||
curl "https://www.sim.ai/api/v1/logs?limit=20" \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
|
||||
# Next page — use the nextCursor from the previous response
|
||||
curl "https://www.sim.ai/api/v1/logs?limit=20&cursor=abc123" \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
```
|
||||
|
||||
The response includes a `nextCursor` field. When `nextCursor` is absent or `null`, you have reached the last page.
|
||||
16
apps/docs/content/docs/de/api-reference/meta.json
Normal file
16
apps/docs/content/docs/de/api-reference/meta.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"title": "API Reference",
|
||||
"root": true,
|
||||
"pages": [
|
||||
"getting-started",
|
||||
"authentication",
|
||||
"---SDKs---",
|
||||
"python",
|
||||
"typescript",
|
||||
"---Endpoints---",
|
||||
"(generated)/workflows",
|
||||
"(generated)/logs",
|
||||
"(generated)/usage",
|
||||
"(generated)/audit-logs"
|
||||
]
|
||||
}
|
||||
766
apps/docs/content/docs/de/api-reference/python.mdx
Normal file
766
apps/docs/content/docs/de/api-reference/python.mdx
Normal file
@@ -0,0 +1,766 @@
|
||||
---
|
||||
title: Python
|
||||
---
|
||||
|
||||
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'
|
||||
|
||||
Das offizielle Python SDK für Sim ermöglicht es Ihnen, Workflows programmatisch aus Ihren Python-Anwendungen heraus mit dem offiziellen Python SDK auszuführen.
|
||||
|
||||
<Callout type="info">
|
||||
Das Python SDK unterstützt Python 3.8+ mit Unterstützung für asynchrone Ausführung, automatischer Ratenbegrenzung mit exponentiellem Backoff und Nutzungsverfolgung.
|
||||
</Callout>
|
||||
|
||||
## Installation
|
||||
|
||||
Installieren Sie das SDK mit pip:
|
||||
|
||||
```bash
|
||||
pip install simstudio-sdk
|
||||
```
|
||||
|
||||
## Schnellstart
|
||||
|
||||
Hier ist ein einfaches Beispiel für den Einstieg:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Initialize the client
|
||||
client = SimStudioClient(
|
||||
api_key="your-api-key-here",
|
||||
base_url="https://sim.ai" # optional, defaults to https://sim.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-Referenz
|
||||
|
||||
### SimStudioClient
|
||||
|
||||
#### Konstruktor
|
||||
|
||||
```python
|
||||
SimStudioClient(api_key: str, base_url: str = "https://sim.ai")
|
||||
```
|
||||
|
||||
**Parameter:**
|
||||
- `api_key` (str): Ihr Sim API-Schlüssel
|
||||
- `base_url` (str, optional): Basis-URL für die Sim API
|
||||
|
||||
#### Methoden
|
||||
|
||||
##### execute_workflow()
|
||||
|
||||
Führt einen Workflow mit optionalen Eingabedaten aus.
|
||||
|
||||
```python
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"message": "Hello, world!"},
|
||||
timeout=30.0 # 30 seconds
|
||||
)
|
||||
```
|
||||
|
||||
**Parameter:**
|
||||
- `workflow_id` (str): Die ID des auszuführenden Workflows
|
||||
- `input_data` (dict, optional): Eingabedaten, die an den Workflow übergeben werden
|
||||
- `timeout` (float, optional): Timeout in Sekunden (Standard: 30.0)
|
||||
- `stream` (bool, optional): Streaming-Antworten aktivieren (Standard: False)
|
||||
- `selected_outputs` (list[str], optional): Block-Ausgaben zum Streamen im Format `blockName.attribute` (z. B. `["agent1.content"]`)
|
||||
- `async_execution` (bool, optional): Asynchron ausführen (Standard: False)
|
||||
|
||||
**Rückgabewert:** `WorkflowExecutionResult | AsyncExecutionResult`
|
||||
|
||||
Wenn `async_execution=True`, wird sofort mit einer Task-ID zum Polling zurückgegeben. Andernfalls wird auf die Fertigstellung gewartet.
|
||||
|
||||
##### get_workflow_status()
|
||||
|
||||
Ruft den Status eines Workflows ab (Deployment-Status usw.).
|
||||
|
||||
```python
|
||||
status = client.get_workflow_status("workflow-id")
|
||||
print("Is deployed:", status.is_deployed)
|
||||
```
|
||||
|
||||
**Parameter:**
|
||||
- `workflow_id` (str): Die ID des Workflows
|
||||
|
||||
**Rückgabe:** `WorkflowStatus`
|
||||
|
||||
##### validate_workflow()
|
||||
|
||||
Überprüft, ob ein Workflow zur Ausführung bereit ist.
|
||||
|
||||
```python
|
||||
is_ready = client.validate_workflow("workflow-id")
|
||||
if is_ready:
|
||||
# Workflow is deployed and ready
|
||||
pass
|
||||
```
|
||||
|
||||
**Parameter:**
|
||||
- `workflow_id` (str): Die ID des Workflows
|
||||
|
||||
**Rückgabe:** `bool`
|
||||
|
||||
##### get_job_status()
|
||||
|
||||
Ruft den Status einer asynchronen Job-Ausführung ab.
|
||||
|
||||
```python
|
||||
status = client.get_job_status("task-id-from-async-execution")
|
||||
print("Status:", status["status"]) # 'queued', 'processing', 'completed', 'failed'
|
||||
if status["status"] == "completed":
|
||||
print("Output:", status["output"])
|
||||
```
|
||||
|
||||
**Parameter:**
|
||||
- `task_id` (str): Die Task-ID, die von der asynchronen Ausführung zurückgegeben wurde
|
||||
|
||||
**Rückgabe:** `Dict[str, Any]`
|
||||
|
||||
**Antwortfelder:**
|
||||
- `success` (bool): Ob die Anfrage erfolgreich war
|
||||
- `taskId` (str): Die Task-ID
|
||||
- `status` (str): Einer von `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
|
||||
- `metadata` (dict): Enthält `startedAt`, `completedAt` und `duration`
|
||||
- `output` (any, optional): Die Workflow-Ausgabe (wenn abgeschlossen)
|
||||
- `error` (any, optional): Fehlerdetails (wenn fehlgeschlagen)
|
||||
- `estimatedDuration` (int, optional): Geschätzte Dauer in Millisekunden (wenn in Bearbeitung/in Warteschlange)
|
||||
|
||||
##### execute_with_retry()
|
||||
|
||||
Führt einen Workflow mit automatischer Wiederholung bei Rate-Limit-Fehlern unter Verwendung von exponentiellem Backoff aus.
|
||||
|
||||
```python
|
||||
result = client.execute_with_retry(
|
||||
"workflow-id",
|
||||
input_data={"message": "Hello"},
|
||||
timeout=30.0,
|
||||
max_retries=3, # Maximum number of retries
|
||||
initial_delay=1.0, # Initial delay in seconds
|
||||
max_delay=30.0, # Maximum delay in seconds
|
||||
backoff_multiplier=2.0 # Exponential backoff multiplier
|
||||
)
|
||||
```
|
||||
|
||||
**Parameter:**
|
||||
- `workflow_id` (str): Die ID des auszuführenden Workflows
|
||||
- `input_data` (dict, optional): Eingabedaten, die an den Workflow übergeben werden
|
||||
- `timeout` (float, optional): Timeout in Sekunden
|
||||
- `stream` (bool, optional): Streaming-Antworten aktivieren
|
||||
- `selected_outputs` (list, optional): Block-Ausgaben zum Streamen
|
||||
- `async_execution` (bool, optional): Asynchron ausführen
|
||||
- `max_retries` (int, optional): Maximale Anzahl von Wiederholungen (Standard: 3)
|
||||
- `initial_delay` (float, optional): Anfangsverzögerung in Sekunden (Standard: 1.0)
|
||||
- `max_delay` (float, optional): Maximale Verzögerung in Sekunden (Standard: 30.0)
|
||||
- `backoff_multiplier` (float, optional): Backoff-Multiplikator (Standard: 2.0)
|
||||
|
||||
**Rückgabe:** `WorkflowExecutionResult | AsyncExecutionResult`
|
||||
|
||||
Die Wiederholungslogik verwendet exponentielles Backoff (1s → 2s → 4s → 8s...) mit ±25% Jitter, um Thundering Herd zu verhindern. Wenn die API einen `retry-after`-Header bereitstellt, wird dieser stattdessen verwendet.
|
||||
|
||||
##### get_rate_limit_info()
|
||||
|
||||
Ruft die aktuellen Rate-Limit-Informationen aus der letzten API-Antwort ab.
|
||||
|
||||
```python
|
||||
rate_limit_info = client.get_rate_limit_info()
|
||||
if rate_limit_info:
|
||||
print("Limit:", rate_limit_info.limit)
|
||||
print("Remaining:", rate_limit_info.remaining)
|
||||
print("Reset:", datetime.fromtimestamp(rate_limit_info.reset))
|
||||
```
|
||||
|
||||
**Rückgabewert:** `RateLimitInfo | None`
|
||||
|
||||
##### get_usage_limits()
|
||||
|
||||
Ruft aktuelle Nutzungslimits und Kontingentinformationen für Ihr Konto ab.
|
||||
|
||||
```python
|
||||
limits = client.get_usage_limits()
|
||||
print("Sync requests remaining:", limits.rate_limit["sync"]["remaining"])
|
||||
print("Async requests remaining:", limits.rate_limit["async"]["remaining"])
|
||||
print("Current period cost:", limits.usage["currentPeriodCost"])
|
||||
print("Plan:", limits.usage["plan"])
|
||||
```
|
||||
|
||||
**Rückgabewert:** `UsageLimits`
|
||||
|
||||
**Antwortstruktur:**
|
||||
|
||||
```python
|
||||
{
|
||||
"success": bool,
|
||||
"rateLimit": {
|
||||
"sync": {
|
||||
"isLimited": bool,
|
||||
"limit": int,
|
||||
"remaining": int,
|
||||
"resetAt": str
|
||||
},
|
||||
"async": {
|
||||
"isLimited": bool,
|
||||
"limit": int,
|
||||
"remaining": int,
|
||||
"resetAt": str
|
||||
},
|
||||
"authType": str # 'api' or 'manual'
|
||||
},
|
||||
"usage": {
|
||||
"currentPeriodCost": float,
|
||||
"limit": float,
|
||||
"plan": str # e.g., 'free', 'pro'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### set_api_key()
|
||||
|
||||
Aktualisiert den API-Schlüssel.
|
||||
|
||||
```python
|
||||
client.set_api_key("new-api-key")
|
||||
```
|
||||
|
||||
##### set_base_url()
|
||||
|
||||
Aktualisiert die Basis-URL.
|
||||
|
||||
```python
|
||||
client.set_base_url("https://my-custom-domain.com")
|
||||
```
|
||||
|
||||
##### close()
|
||||
|
||||
Schließt die zugrunde liegende HTTP-Sitzung.
|
||||
|
||||
```python
|
||||
client.close()
|
||||
```
|
||||
|
||||
## Datenklassen
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
### AsyncExecutionResult
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class AsyncExecutionResult:
|
||||
success: bool
|
||||
task_id: str
|
||||
status: str # 'queued'
|
||||
created_at: str
|
||||
links: Dict[str, str] # e.g., {"status": "/api/jobs/{taskId}"}
|
||||
```
|
||||
|
||||
### WorkflowStatus
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class WorkflowStatus:
|
||||
is_deployed: bool
|
||||
deployed_at: Optional[str] = None
|
||||
needs_redeployment: bool = False
|
||||
```
|
||||
|
||||
### RateLimitInfo
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class RateLimitInfo:
|
||||
limit: int
|
||||
remaining: int
|
||||
reset: int
|
||||
retry_after: Optional[int] = None
|
||||
```
|
||||
|
||||
### UsageLimits
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class UsageLimits:
|
||||
success: bool
|
||||
rate_limit: Dict[str, Any]
|
||||
usage: Dict[str, Any]
|
||||
```
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
**Häufige Fehlercodes:**
|
||||
- `UNAUTHORIZED`: Ungültiger API-Schlüssel
|
||||
- `TIMEOUT`: Zeitüberschreitung der Anfrage
|
||||
- `RATE_LIMIT_EXCEEDED`: Ratenlimit überschritten
|
||||
- `USAGE_LIMIT_EXCEEDED`: Nutzungslimit überschritten
|
||||
- `EXECUTION_ERROR`: Workflow-Ausführung fehlgeschlagen
|
||||
|
||||
## Beispiele
|
||||
|
||||
### Grundlegende Workflow-Ausführung
|
||||
|
||||
<Steps>
|
||||
<Step title="Client initialisieren">
|
||||
Richten Sie den SimStudioClient mit Ihrem API-Schlüssel ein.
|
||||
</Step>
|
||||
<Step title="Workflow validieren">
|
||||
Prüfen Sie, ob der Workflow bereitgestellt und zur Ausführung bereit ist.
|
||||
</Step>
|
||||
<Step title="Workflow ausführen">
|
||||
Führen Sie den Workflow mit Ihren Eingabedaten aus.
|
||||
</Step>
|
||||
<Step title="Ergebnis verarbeiten">
|
||||
Verarbeiten Sie das Ausführungsergebnis und behandeln Sie eventuelle Fehler.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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()
|
||||
```
|
||||
|
||||
### Fehlerbehandlung
|
||||
|
||||
Behandeln Sie verschiedene Fehlertypen, die während der Workflow-Ausführung auftreten können:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient, SimStudioError
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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
|
||||
```
|
||||
|
||||
### Verwendung des Context-Managers
|
||||
|
||||
Verwenden Sie den Client als Context-Manager, um die Ressourcenbereinigung automatisch zu handhaben:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
# Using context manager to automatically close the session
|
||||
with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client:
|
||||
result = client.execute_workflow("workflow-id")
|
||||
print("Result:", result)
|
||||
# Session is automatically closed here
|
||||
```
|
||||
|
||||
### Batch-Workflow-Ausführung
|
||||
|
||||
Führen Sie mehrere Workflows effizient aus:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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'}")
|
||||
```
|
||||
|
||||
### Asynchrone Workflow-Ausführung
|
||||
|
||||
Führen Sie Workflows asynchron für langwierige Aufgaben aus:
|
||||
|
||||
```python
|
||||
import os
|
||||
import time
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_async():
|
||||
try:
|
||||
# Start async execution
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"data": "large dataset"},
|
||||
async_execution=True # Execute asynchronously
|
||||
)
|
||||
|
||||
# Check if result is an async execution
|
||||
if hasattr(result, 'task_id'):
|
||||
print(f"Task ID: {result.task_id}")
|
||||
print(f"Status endpoint: {result.links['status']}")
|
||||
|
||||
# Poll for completion
|
||||
status = client.get_job_status(result.task_id)
|
||||
|
||||
while status["status"] in ["queued", "processing"]:
|
||||
print(f"Current status: {status['status']}")
|
||||
time.sleep(2) # Wait 2 seconds
|
||||
status = client.get_job_status(result.task_id)
|
||||
|
||||
if status["status"] == "completed":
|
||||
print("Workflow completed!")
|
||||
print(f"Output: {status['output']}")
|
||||
print(f"Duration: {status['metadata']['duration']}")
|
||||
else:
|
||||
print(f"Workflow failed: {status['error']}")
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error: {error}")
|
||||
|
||||
execute_async()
|
||||
```
|
||||
|
||||
### Ratenlimitierung und Wiederholung
|
||||
|
||||
Behandeln Sie Ratenbegrenzungen automatisch mit exponentiellem Backoff:
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient, SimStudioError
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_with_retry_handling():
|
||||
try:
|
||||
# Automatically retries on rate limit
|
||||
result = client.execute_with_retry(
|
||||
"workflow-id",
|
||||
input_data={"message": "Process this"},
|
||||
max_retries=5,
|
||||
initial_delay=1.0,
|
||||
max_delay=60.0,
|
||||
backoff_multiplier=2.0
|
||||
)
|
||||
|
||||
print(f"Success: {result}")
|
||||
except SimStudioError as error:
|
||||
if error.code == "RATE_LIMIT_EXCEEDED":
|
||||
print("Rate limit exceeded after all retries")
|
||||
|
||||
# Check rate limit info
|
||||
rate_limit_info = client.get_rate_limit_info()
|
||||
if rate_limit_info:
|
||||
from datetime import datetime
|
||||
reset_time = datetime.fromtimestamp(rate_limit_info.reset)
|
||||
print(f"Rate limit resets at: {reset_time}")
|
||||
|
||||
execute_with_retry_handling()
|
||||
```
|
||||
|
||||
### Nutzungsüberwachung
|
||||
|
||||
Überwachen Sie die Nutzung und Limits Ihres Kontos:
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def check_usage():
|
||||
try:
|
||||
limits = client.get_usage_limits()
|
||||
|
||||
print("=== Rate Limits ===")
|
||||
print("Sync requests:")
|
||||
print(f" Limit: {limits.rate_limit['sync']['limit']}")
|
||||
print(f" Remaining: {limits.rate_limit['sync']['remaining']}")
|
||||
print(f" Resets at: {limits.rate_limit['sync']['resetAt']}")
|
||||
print(f" Is limited: {limits.rate_limit['sync']['isLimited']}")
|
||||
|
||||
print("\nAsync requests:")
|
||||
print(f" Limit: {limits.rate_limit['async']['limit']}")
|
||||
print(f" Remaining: {limits.rate_limit['async']['remaining']}")
|
||||
print(f" Resets at: {limits.rate_limit['async']['resetAt']}")
|
||||
print(f" Is limited: {limits.rate_limit['async']['isLimited']}")
|
||||
|
||||
print("\n=== Usage ===")
|
||||
print(f"Current period cost: ${limits.usage['currentPeriodCost']:.2f}")
|
||||
print(f"Limit: ${limits.usage['limit']:.2f}")
|
||||
print(f"Plan: {limits.usage['plan']}")
|
||||
|
||||
percent_used = (limits.usage['currentPeriodCost'] / limits.usage['limit']) * 100
|
||||
print(f"Usage: {percent_used:.1f}%")
|
||||
|
||||
if percent_used > 80:
|
||||
print("⚠️ Warning: You are approaching your usage limit!")
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error checking usage: {error}")
|
||||
|
||||
check_usage()
|
||||
```
|
||||
|
||||
### Streaming-Workflow-Ausführung
|
||||
|
||||
Führen Sie Workflows mit Echtzeit-Streaming-Antworten aus:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_with_streaming():
|
||||
"""Execute workflow with streaming enabled."""
|
||||
try:
|
||||
# Enable streaming for specific block outputs
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"message": "Count to five"},
|
||||
stream=True,
|
||||
selected_outputs=["agent1.content"] # Use blockName.attribute format
|
||||
)
|
||||
|
||||
print("Workflow result:", result)
|
||||
except Exception as error:
|
||||
print("Error:", error)
|
||||
|
||||
execute_with_streaming()
|
||||
```
|
||||
|
||||
Die Streaming-Antwort folgt dem Server-Sent-Events- (SSE-) Format:
|
||||
|
||||
```
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
|
||||
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"}
|
||||
|
||||
data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
|
||||
|
||||
data: [DONE]
|
||||
```
|
||||
|
||||
**Flask-Streaming-Beispiel:**
|
||||
|
||||
```python
|
||||
from flask import Flask, Response, stream_with_context
|
||||
import requests
|
||||
import json
|
||||
import os
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route('/stream-workflow')
|
||||
def stream_workflow():
|
||||
"""Stream workflow execution to the client."""
|
||||
|
||||
def generate():
|
||||
response = requests.post(
|
||||
'https://sim.ai/api/workflows/WORKFLOW_ID/execute',
|
||||
headers={
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': os.getenv('SIM_API_KEY')
|
||||
},
|
||||
json={
|
||||
'message': 'Generate a story',
|
||||
'stream': True,
|
||||
'selectedOutputs': ['agent1.content']
|
||||
},
|
||||
stream=True
|
||||
)
|
||||
|
||||
for line in response.iter_lines():
|
||||
if line:
|
||||
decoded_line = line.decode('utf-8')
|
||||
if decoded_line.startswith('data: '):
|
||||
data = decoded_line[6:] # Remove 'data: ' prefix
|
||||
|
||||
if data == '[DONE]':
|
||||
break
|
||||
|
||||
try:
|
||||
parsed = json.loads(data)
|
||||
if 'chunk' in parsed:
|
||||
yield f"data: {json.dumps(parsed)}\n\n"
|
||||
elif parsed.get('event') == 'done':
|
||||
yield f"data: {json.dumps(parsed)}\n\n"
|
||||
print("Execution complete:", parsed.get('metadata'))
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
return Response(
|
||||
stream_with_context(generate()),
|
||||
mimetype='text/event-stream'
|
||||
)
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
```
|
||||
|
||||
### Umgebungskonfiguration
|
||||
|
||||
Konfigurieren Sie den Client mit Umgebungsvariablen:
|
||||
|
||||
<Tabs items={['Development', 'Production']}>
|
||||
<Tab value="Development">
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Development configuration
|
||||
client = SimStudioClient(
|
||||
api_key=os.getenv("SIM_API_KEY")
|
||||
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
|
||||
)
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value="Production">
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Production configuration with error handling
|
||||
api_key = os.getenv("SIM_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("SIM_API_KEY environment variable is required")
|
||||
|
||||
client = SimStudioClient(
|
||||
api_key=api_key,
|
||||
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
|
||||
)
|
||||
```
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Ihren API-Schlüssel erhalten
|
||||
|
||||
<Steps>
|
||||
<Step title="Bei Sim anmelden">
|
||||
Navigieren Sie zu [Sim](https://sim.ai) und melden Sie sich in Ihrem Konto an.
|
||||
</Step>
|
||||
<Step title="Workflow öffnen">
|
||||
Navigieren Sie zu dem Workflow, den Sie programmatisch ausführen möchten.
|
||||
</Step>
|
||||
<Step title="Workflow bereitstellen">
|
||||
Klicken Sie auf "Bereitstellen", um Ihren Workflow bereitzustellen, falls dies noch nicht geschehen ist.
|
||||
</Step>
|
||||
<Step title="API-Schlüssel erstellen oder auswählen">
|
||||
Wählen oder erstellen Sie während des Bereitstellungsprozesses einen API-Schlüssel.
|
||||
</Step>
|
||||
<Step title="API-Schlüssel kopieren">
|
||||
Kopieren Sie den API-Schlüssel, um ihn in Ihrer Python-Anwendung zu verwenden.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Voraussetzungen
|
||||
|
||||
- Python 3.8+
|
||||
- requests >= 2.25.0
|
||||
|
||||
## Lizenz
|
||||
|
||||
Apache-2.0
|
||||
1052
apps/docs/content/docs/de/api-reference/typescript.mdx
Normal file
1052
apps/docs/content/docs/de/api-reference/typescript.mdx
Normal file
File diff suppressed because it is too large
Load Diff
24
apps/docs/content/docs/de/meta.json
Normal file
24
apps/docs/content/docs/de/meta.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"title": "Sim Documentation",
|
||||
"pages": [
|
||||
"./introduction/index",
|
||||
"./getting-started/index",
|
||||
"./quick-reference/index",
|
||||
"triggers",
|
||||
"blocks",
|
||||
"tools",
|
||||
"connections",
|
||||
"mcp",
|
||||
"copilot",
|
||||
"skills",
|
||||
"knowledgebase",
|
||||
"variables",
|
||||
"credentials",
|
||||
"execution",
|
||||
"permissions",
|
||||
"self-hosting",
|
||||
"./enterprise/index",
|
||||
"./keyboard-shortcuts/index"
|
||||
],
|
||||
"defaultOpen": false
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
{
|
||||
"pages": ["executeWorkflow", "cancelExecution", "listWorkflows", "getWorkflow", "getJobStatus"]
|
||||
}
|
||||
94
apps/docs/content/docs/en/api-reference/authentication.mdx
Normal file
94
apps/docs/content/docs/en/api-reference/authentication.mdx
Normal file
@@ -0,0 +1,94 @@
|
||||
---
|
||||
title: Authentication
|
||||
description: API key types, generation, and how to authenticate requests
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
|
||||
To access the Sim API, you need an API key. Sim supports two types of API keys — **personal keys** and **workspace keys** — each with different billing and access behaviors.
|
||||
|
||||
## Key Types
|
||||
|
||||
| | **Personal Keys** | **Workspace Keys** |
|
||||
| --- | --- | --- |
|
||||
| **Billed to** | Your individual account | Workspace owner |
|
||||
| **Scope** | Across workspaces you have access to | Shared across the workspace |
|
||||
| **Managed by** | Each user individually | Workspace admins |
|
||||
| **Permissions** | Must be enabled at workspace level | Require admin permissions |
|
||||
|
||||
<Callout type="info">
|
||||
Workspace admins can disable personal API key usage for their workspace. If disabled, only workspace keys can be used.
|
||||
</Callout>
|
||||
|
||||
## Generating API Keys
|
||||
|
||||
To generate a key, open the Sim dashboard and navigate to **Settings**, then go to **Sim Keys** and click **Create**.
|
||||
|
||||
<Callout type="warn">
|
||||
API keys are only shown once when generated. Store your key securely — you will not be able to view it again.
|
||||
</Callout>
|
||||
|
||||
## Using API Keys
|
||||
|
||||
Pass your API key in the `X-API-Key` header with every request:
|
||||
|
||||
<Tabs items={['curl', 'TypeScript', 'Python']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch(
|
||||
'https://www.sim.ai/api/workflows/{workflowId}/execute',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': process.env.SIM_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify({ inputs: {} }),
|
||||
}
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
```python
|
||||
import requests
|
||||
|
||||
response = requests.post(
|
||||
"https://www.sim.ai/api/workflows/{workflowId}/execute",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": os.environ["SIM_API_KEY"],
|
||||
},
|
||||
json={"inputs": {}},
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Where Keys Are Used
|
||||
|
||||
API keys authenticate access to:
|
||||
|
||||
- **Workflow execution** — run deployed workflows via the API
|
||||
- **Logs API** — query workflow execution logs and metrics
|
||||
- **MCP servers** — authenticate connections to deployed MCP servers
|
||||
- **SDKs** — the [Python](/api-reference/python) and [TypeScript](/api-reference/typescript) SDKs use API keys for all operations
|
||||
|
||||
## Security
|
||||
|
||||
- Keys use the `sk-sim-` prefix and are encrypted at rest
|
||||
- Keys can be revoked at any time from the dashboard
|
||||
- Use environment variables to store keys — never hardcode them in source code
|
||||
- For browser-based applications, use a backend proxy to avoid exposing keys to the client
|
||||
|
||||
<Callout type="warn">
|
||||
Never expose your API key in client-side code. Use a server-side proxy to make authenticated requests on behalf of your frontend.
|
||||
</Callout>
|
||||
210
apps/docs/content/docs/en/api-reference/getting-started.mdx
Normal file
210
apps/docs/content/docs/en/api-reference/getting-started.mdx
Normal file
@@ -0,0 +1,210 @@
|
||||
---
|
||||
title: Getting Started
|
||||
description: Base URL, first API call, response format, error handling, and pagination
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
|
||||
## Base URL
|
||||
|
||||
All API requests are made to:
|
||||
|
||||
```
|
||||
https://www.sim.ai
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step>
|
||||
### Get your API key
|
||||
|
||||
Go to the Sim platform and navigate to **Settings**, then go to **Sim Keys** and click **Create**. See [Authentication](/api-reference/authentication) for details on key types.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Find your workflow ID
|
||||
|
||||
Open a workflow in the Sim editor. The workflow ID is in the URL:
|
||||
|
||||
```
|
||||
https://www.sim.ai/workspace/{workspaceId}/w/{workflowId}
|
||||
```
|
||||
|
||||
You can also use the [List Workflows](/api-reference/workflows/listWorkflows) endpoint to get all workflow IDs in a workspace.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Deploy your workflow
|
||||
|
||||
A workflow must be deployed before it can be executed via the API. Click the **Deploy** button in the editor toolbar, or use the dashboard to manage deployments.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Make your first request
|
||||
|
||||
<Tabs items={['curl', 'TypeScript', 'Python']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch(
|
||||
`https://www.sim.ai/api/workflows/${workflowId}/execute`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': process.env.SIM_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify({ inputs: {} }),
|
||||
}
|
||||
)
|
||||
|
||||
const data = await response.json()
|
||||
console.log(data.output)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
```python
|
||||
import requests
|
||||
import os
|
||||
|
||||
response = requests.post(
|
||||
f"https://www.sim.ai/api/workflows/{workflow_id}/execute",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": os.environ["SIM_API_KEY"],
|
||||
},
|
||||
json={"inputs": {}},
|
||||
)
|
||||
|
||||
data = response.json()
|
||||
print(data["output"])
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## Sync vs Async Execution
|
||||
|
||||
By default, workflow executions are **synchronous** — the API blocks until the workflow completes and returns the result directly.
|
||||
|
||||
For long-running workflows, use **asynchronous execution** by passing `async: true`:
|
||||
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}, "async": true}'
|
||||
```
|
||||
|
||||
This returns immediately with a `taskId`:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"taskId": "job_abc123",
|
||||
"status": "queued"
|
||||
}
|
||||
```
|
||||
|
||||
Poll the [Get Job Status](/api-reference/workflows/getJobStatus) endpoint until the status is `completed` or `failed`:
|
||||
|
||||
```bash
|
||||
curl https://www.sim.ai/api/jobs/{taskId} \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
```
|
||||
|
||||
<Callout type="info">
|
||||
Job status transitions follow: `queued` → `processing` → `completed` or `failed`. The `output` field is only present when status is `completed`.
|
||||
</Callout>
|
||||
|
||||
## Response Format
|
||||
|
||||
Successful responses include an `output` object with your workflow results and a `limits` object with your current rate limit and usage status:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"output": {
|
||||
"result": "Hello, world!"
|
||||
},
|
||||
"limits": {
|
||||
"workflowExecutionRateLimit": {
|
||||
"sync": {
|
||||
"requestsPerMinute": 60,
|
||||
"maxBurst": 10,
|
||||
"remaining": 59,
|
||||
"resetAt": "2025-01-01T00:01:00Z"
|
||||
},
|
||||
"async": {
|
||||
"requestsPerMinute": 30,
|
||||
"maxBurst": 5,
|
||||
"remaining": 30,
|
||||
"resetAt": "2025-01-01T00:01:00Z"
|
||||
}
|
||||
},
|
||||
"usage": {
|
||||
"currentPeriodCost": 1.25,
|
||||
"limit": 50.00,
|
||||
"plan": "pro",
|
||||
"isExceeded": false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The API uses standard HTTP status codes. Error responses include a human-readable `error` message:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Workflow not found"
|
||||
}
|
||||
```
|
||||
|
||||
| Status | Meaning | What to do |
|
||||
| --- | --- | --- |
|
||||
| `400` | Invalid request parameters | Check the `details` array for specific field errors |
|
||||
| `401` | Missing or invalid API key | Verify your `X-API-Key` header |
|
||||
| `403` | Access denied | Check you have permission for this resource |
|
||||
| `404` | Resource not found | Verify the ID exists and belongs to your workspace |
|
||||
| `429` | Rate limit exceeded | Wait for the duration in the `Retry-After` header |
|
||||
|
||||
<Callout type="info">
|
||||
Use the [Get Usage Limits](/api-reference/usage/getUsageLimits) endpoint to check your current rate limit status and billing usage at any time.
|
||||
</Callout>
|
||||
|
||||
## Rate Limits
|
||||
|
||||
Rate limits depend on your subscription plan and apply separately to synchronous and asynchronous executions. Every execution response includes a `limits` object showing your current rate limit status.
|
||||
|
||||
When rate limited, the API returns a `429` response with a `Retry-After` header indicating how many seconds to wait before retrying.
|
||||
|
||||
## Pagination
|
||||
|
||||
List endpoints (workflows, logs, audit logs) use **cursor-based pagination**:
|
||||
|
||||
```bash
|
||||
# First page
|
||||
curl "https://www.sim.ai/api/v1/logs?limit=20" \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
|
||||
# Next page — use the nextCursor from the previous response
|
||||
curl "https://www.sim.ai/api/v1/logs?limit=20&cursor=abc123" \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
```
|
||||
|
||||
The response includes a `nextCursor` field. When `nextCursor` is absent or `null`, you have reached the last page.
|
||||
16
apps/docs/content/docs/en/api-reference/meta.json
Normal file
16
apps/docs/content/docs/en/api-reference/meta.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"title": "API Reference",
|
||||
"root": true,
|
||||
"pages": [
|
||||
"getting-started",
|
||||
"authentication",
|
||||
"---SDKs---",
|
||||
"python",
|
||||
"typescript",
|
||||
"---Endpoints---",
|
||||
"(generated)/workflows",
|
||||
"(generated)/logs",
|
||||
"(generated)/usage",
|
||||
"(generated)/audit-logs"
|
||||
]
|
||||
}
|
||||
761
apps/docs/content/docs/en/api-reference/python.mdx
Normal file
761
apps/docs/content/docs/en/api-reference/python.mdx
Normal file
@@ -0,0 +1,761 @@
|
||||
---
|
||||
title: Python
|
||||
---
|
||||
|
||||
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 allows you to execute workflows programmatically from your Python applications using the official Python SDK.
|
||||
|
||||
<Callout type="info">
|
||||
The Python SDK supports Python 3.8+ with async execution support, automatic rate limiting with exponential backoff, and usage tracking.
|
||||
</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://sim.ai" # optional, defaults to https://sim.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://sim.ai")
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `api_key` (str): Your Sim API key
|
||||
- `base_url` (str, optional): Base URL for the Sim 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)
|
||||
- `stream` (bool, optional): Enable streaming responses (default: False)
|
||||
- `selected_outputs` (list[str], optional): Block outputs to stream in `blockName.attribute` format (e.g., `["agent1.content"]`)
|
||||
- `async_execution` (bool, optional): Execute asynchronously (default: False)
|
||||
|
||||
**Returns:** `WorkflowExecutionResult | AsyncExecutionResult`
|
||||
|
||||
When `async_execution=True`, returns immediately with a task ID for polling. Otherwise, waits for completion.
|
||||
|
||||
##### 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`
|
||||
|
||||
##### get_job_status()
|
||||
|
||||
Get the status of an async job execution.
|
||||
|
||||
```python
|
||||
status = client.get_job_status("task-id-from-async-execution")
|
||||
print("Status:", status["status"]) # 'queued', 'processing', 'completed', 'failed'
|
||||
if status["status"] == "completed":
|
||||
print("Output:", status["output"])
|
||||
```
|
||||
|
||||
**Parameters:**
|
||||
- `task_id` (str): The task ID returned from async execution
|
||||
|
||||
**Returns:** `Dict[str, Any]`
|
||||
|
||||
**Response fields:**
|
||||
- `success` (bool): Whether the request was successful
|
||||
- `taskId` (str): The task ID
|
||||
- `status` (str): One of `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
|
||||
- `metadata` (dict): Contains `startedAt`, `completedAt`, and `duration`
|
||||
- `output` (any, optional): The workflow output (when completed)
|
||||
- `error` (any, optional): Error details (when failed)
|
||||
- `estimatedDuration` (int, optional): Estimated duration in milliseconds (when processing/queued)
|
||||
|
||||
##### execute_with_retry()
|
||||
|
||||
Execute a workflow with automatic retry on rate limit errors using exponential backoff.
|
||||
|
||||
```python
|
||||
result = client.execute_with_retry(
|
||||
"workflow-id",
|
||||
input_data={"message": "Hello"},
|
||||
timeout=30.0,
|
||||
max_retries=3, # Maximum number of retries
|
||||
initial_delay=1.0, # Initial delay in seconds
|
||||
max_delay=30.0, # Maximum delay in seconds
|
||||
backoff_multiplier=2.0 # Exponential backoff multiplier
|
||||
)
|
||||
```
|
||||
|
||||
**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
|
||||
- `stream` (bool, optional): Enable streaming responses
|
||||
- `selected_outputs` (list, optional): Block outputs to stream
|
||||
- `async_execution` (bool, optional): Execute asynchronously
|
||||
- `max_retries` (int, optional): Maximum number of retries (default: 3)
|
||||
- `initial_delay` (float, optional): Initial delay in seconds (default: 1.0)
|
||||
- `max_delay` (float, optional): Maximum delay in seconds (default: 30.0)
|
||||
- `backoff_multiplier` (float, optional): Backoff multiplier (default: 2.0)
|
||||
|
||||
**Returns:** `WorkflowExecutionResult | AsyncExecutionResult`
|
||||
|
||||
The retry logic uses exponential backoff (1s → 2s → 4s → 8s...) with ±25% jitter to prevent thundering herd. If the API provides a `retry-after` header, it will be used instead.
|
||||
|
||||
##### get_rate_limit_info()
|
||||
|
||||
Get the current rate limit information from the last API response.
|
||||
|
||||
```python
|
||||
rate_limit_info = client.get_rate_limit_info()
|
||||
if rate_limit_info:
|
||||
print("Limit:", rate_limit_info.limit)
|
||||
print("Remaining:", rate_limit_info.remaining)
|
||||
print("Reset:", datetime.fromtimestamp(rate_limit_info.reset))
|
||||
```
|
||||
|
||||
**Returns:** `RateLimitInfo | None`
|
||||
|
||||
##### get_usage_limits()
|
||||
|
||||
Get current usage limits and quota information for your account.
|
||||
|
||||
```python
|
||||
limits = client.get_usage_limits()
|
||||
print("Sync requests remaining:", limits.rate_limit["sync"]["remaining"])
|
||||
print("Async requests remaining:", limits.rate_limit["async"]["remaining"])
|
||||
print("Current period cost:", limits.usage["currentPeriodCost"])
|
||||
print("Plan:", limits.usage["plan"])
|
||||
```
|
||||
|
||||
**Returns:** `UsageLimits`
|
||||
|
||||
**Response structure:**
|
||||
```python
|
||||
{
|
||||
"success": bool,
|
||||
"rateLimit": {
|
||||
"sync": {
|
||||
"isLimited": bool,
|
||||
"limit": int,
|
||||
"remaining": int,
|
||||
"resetAt": str
|
||||
},
|
||||
"async": {
|
||||
"isLimited": bool,
|
||||
"limit": int,
|
||||
"remaining": int,
|
||||
"resetAt": str
|
||||
},
|
||||
"authType": str # 'api' or 'manual'
|
||||
},
|
||||
"usage": {
|
||||
"currentPeriodCost": float,
|
||||
"limit": float,
|
||||
"plan": str # e.g., 'free', 'pro'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### 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
|
||||
```
|
||||
|
||||
### AsyncExecutionResult
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class AsyncExecutionResult:
|
||||
success: bool
|
||||
task_id: str
|
||||
status: str # 'queued'
|
||||
created_at: str
|
||||
links: Dict[str, str] # e.g., {"status": "/api/jobs/{taskId}"}
|
||||
```
|
||||
|
||||
### WorkflowStatus
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class WorkflowStatus:
|
||||
is_deployed: bool
|
||||
deployed_at: Optional[str] = None
|
||||
needs_redeployment: bool = False
|
||||
```
|
||||
|
||||
### RateLimitInfo
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class RateLimitInfo:
|
||||
limit: int
|
||||
remaining: int
|
||||
reset: int
|
||||
retry_after: Optional[int] = None
|
||||
```
|
||||
|
||||
### UsageLimits
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class UsageLimits:
|
||||
success: bool
|
||||
rate_limit: Dict[str, Any]
|
||||
usage: Dict[str, Any]
|
||||
```
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
**Common error codes:**
|
||||
- `UNAUTHORIZED`: Invalid API key
|
||||
- `TIMEOUT`: Request timed out
|
||||
- `RATE_LIMIT_EXCEEDED`: Rate limit exceeded
|
||||
- `USAGE_LIMIT_EXCEEDED`: Usage limit exceeded
|
||||
- `EXECUTION_ERROR`: Workflow execution failed
|
||||
|
||||
## 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("SIM_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("SIM_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("SIM_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("SIM_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'}")
|
||||
```
|
||||
|
||||
### Async Workflow Execution
|
||||
|
||||
Execute workflows asynchronously for long-running tasks:
|
||||
|
||||
```python
|
||||
import os
|
||||
import time
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_async():
|
||||
try:
|
||||
# Start async execution
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"data": "large dataset"},
|
||||
async_execution=True # Execute asynchronously
|
||||
)
|
||||
|
||||
# Check if result is an async execution
|
||||
if hasattr(result, 'task_id'):
|
||||
print(f"Task ID: {result.task_id}")
|
||||
print(f"Status endpoint: {result.links['status']}")
|
||||
|
||||
# Poll for completion
|
||||
status = client.get_job_status(result.task_id)
|
||||
|
||||
while status["status"] in ["queued", "processing"]:
|
||||
print(f"Current status: {status['status']}")
|
||||
time.sleep(2) # Wait 2 seconds
|
||||
status = client.get_job_status(result.task_id)
|
||||
|
||||
if status["status"] == "completed":
|
||||
print("Workflow completed!")
|
||||
print(f"Output: {status['output']}")
|
||||
print(f"Duration: {status['metadata']['duration']}")
|
||||
else:
|
||||
print(f"Workflow failed: {status['error']}")
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error: {error}")
|
||||
|
||||
execute_async()
|
||||
```
|
||||
|
||||
### Rate Limiting and Retry
|
||||
|
||||
Handle rate limits automatically with exponential backoff:
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient, SimStudioError
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_with_retry_handling():
|
||||
try:
|
||||
# Automatically retries on rate limit
|
||||
result = client.execute_with_retry(
|
||||
"workflow-id",
|
||||
input_data={"message": "Process this"},
|
||||
max_retries=5,
|
||||
initial_delay=1.0,
|
||||
max_delay=60.0,
|
||||
backoff_multiplier=2.0
|
||||
)
|
||||
|
||||
print(f"Success: {result}")
|
||||
except SimStudioError as error:
|
||||
if error.code == "RATE_LIMIT_EXCEEDED":
|
||||
print("Rate limit exceeded after all retries")
|
||||
|
||||
# Check rate limit info
|
||||
rate_limit_info = client.get_rate_limit_info()
|
||||
if rate_limit_info:
|
||||
from datetime import datetime
|
||||
reset_time = datetime.fromtimestamp(rate_limit_info.reset)
|
||||
print(f"Rate limit resets at: {reset_time}")
|
||||
|
||||
execute_with_retry_handling()
|
||||
```
|
||||
|
||||
### Usage Monitoring
|
||||
|
||||
Monitor your account usage and limits:
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def check_usage():
|
||||
try:
|
||||
limits = client.get_usage_limits()
|
||||
|
||||
print("=== Rate Limits ===")
|
||||
print("Sync requests:")
|
||||
print(f" Limit: {limits.rate_limit['sync']['limit']}")
|
||||
print(f" Remaining: {limits.rate_limit['sync']['remaining']}")
|
||||
print(f" Resets at: {limits.rate_limit['sync']['resetAt']}")
|
||||
print(f" Is limited: {limits.rate_limit['sync']['isLimited']}")
|
||||
|
||||
print("\nAsync requests:")
|
||||
print(f" Limit: {limits.rate_limit['async']['limit']}")
|
||||
print(f" Remaining: {limits.rate_limit['async']['remaining']}")
|
||||
print(f" Resets at: {limits.rate_limit['async']['resetAt']}")
|
||||
print(f" Is limited: {limits.rate_limit['async']['isLimited']}")
|
||||
|
||||
print("\n=== Usage ===")
|
||||
print(f"Current period cost: ${limits.usage['currentPeriodCost']:.2f}")
|
||||
print(f"Limit: ${limits.usage['limit']:.2f}")
|
||||
print(f"Plan: {limits.usage['plan']}")
|
||||
|
||||
percent_used = (limits.usage['currentPeriodCost'] / limits.usage['limit']) * 100
|
||||
print(f"Usage: {percent_used:.1f}%")
|
||||
|
||||
if percent_used > 80:
|
||||
print("⚠️ Warning: You are approaching your usage limit!")
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error checking usage: {error}")
|
||||
|
||||
check_usage()
|
||||
```
|
||||
|
||||
### Streaming Workflow Execution
|
||||
|
||||
Execute workflows with real-time streaming responses:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_with_streaming():
|
||||
"""Execute workflow with streaming enabled."""
|
||||
try:
|
||||
# Enable streaming for specific block outputs
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"message": "Count to five"},
|
||||
stream=True,
|
||||
selected_outputs=["agent1.content"] # Use blockName.attribute format
|
||||
)
|
||||
|
||||
print("Workflow result:", result)
|
||||
except Exception as error:
|
||||
print("Error:", error)
|
||||
|
||||
execute_with_streaming()
|
||||
```
|
||||
|
||||
The streaming response follows the Server-Sent Events (SSE) format:
|
||||
|
||||
```
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
|
||||
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"}
|
||||
|
||||
data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
|
||||
|
||||
data: [DONE]
|
||||
```
|
||||
|
||||
**Flask Streaming Example:**
|
||||
|
||||
```python
|
||||
from flask import Flask, Response, stream_with_context
|
||||
import requests
|
||||
import json
|
||||
import os
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route('/stream-workflow')
|
||||
def stream_workflow():
|
||||
"""Stream workflow execution to the client."""
|
||||
|
||||
def generate():
|
||||
response = requests.post(
|
||||
'https://sim.ai/api/workflows/WORKFLOW_ID/execute',
|
||||
headers={
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': os.getenv('SIM_API_KEY')
|
||||
},
|
||||
json={
|
||||
'message': 'Generate a story',
|
||||
'stream': True,
|
||||
'selectedOutputs': ['agent1.content']
|
||||
},
|
||||
stream=True
|
||||
)
|
||||
|
||||
for line in response.iter_lines():
|
||||
if line:
|
||||
decoded_line = line.decode('utf-8')
|
||||
if decoded_line.startswith('data: '):
|
||||
data = decoded_line[6:] # Remove 'data: ' prefix
|
||||
|
||||
if data == '[DONE]':
|
||||
break
|
||||
|
||||
try:
|
||||
parsed = json.loads(data)
|
||||
if 'chunk' in parsed:
|
||||
yield f"data: {json.dumps(parsed)}\n\n"
|
||||
elif parsed.get('event') == 'done':
|
||||
yield f"data: {json.dumps(parsed)}\n\n"
|
||||
print("Execution complete:", parsed.get('metadata'))
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
return Response(
|
||||
stream_with_context(generate()),
|
||||
mimetype='text/event-stream'
|
||||
)
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
```
|
||||
|
||||
### 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("SIM_API_KEY")
|
||||
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Production">
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Production configuration with error handling
|
||||
api_key = os.getenv("SIM_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("SIM_API_KEY environment variable is required")
|
||||
|
||||
client = SimStudioClient(
|
||||
api_key=api_key,
|
||||
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Getting Your API Key
|
||||
|
||||
<Steps>
|
||||
<Step title="Log in to Sim">
|
||||
Navigate to [Sim](https://sim.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>
|
||||
|
||||
## Requirements
|
||||
|
||||
- Python 3.8+
|
||||
- requests >= 2.25.0
|
||||
|
||||
## License
|
||||
|
||||
Apache-2.0
|
||||
1035
apps/docs/content/docs/en/api-reference/typescript.mdx
Normal file
1035
apps/docs/content/docs/en/api-reference/typescript.mdx
Normal file
File diff suppressed because it is too large
Load Diff
@@ -17,7 +17,7 @@ curl -H "x-api-key: YOUR_API_KEY" \
|
||||
https://sim.ai/api/v1/logs?workspaceId=YOUR_WORKSPACE_ID
|
||||
```
|
||||
|
||||
You can generate API keys from your user settings in the Sim dashboard.
|
||||
You can generate API keys from the Sim platform and navigate to **Settings**, then go to **Sim Keys** and click **Create**.
|
||||
|
||||
## Logs API
|
||||
|
||||
|
||||
@@ -16,7 +16,6 @@
|
||||
"credentials",
|
||||
"execution",
|
||||
"permissions",
|
||||
"sdks",
|
||||
"self-hosting",
|
||||
"./enterprise/index",
|
||||
"./keyboard-shortcuts/index"
|
||||
|
||||
@@ -113,7 +113,7 @@ Users can create two types of environment variables:
|
||||
### Personal Environment Variables
|
||||
- Only visible to the individual user
|
||||
- Available in all workflows they run
|
||||
- Managed in user settings
|
||||
- Managed in **Settings**, then go to **Secrets**
|
||||
|
||||
### Workspace Environment Variables
|
||||
- **Read permission**: Can see variable names and values
|
||||
|
||||
@@ -26,12 +26,63 @@ In Sim, the Airtable integration enables your agents to interact with your Airta
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
Integrates Airtable into the workflow. Can create, get, list, or update Airtable records. Can be used in trigger mode to trigger a workflow when an update is made to an Airtable table.
|
||||
Integrates Airtable into the workflow. Can list bases, list tables (with schema), and create, get, list, or update records. Can also be used in trigger mode to trigger a workflow when an update is made to an Airtable table.
|
||||
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
### `airtable_list_bases`
|
||||
|
||||
List all Airtable bases the user has access to
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `offset` | string | No | Pagination offset for retrieving additional bases |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `bases` | array | List of Airtable bases |
|
||||
| ↳ `id` | string | Base ID \(starts with "app"\) |
|
||||
| ↳ `name` | string | Base name |
|
||||
| ↳ `permissionLevel` | string | Permission level \(none, read, comment, edit, create\) |
|
||||
| `metadata` | json | Pagination and count metadata |
|
||||
| ↳ `offset` | string | Offset for next page of results |
|
||||
| ↳ `totalBases` | number | Number of bases returned |
|
||||
|
||||
### `airtable_list_tables`
|
||||
|
||||
List all tables and their schema in an Airtable base
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `baseId` | string | Yes | Airtable base ID \(starts with "app", e.g., "appXXXXXXXXXXXXXX"\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `tables` | array | List of tables in the base with their schema |
|
||||
| ↳ `id` | string | Table ID \(starts with "tbl"\) |
|
||||
| ↳ `name` | string | Table name |
|
||||
| ↳ `description` | string | Table description |
|
||||
| ↳ `primaryFieldId` | string | ID of the primary field |
|
||||
| ↳ `fields` | array | List of fields in the table |
|
||||
| ↳ `id` | string | Field ID \(starts with "fld"\) |
|
||||
| ↳ `name` | string | Field name |
|
||||
| ↳ `type` | string | Field type \(singleLineText, multilineText, number, checkbox, singleSelect, multipleSelects, date, dateTime, attachment, linkedRecord, etc.\) |
|
||||
| ↳ `description` | string | Field description |
|
||||
| ↳ `options` | json | Field-specific options \(choices, etc.\) |
|
||||
| `metadata` | json | Base info and count metadata |
|
||||
| ↳ `baseId` | string | The base ID queried |
|
||||
| ↳ `totalTables` | number | Number of tables in the base |
|
||||
|
||||
### `airtable_list_records`
|
||||
|
||||
Read records from an Airtable table
|
||||
@@ -49,8 +100,13 @@ Read records from an Airtable table
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `records` | json | Array of retrieved Airtable records |
|
||||
| `records` | array | Array of retrieved Airtable records |
|
||||
| ↳ `id` | string | Record ID |
|
||||
| ↳ `createdTime` | string | Record creation timestamp |
|
||||
| ↳ `fields` | json | Record field values |
|
||||
| `metadata` | json | Operation metadata including pagination offset and total records count |
|
||||
| ↳ `offset` | string | Pagination offset for next page |
|
||||
| ↳ `totalRecords` | number | Number of records returned |
|
||||
|
||||
### `airtable_get_record`
|
||||
|
||||
@@ -68,8 +124,12 @@ Retrieve a single record from an Airtable table by its ID
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `record` | json | Retrieved Airtable record with id, createdTime, and fields |
|
||||
| `metadata` | json | Operation metadata including record count |
|
||||
| `record` | json | Retrieved Airtable record |
|
||||
| ↳ `id` | string | Record ID |
|
||||
| ↳ `createdTime` | string | Record creation timestamp |
|
||||
| ↳ `fields` | json | Record field values |
|
||||
| `metadata` | json | Operation metadata |
|
||||
| ↳ `recordCount` | number | Number of records returned \(always 1\) |
|
||||
|
||||
### `airtable_create_records`
|
||||
|
||||
@@ -88,8 +148,12 @@ Write new records to an Airtable table
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `records` | json | Array of created Airtable records |
|
||||
| `records` | array | Array of created Airtable records |
|
||||
| ↳ `id` | string | Record ID |
|
||||
| ↳ `createdTime` | string | Record creation timestamp |
|
||||
| ↳ `fields` | json | Record field values |
|
||||
| `metadata` | json | Operation metadata |
|
||||
| ↳ `recordCount` | number | Number of records created |
|
||||
|
||||
### `airtable_update_record`
|
||||
|
||||
@@ -108,8 +172,13 @@ Update an existing record in an Airtable table by ID
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `record` | json | Updated Airtable record with id, createdTime, and fields |
|
||||
| `metadata` | json | Operation metadata including record count and updated field names |
|
||||
| `record` | json | Updated Airtable record |
|
||||
| ↳ `id` | string | Record ID |
|
||||
| ↳ `createdTime` | string | Record creation timestamp |
|
||||
| ↳ `fields` | json | Record field values |
|
||||
| `metadata` | json | Operation metadata |
|
||||
| ↳ `recordCount` | number | Number of records updated \(always 1\) |
|
||||
| ↳ `updatedFields` | array | List of field names that were updated |
|
||||
|
||||
### `airtable_update_multiple_records`
|
||||
|
||||
@@ -127,7 +196,12 @@ Update multiple existing records in an Airtable table
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `records` | json | Array of updated Airtable records |
|
||||
| `metadata` | json | Operation metadata including record count and updated record IDs |
|
||||
| `records` | array | Array of updated Airtable records |
|
||||
| ↳ `id` | string | Record ID |
|
||||
| ↳ `createdTime` | string | Record creation timestamp |
|
||||
| ↳ `fields` | json | Record field values |
|
||||
| `metadata` | json | Operation metadata |
|
||||
| ↳ `recordCount` | number | Number of records updated |
|
||||
| ↳ `updatedRecordIds` | array | List of updated record IDs |
|
||||
|
||||
|
||||
|
||||
313
apps/docs/content/docs/en/tools/amplitude.mdx
Normal file
313
apps/docs/content/docs/en/tools/amplitude.mdx
Normal file
@@ -0,0 +1,313 @@
|
||||
---
|
||||
title: Amplitude
|
||||
description: Track events and query analytics from Amplitude
|
||||
---
|
||||
|
||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||
|
||||
<BlockInfoCard
|
||||
type="amplitude"
|
||||
color="#1B1F3B"
|
||||
/>
|
||||
|
||||
{/* MANUAL-CONTENT-START:intro */}
|
||||
[Amplitude](https://amplitude.com/) is a leading digital analytics platform that helps teams understand user behavior, measure product performance, and make data-driven decisions at scale.
|
||||
|
||||
The Amplitude integration in Sim connects with the Amplitude HTTP and Dashboard REST APIs using API key and secret key authentication, allowing your agents to track events, manage user properties, and query analytics data programmatically. This API-based approach ensures secure access to Amplitude's full suite of analytics capabilities.
|
||||
|
||||
With the Amplitude integration, your agents can:
|
||||
|
||||
- **Track events**: Send custom events to Amplitude with rich properties, revenue data, and user context directly from your workflows
|
||||
- **Identify users**: Set and update user properties using operations like $set, $setOnce, $add, $append, and $unset to maintain detailed user profiles
|
||||
- **Search for users**: Look up users by User ID, Device ID, or Amplitude ID to retrieve profile information and metadata
|
||||
- **Query event analytics**: Run event segmentation queries with grouping, custom metrics (uniques, totals, averages, DAU percentages), and flexible date ranges
|
||||
- **Monitor user activity**: Retrieve event streams for specific users to understand individual user journeys and behavior patterns
|
||||
- **Analyze active users**: Get active or new user counts over time with daily, weekly, or monthly granularity
|
||||
- **Track revenue**: Access revenue LTV metrics including ARPU, ARPPU, total revenue, and paying user counts
|
||||
|
||||
In Sim, the Amplitude integration enables powerful analytics automation scenarios. Your agents can track product events in real time based on workflow triggers, enrich user profiles as new data becomes available, query segmentation data to inform downstream decisions, or build monitoring workflows that alert on changes in key metrics. By connecting Sim with Amplitude, you can build intelligent agents that bridge the gap between analytics insights and automated action, enabling data-driven workflows that respond to user behavior patterns and product performance trends.
|
||||
{/* MANUAL-CONTENT-END */}
|
||||
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
Integrate Amplitude into your workflow to track events, identify users and groups, search for users, query analytics, and retrieve revenue data.
|
||||
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
### `amplitude_send_event`
|
||||
|
||||
Track an event in Amplitude using the HTTP V2 API.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Amplitude API Key |
|
||||
| `userId` | string | No | User ID \(required if no device_id\) |
|
||||
| `deviceId` | string | No | Device ID \(required if no user_id\) |
|
||||
| `eventType` | string | Yes | Name of the event \(e.g., "page_view", "purchase"\) |
|
||||
| `eventProperties` | string | No | JSON object of custom event properties |
|
||||
| `userProperties` | string | No | JSON object of user properties to set \(supports $set, $setOnce, $add, $append, $unset\) |
|
||||
| `time` | string | No | Event timestamp in milliseconds since epoch |
|
||||
| `sessionId` | string | No | Session start time in milliseconds since epoch |
|
||||
| `insertId` | string | No | Unique ID for deduplication \(within 7-day window\) |
|
||||
| `appVersion` | string | No | Application version string |
|
||||
| `platform` | string | No | Platform \(e.g., "Web", "iOS", "Android"\) |
|
||||
| `country` | string | No | Two-letter country code |
|
||||
| `language` | string | No | Language code \(e.g., "en"\) |
|
||||
| `ip` | string | No | IP address for geo-location |
|
||||
| `price` | string | No | Price of the item purchased |
|
||||
| `quantity` | string | No | Quantity of items purchased |
|
||||
| `revenue` | string | No | Revenue amount |
|
||||
| `productId` | string | No | Product identifier |
|
||||
| `revenueType` | string | No | Revenue type \(e.g., "purchase", "refund"\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `code` | number | Response code \(200 for success\) |
|
||||
| `eventsIngested` | number | Number of events ingested |
|
||||
| `payloadSizeBytes` | number | Size of the payload in bytes |
|
||||
| `serverUploadTime` | number | Server upload timestamp |
|
||||
|
||||
### `amplitude_identify_user`
|
||||
|
||||
Set user properties in Amplitude using the Identify API. Supports $set, $setOnce, $add, $append, $unset operations.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Amplitude API Key |
|
||||
| `userId` | string | No | User ID \(required if no device_id\) |
|
||||
| `deviceId` | string | No | Device ID \(required if no user_id\) |
|
||||
| `userProperties` | string | Yes | JSON object of user properties. Use operations like $set, $setOnce, $add, $append, $unset. |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `code` | number | HTTP response status code |
|
||||
| `message` | string | Response message |
|
||||
|
||||
### `amplitude_group_identify`
|
||||
|
||||
Set group-level properties in Amplitude. Supports $set, $setOnce, $add, $append, $unset operations.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Amplitude API Key |
|
||||
| `groupType` | string | Yes | Group classification \(e.g., "company", "org_id"\) |
|
||||
| `groupValue` | string | Yes | Specific group identifier \(e.g., "Acme Corp"\) |
|
||||
| `groupProperties` | string | Yes | JSON object of group properties. Use operations like $set, $setOnce, $add, $append, $unset. |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `code` | number | HTTP response status code |
|
||||
| `message` | string | Response message |
|
||||
|
||||
### `amplitude_user_search`
|
||||
|
||||
Search for a user by User ID, Device ID, or Amplitude ID using the Dashboard REST API.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Amplitude API Key |
|
||||
| `secretKey` | string | Yes | Amplitude Secret Key |
|
||||
| `user` | string | Yes | User ID, Device ID, or Amplitude ID to search for |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `matches` | array | List of matching users |
|
||||
| ↳ `amplitudeId` | number | Amplitude internal user ID |
|
||||
| ↳ `userId` | string | External user ID |
|
||||
| `type` | string | Match type \(e.g., match_user_or_device_id\) |
|
||||
|
||||
### `amplitude_user_activity`
|
||||
|
||||
Get the event stream for a specific user by their Amplitude ID.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Amplitude API Key |
|
||||
| `secretKey` | string | Yes | Amplitude Secret Key |
|
||||
| `amplitudeId` | string | Yes | Amplitude internal user ID |
|
||||
| `offset` | string | No | Offset for pagination \(default 0\) |
|
||||
| `limit` | string | No | Maximum number of events to return \(default 1000, max 1000\) |
|
||||
| `direction` | string | No | Sort direction: "latest" or "earliest" \(default: latest\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `events` | array | List of user events |
|
||||
| ↳ `eventType` | string | Type of event |
|
||||
| ↳ `eventTime` | string | Event timestamp |
|
||||
| ↳ `eventProperties` | json | Custom event properties |
|
||||
| ↳ `userProperties` | json | User properties at event time |
|
||||
| ↳ `sessionId` | number | Session ID |
|
||||
| ↳ `platform` | string | Platform |
|
||||
| ↳ `country` | string | Country |
|
||||
| ↳ `city` | string | City |
|
||||
| `userData` | json | User metadata |
|
||||
| ↳ `userId` | string | External user ID |
|
||||
| ↳ `canonicalAmplitudeId` | number | Canonical Amplitude ID |
|
||||
| ↳ `numEvents` | number | Total event count |
|
||||
| ↳ `numSessions` | number | Total session count |
|
||||
| ↳ `platform` | string | Primary platform |
|
||||
| ↳ `country` | string | Country |
|
||||
|
||||
### `amplitude_user_profile`
|
||||
|
||||
Get a user profile including properties, cohort memberships, and computed properties.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `secretKey` | string | Yes | Amplitude Secret Key |
|
||||
| `userId` | string | No | External user ID \(required if no device_id\) |
|
||||
| `deviceId` | string | No | Device ID \(required if no user_id\) |
|
||||
| `getAmpProps` | string | No | Include Amplitude user properties \(true/false, default: false\) |
|
||||
| `getCohortIds` | string | No | Include cohort IDs the user belongs to \(true/false, default: false\) |
|
||||
| `getComputations` | string | No | Include computed user properties \(true/false, default: false\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `userId` | string | External user ID |
|
||||
| `deviceId` | string | Device ID |
|
||||
| `ampProps` | json | Amplitude user properties \(library, first_used, last_used, custom properties\) |
|
||||
| `cohortIds` | array | List of cohort IDs the user belongs to |
|
||||
| `computations` | json | Computed user properties |
|
||||
|
||||
### `amplitude_event_segmentation`
|
||||
|
||||
Query event analytics data with segmentation. Get event counts, uniques, averages, and more.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Amplitude API Key |
|
||||
| `secretKey` | string | Yes | Amplitude Secret Key |
|
||||
| `eventType` | string | Yes | Event type name to analyze |
|
||||
| `start` | string | Yes | Start date in YYYYMMDD format |
|
||||
| `end` | string | Yes | End date in YYYYMMDD format |
|
||||
| `metric` | string | No | Metric type: uniques, totals, pct_dau, average, histogram, sums, value_avg, or formula \(default: uniques\) |
|
||||
| `interval` | string | No | Time interval: 1 \(daily\), 7 \(weekly\), or 30 \(monthly\) |
|
||||
| `groupBy` | string | No | Property name to group by \(prefix custom user properties with "gp:"\) |
|
||||
| `limit` | string | No | Maximum number of group-by values \(max 1000\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `series` | json | Time-series data arrays indexed by series |
|
||||
| `seriesLabels` | array | Labels for each data series |
|
||||
| `seriesCollapsed` | json | Collapsed aggregate totals per series |
|
||||
| `xValues` | array | Date values for the x-axis |
|
||||
|
||||
### `amplitude_get_active_users`
|
||||
|
||||
Get active or new user counts over a date range from the Dashboard REST API.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Amplitude API Key |
|
||||
| `secretKey` | string | Yes | Amplitude Secret Key |
|
||||
| `start` | string | Yes | Start date in YYYYMMDD format |
|
||||
| `end` | string | Yes | End date in YYYYMMDD format |
|
||||
| `metric` | string | No | Metric type: "active" or "new" \(default: active\) |
|
||||
| `interval` | string | No | Time interval: 1 \(daily\), 7 \(weekly\), or 30 \(monthly\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `series` | json | Array of data series with user counts per time interval |
|
||||
| `seriesMeta` | array | Metadata labels for each data series \(e.g., segment names\) |
|
||||
| `xValues` | array | Date values for the x-axis |
|
||||
|
||||
### `amplitude_realtime_active_users`
|
||||
|
||||
Get real-time active user counts at 5-minute granularity for the last 2 days.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Amplitude API Key |
|
||||
| `secretKey` | string | Yes | Amplitude Secret Key |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `series` | json | Array of data series with active user counts at 5-minute intervals |
|
||||
| `seriesLabels` | array | Labels for each series \(e.g., "Today", "Yesterday"\) |
|
||||
| `xValues` | array | Time values for the x-axis \(e.g., "15:00", "15:05"\) |
|
||||
|
||||
### `amplitude_list_events`
|
||||
|
||||
List all event types in the Amplitude project with their weekly totals and unique counts.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Amplitude API Key |
|
||||
| `secretKey` | string | Yes | Amplitude Secret Key |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `events` | array | List of event types in the project |
|
||||
| ↳ `value` | string | Event type name |
|
||||
| ↳ `displayName` | string | Event display name |
|
||||
| ↳ `totals` | number | Weekly total count |
|
||||
| ↳ `hidden` | boolean | Whether the event is hidden |
|
||||
| ↳ `deleted` | boolean | Whether the event is deleted |
|
||||
|
||||
### `amplitude_get_revenue`
|
||||
|
||||
Get revenue LTV data including ARPU, ARPPU, total revenue, and paying user counts.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Amplitude API Key |
|
||||
| `secretKey` | string | Yes | Amplitude Secret Key |
|
||||
| `start` | string | Yes | Start date in YYYYMMDD format |
|
||||
| `end` | string | Yes | End date in YYYYMMDD format |
|
||||
| `metric` | string | No | Metric: 0 \(ARPU\), 1 \(ARPPU\), 2 \(Total Revenue\), 3 \(Paying Users\) |
|
||||
| `interval` | string | No | Time interval: 1 \(daily\), 7 \(weekly\), or 30 \(monthly\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `series` | json | Array of revenue data series |
|
||||
| `seriesLabels` | array | Labels for each data series |
|
||||
| `xValues` | array | Date values for the x-axis |
|
||||
|
||||
|
||||
83
apps/docs/content/docs/en/tools/brandfetch.mdx
Normal file
83
apps/docs/content/docs/en/tools/brandfetch.mdx
Normal file
@@ -0,0 +1,83 @@
|
||||
---
|
||||
title: Brandfetch
|
||||
description: Look up brand assets, logos, colors, and company info
|
||||
---
|
||||
|
||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||
|
||||
<BlockInfoCard
|
||||
type="brandfetch"
|
||||
color="#000000"
|
||||
/>
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
Integrate Brandfetch into your workflow. Retrieve brand logos, colors, fonts, and company data by domain, ticker, or name search.
|
||||
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
### `brandfetch_get_brand`
|
||||
|
||||
Retrieve brand assets including logos, colors, fonts, and company info by domain, ticker, ISIN, or crypto symbol
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Brandfetch API key |
|
||||
| `identifier` | string | Yes | Brand identifier: domain \(nike.com\), stock ticker \(NKE\), ISIN \(US6541061031\), or crypto symbol \(BTC\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `id` | string | Unique brand identifier |
|
||||
| `name` | string | Brand name |
|
||||
| `domain` | string | Brand domain |
|
||||
| `claimed` | boolean | Whether the brand profile is claimed |
|
||||
| `description` | string | Short brand description |
|
||||
| `longDescription` | string | Detailed brand description |
|
||||
| `links` | array | Social media and website links |
|
||||
| ↳ `name` | string | Link name \(e.g., twitter, linkedin\) |
|
||||
| ↳ `url` | string | Link URL |
|
||||
| `logos` | array | Brand logos with formats and themes |
|
||||
| ↳ `type` | string | Logo type \(logo, icon, symbol, other\) |
|
||||
| ↳ `theme` | string | Logo theme \(light, dark\) |
|
||||
| ↳ `formats` | array | Available formats with src URL, format, width, and height |
|
||||
| `colors` | array | Brand colors with hex values and types |
|
||||
| ↳ `hex` | string | Hex color code |
|
||||
| ↳ `type` | string | Color type \(accent, dark, light, brand\) |
|
||||
| ↳ `brightness` | number | Brightness value |
|
||||
| `fonts` | array | Brand fonts with names and types |
|
||||
| ↳ `name` | string | Font name |
|
||||
| ↳ `type` | string | Font type \(title, body\) |
|
||||
| ↳ `origin` | string | Font origin \(google, custom, system\) |
|
||||
| `company` | json | Company firmographic data including employees, location, and industries |
|
||||
| `qualityScore` | number | Data quality score from 0 to 1 |
|
||||
| `isNsfw` | boolean | Whether the brand contains adult content |
|
||||
|
||||
### `brandfetch_search`
|
||||
|
||||
Search for brands by name and find their domains and logos
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Brandfetch API key |
|
||||
| `name` | string | Yes | Company or brand name to search for |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `results` | array | List of matching brands |
|
||||
| ↳ `brandId` | string | Unique brand identifier |
|
||||
| ↳ `name` | string | Brand name |
|
||||
| ↳ `domain` | string | Brand domain |
|
||||
| ↳ `claimed` | boolean | Whether the brand profile is claimed |
|
||||
| ↳ `icon` | string | Brand icon URL |
|
||||
|
||||
|
||||
318
apps/docs/content/docs/en/tools/dub.mdx
Normal file
318
apps/docs/content/docs/en/tools/dub.mdx
Normal file
@@ -0,0 +1,318 @@
|
||||
---
|
||||
title: Dub
|
||||
description: Link management with Dub
|
||||
---
|
||||
|
||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||
|
||||
<BlockInfoCard
|
||||
type="dub"
|
||||
color="#181C1E"
|
||||
/>
|
||||
|
||||
{/* MANUAL-CONTENT-START:intro */}
|
||||
[Dub](https://dub.co/) is an open-source link management platform for modern marketing teams. It provides powerful short link creation, analytics, and tracking capabilities with enterprise-grade infrastructure.
|
||||
|
||||
With the Dub integration in Sim, you can:
|
||||
|
||||
- **Create short links**: Generate branded short links with custom domains, slugs, and UTM parameters
|
||||
- **Upsert links**: Create or update links idempotently by destination URL
|
||||
- **Retrieve link info**: Look up link details by ID, external ID, or domain + key combination
|
||||
- **Update links**: Modify destination URLs, metadata, UTM parameters, and link settings
|
||||
- **Delete links**: Remove short links by ID or external ID
|
||||
- **List links**: Search and filter links with pagination, sorting, and tag filtering
|
||||
- **Get analytics**: Retrieve click, lead, and sales analytics with grouping by time, geography, device, browser, referer, and more
|
||||
|
||||
In Sim, the Dub integration enables your agents to manage short links and track their performance programmatically. Use it to create trackable links as part of marketing workflows, monitor link engagement, and make data-driven decisions based on click analytics and conversion metrics.
|
||||
{/* MANUAL-CONTENT-END */}
|
||||
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
Create, manage, and track short links with Dub. Supports custom domains, UTM parameters, link analytics, and more.
|
||||
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
### `dub_create_link`
|
||||
|
||||
Create a new short link with Dub. Supports custom domains, slugs, UTM parameters, and more.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Dub API key |
|
||||
| `url` | string | Yes | The destination URL of the short link |
|
||||
| `domain` | string | No | Custom domain for the short link \(defaults to dub.sh\) |
|
||||
| `key` | string | No | Custom slug for the short link \(randomly generated if not provided\) |
|
||||
| `externalId` | string | No | External ID for the link in your database |
|
||||
| `tagIds` | string | No | Comma-separated tag IDs to assign to the link |
|
||||
| `comments` | string | No | Comments for the short link |
|
||||
| `expiresAt` | string | No | Expiration date in ISO 8601 format |
|
||||
| `password` | string | No | Password to protect the short link |
|
||||
| `rewrite` | boolean | No | Whether to enable link cloaking |
|
||||
| `archived` | boolean | No | Whether to archive the link |
|
||||
| `title` | string | No | Custom OG title for the link preview |
|
||||
| `description` | string | No | Custom OG description for the link preview |
|
||||
| `utm_source` | string | No | UTM source parameter |
|
||||
| `utm_medium` | string | No | UTM medium parameter |
|
||||
| `utm_campaign` | string | No | UTM campaign parameter |
|
||||
| `utm_term` | string | No | UTM term parameter |
|
||||
| `utm_content` | string | No | UTM content parameter |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `id` | string | Unique ID of the created link |
|
||||
| `domain` | string | Domain of the short link |
|
||||
| `key` | string | Slug of the short link |
|
||||
| `url` | string | Destination URL |
|
||||
| `shortLink` | string | Full short link URL |
|
||||
| `qrCode` | string | QR code URL for the short link |
|
||||
| `archived` | boolean | Whether the link is archived |
|
||||
| `externalId` | string | External ID |
|
||||
| `title` | string | OG title |
|
||||
| `description` | string | OG description |
|
||||
| `tags` | json | Tags assigned to the link \(id, name, color\) |
|
||||
| `clicks` | number | Number of clicks |
|
||||
| `leads` | number | Number of leads |
|
||||
| `sales` | number | Number of sales |
|
||||
| `saleAmount` | number | Total sale amount in cents |
|
||||
| `lastClicked` | string | Last clicked timestamp |
|
||||
| `createdAt` | string | Creation timestamp |
|
||||
| `updatedAt` | string | Last update timestamp |
|
||||
| `utm_source` | string | UTM source parameter |
|
||||
| `utm_medium` | string | UTM medium parameter |
|
||||
| `utm_campaign` | string | UTM campaign parameter |
|
||||
| `utm_term` | string | UTM term parameter |
|
||||
| `utm_content` | string | UTM content parameter |
|
||||
|
||||
### `dub_upsert_link`
|
||||
|
||||
Create or update a short link by its URL. If a link with the same URL already exists, update it. Otherwise, create a new link.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Dub API key |
|
||||
| `url` | string | Yes | The destination URL of the short link |
|
||||
| `domain` | string | No | Custom domain for the short link \(defaults to dub.sh\) |
|
||||
| `key` | string | No | Custom slug for the short link \(randomly generated if not provided\) |
|
||||
| `externalId` | string | No | External ID for the link in your database |
|
||||
| `tagIds` | string | No | Comma-separated tag IDs to assign to the link |
|
||||
| `comments` | string | No | Comments for the short link |
|
||||
| `expiresAt` | string | No | Expiration date in ISO 8601 format |
|
||||
| `password` | string | No | Password to protect the short link |
|
||||
| `rewrite` | boolean | No | Whether to enable link cloaking |
|
||||
| `archived` | boolean | No | Whether to archive the link |
|
||||
| `title` | string | No | Custom OG title for the link preview |
|
||||
| `description` | string | No | Custom OG description for the link preview |
|
||||
| `utm_source` | string | No | UTM source parameter |
|
||||
| `utm_medium` | string | No | UTM medium parameter |
|
||||
| `utm_campaign` | string | No | UTM campaign parameter |
|
||||
| `utm_term` | string | No | UTM term parameter |
|
||||
| `utm_content` | string | No | UTM content parameter |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `id` | string | Unique ID of the link |
|
||||
| `domain` | string | Domain of the short link |
|
||||
| `key` | string | Slug of the short link |
|
||||
| `url` | string | Destination URL |
|
||||
| `shortLink` | string | Full short link URL |
|
||||
| `qrCode` | string | QR code URL for the short link |
|
||||
| `archived` | boolean | Whether the link is archived |
|
||||
| `externalId` | string | External ID |
|
||||
| `title` | string | OG title |
|
||||
| `description` | string | OG description |
|
||||
| `tags` | json | Tags assigned to the link \(id, name, color\) |
|
||||
| `clicks` | number | Number of clicks |
|
||||
| `leads` | number | Number of leads |
|
||||
| `sales` | number | Number of sales |
|
||||
| `saleAmount` | number | Total sale amount in cents |
|
||||
| `lastClicked` | string | Last clicked timestamp |
|
||||
| `createdAt` | string | Creation timestamp |
|
||||
| `updatedAt` | string | Last update timestamp |
|
||||
| `utm_source` | string | UTM source parameter |
|
||||
| `utm_medium` | string | UTM medium parameter |
|
||||
| `utm_campaign` | string | UTM campaign parameter |
|
||||
| `utm_term` | string | UTM term parameter |
|
||||
| `utm_content` | string | UTM content parameter |
|
||||
|
||||
### `dub_get_link`
|
||||
|
||||
Retrieve information about a short link by its link ID, external ID, or domain + key combination.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Dub API key |
|
||||
| `linkId` | string | No | The unique ID of the short link |
|
||||
| `externalId` | string | No | The external ID of the link in your database |
|
||||
| `domain` | string | No | The domain of the link \(use with key\) |
|
||||
| `key` | string | No | The slug of the link \(use with domain\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `id` | string | Unique ID of the link |
|
||||
| `domain` | string | Domain of the short link |
|
||||
| `key` | string | Slug of the short link |
|
||||
| `url` | string | Destination URL |
|
||||
| `shortLink` | string | Full short link URL |
|
||||
| `qrCode` | string | QR code URL for the short link |
|
||||
| `archived` | boolean | Whether the link is archived |
|
||||
| `externalId` | string | External ID |
|
||||
| `title` | string | OG title |
|
||||
| `description` | string | OG description |
|
||||
| `tags` | json | Tags assigned to the link \(id, name, color\) |
|
||||
| `clicks` | number | Number of clicks |
|
||||
| `leads` | number | Number of leads |
|
||||
| `sales` | number | Number of sales |
|
||||
| `saleAmount` | number | Total sale amount in cents |
|
||||
| `lastClicked` | string | Last clicked timestamp |
|
||||
| `createdAt` | string | Creation timestamp |
|
||||
| `updatedAt` | string | Last update timestamp |
|
||||
| `utm_source` | string | UTM source parameter |
|
||||
| `utm_medium` | string | UTM medium parameter |
|
||||
| `utm_campaign` | string | UTM campaign parameter |
|
||||
| `utm_term` | string | UTM term parameter |
|
||||
| `utm_content` | string | UTM content parameter |
|
||||
|
||||
### `dub_update_link`
|
||||
|
||||
Update an existing short link. You can modify the destination URL, slug, metadata, UTM parameters, and more.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Dub API key |
|
||||
| `linkId` | string | Yes | The link ID or external ID prefixed with ext_ |
|
||||
| `url` | string | No | New destination URL |
|
||||
| `domain` | string | No | New custom domain |
|
||||
| `key` | string | No | New custom slug |
|
||||
| `title` | string | No | Custom OG title |
|
||||
| `description` | string | No | Custom OG description |
|
||||
| `externalId` | string | No | External ID for the link |
|
||||
| `tagIds` | string | No | Comma-separated tag IDs |
|
||||
| `comments` | string | No | Comments for the short link |
|
||||
| `expiresAt` | string | No | Expiration date in ISO 8601 format |
|
||||
| `password` | string | No | Password to protect the link |
|
||||
| `rewrite` | boolean | No | Whether to enable link cloaking |
|
||||
| `archived` | boolean | No | Whether to archive the link |
|
||||
| `utm_source` | string | No | UTM source parameter |
|
||||
| `utm_medium` | string | No | UTM medium parameter |
|
||||
| `utm_campaign` | string | No | UTM campaign parameter |
|
||||
| `utm_term` | string | No | UTM term parameter |
|
||||
| `utm_content` | string | No | UTM content parameter |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `id` | string | Unique ID of the updated link |
|
||||
| `domain` | string | Domain of the short link |
|
||||
| `key` | string | Slug of the short link |
|
||||
| `url` | string | Destination URL |
|
||||
| `shortLink` | string | Full short link URL |
|
||||
| `qrCode` | string | QR code URL for the short link |
|
||||
| `archived` | boolean | Whether the link is archived |
|
||||
| `externalId` | string | External ID |
|
||||
| `title` | string | OG title |
|
||||
| `description` | string | OG description |
|
||||
| `tags` | json | Tags assigned to the link \(id, name, color\) |
|
||||
| `clicks` | number | Number of clicks |
|
||||
| `leads` | number | Number of leads |
|
||||
| `sales` | number | Number of sales |
|
||||
| `saleAmount` | number | Total sale amount in cents |
|
||||
| `lastClicked` | string | Last clicked timestamp |
|
||||
| `createdAt` | string | Creation timestamp |
|
||||
| `updatedAt` | string | Last update timestamp |
|
||||
| `utm_source` | string | UTM source parameter |
|
||||
| `utm_medium` | string | UTM medium parameter |
|
||||
| `utm_campaign` | string | UTM campaign parameter |
|
||||
| `utm_term` | string | UTM term parameter |
|
||||
| `utm_content` | string | UTM content parameter |
|
||||
|
||||
### `dub_delete_link`
|
||||
|
||||
Delete a short link by its link ID or external ID (prefixed with ext_).
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Dub API key |
|
||||
| `linkId` | string | Yes | The link ID or external ID prefixed with ext_ |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `id` | string | ID of the deleted link |
|
||||
|
||||
### `dub_list_links`
|
||||
|
||||
Retrieve a paginated list of short links for the authenticated workspace. Supports filtering by domain, search query, tags, and sorting.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Dub API key |
|
||||
| `domain` | string | No | Filter by domain |
|
||||
| `search` | string | No | Search query matched against the short link slug and destination URL |
|
||||
| `tagIds` | string | No | Comma-separated tag IDs to filter by |
|
||||
| `showArchived` | boolean | No | Whether to include archived links \(defaults to false\) |
|
||||
| `sortBy` | string | No | Sort by field: createdAt, clicks, saleAmount, or lastClicked |
|
||||
| `sortOrder` | string | No | Sort order: asc or desc |
|
||||
| `page` | number | No | Page number \(default: 1\) |
|
||||
| `pageSize` | number | No | Number of links per page \(default: 100, max: 100\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `links` | json | Array of link objects \(id, domain, key, url, shortLink, clicks, tags, createdAt\) |
|
||||
| `count` | number | Number of links returned |
|
||||
|
||||
### `dub_get_analytics`
|
||||
|
||||
Retrieve analytics for links including clicks, leads, and sales. Supports filtering by link, time range, and grouping by various dimensions.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Dub API key |
|
||||
| `event` | string | No | Event type: clicks \(default\), leads, sales, or composite |
|
||||
| `groupBy` | string | No | Group results by: count \(default\), timeseries, countries, cities, devices, browsers, os, referers, top_links, top_urls |
|
||||
| `linkId` | string | No | Filter by link ID |
|
||||
| `externalId` | string | No | Filter by external ID \(prefix with ext_\) |
|
||||
| `domain` | string | No | Filter by domain |
|
||||
| `interval` | string | No | Time interval: 24h \(default\), 7d, 30d, 90d, 1y, mtd, qtd, ytd, or all |
|
||||
| `start` | string | No | Start date/time in ISO 8601 format \(overrides interval\) |
|
||||
| `end` | string | No | End date/time in ISO 8601 format \(defaults to now\) |
|
||||
| `country` | string | No | Filter by country \(ISO 3166-1 alpha-2 code\) |
|
||||
| `timezone` | string | No | IANA timezone for timeseries data \(defaults to UTC\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `clicks` | number | Total number of clicks |
|
||||
| `leads` | number | Total number of leads |
|
||||
| `sales` | number | Total number of sales |
|
||||
| `saleAmount` | number | Total sale amount in cents |
|
||||
| `data` | json | Grouped analytics data \(timeseries, countries, devices, etc.\) |
|
||||
|
||||
|
||||
156
apps/docs/content/docs/en/tools/google_meet.mdx
Normal file
156
apps/docs/content/docs/en/tools/google_meet.mdx
Normal file
@@ -0,0 +1,156 @@
|
||||
---
|
||||
title: Google Meet
|
||||
description: Create and manage Google Meet meetings
|
||||
---
|
||||
|
||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||
|
||||
<BlockInfoCard
|
||||
type="google_meet"
|
||||
color="#E0E0E0"
|
||||
/>
|
||||
|
||||
{/* MANUAL-CONTENT-START:intro */}
|
||||
[Google Meet](https://meet.google.com) is Google's video conferencing and online meeting platform, providing secure, high-quality video calls for individuals and teams. As a core component of Google Workspace, Google Meet enables real-time collaboration through video meetings, screen sharing, and integrated chat.
|
||||
|
||||
The Google Meet REST API (v2) allows programmatic management of meeting spaces and conference records, enabling automated workflows to create meetings, track participation, and manage active conferences without manual intervention.
|
||||
|
||||
Key features of the Google Meet API include:
|
||||
|
||||
- **Meeting Space Management**: Create, retrieve, and configure meeting spaces with customizable access controls.
|
||||
- **Conference Records**: Access historical conference data including start/end times and associated spaces.
|
||||
- **Participant Tracking**: View participant details for any conference including join/leave times and user types.
|
||||
- **Access Controls**: Configure who can join meetings (open, trusted, or restricted) and which entry points are allowed.
|
||||
- **Active Conference Management**: Programmatically end active conferences in meeting spaces.
|
||||
|
||||
In Sim, the Google Meet integration allows your agents to create meeting spaces on demand, monitor conference activity, track participation across meetings, and manage active conferences as part of automated workflows. This enables scenarios such as automatically provisioning meeting rooms for scheduled events, generating attendance reports, ending stale conferences, and building meeting analytics dashboards.
|
||||
{/* MANUAL-CONTENT-END */}
|
||||
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
Integrate Google Meet into your workflow. Create meeting spaces, get space details, end conferences, list conference records, and view participants.
|
||||
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
### `google_meet_create_space`
|
||||
|
||||
Create a new Google Meet meeting space
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `accessType` | string | No | Who can join the meeting without knocking: OPEN \(anyone with link\), TRUSTED \(org members\), RESTRICTED \(only invited\) |
|
||||
| `entryPointAccess` | string | No | Entry points allowed: ALL \(all entry points\) or CREATOR_APP_ONLY \(only via app\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `name` | string | Resource name of the space \(e.g., spaces/abc123\) |
|
||||
| `meetingUri` | string | Meeting URL \(e.g., https://meet.google.com/abc-defg-hij\) |
|
||||
| `meetingCode` | string | Meeting code \(e.g., abc-defg-hij\) |
|
||||
| `accessType` | string | Access type configuration |
|
||||
| `entryPointAccess` | string | Entry point access configuration |
|
||||
|
||||
### `google_meet_get_space`
|
||||
|
||||
Get details of a Google Meet meeting space by name or meeting code
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `spaceName` | string | Yes | Space resource name \(spaces/abc123\) or meeting code \(abc-defg-hij\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `name` | string | Resource name of the space |
|
||||
| `meetingUri` | string | Meeting URL |
|
||||
| `meetingCode` | string | Meeting code |
|
||||
| `accessType` | string | Access type configuration |
|
||||
| `entryPointAccess` | string | Entry point access configuration |
|
||||
| `activeConference` | string | Active conference record name |
|
||||
|
||||
### `google_meet_end_conference`
|
||||
|
||||
End the active conference in a Google Meet space
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `spaceName` | string | Yes | Space resource name \(e.g., spaces/abc123\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `ended` | boolean | Whether the conference was ended successfully |
|
||||
|
||||
### `google_meet_list_conference_records`
|
||||
|
||||
List conference records for meetings you organized
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `filter` | string | No | Filter by space name \(e.g., space.name = "spaces/abc123"\) or time range \(e.g., start_time > "2024-01-01T00:00:00Z"\) |
|
||||
| `pageSize` | number | No | Maximum number of conference records to return \(max 100\) |
|
||||
| `pageToken` | string | No | Page token from a previous list request |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `conferenceRecords` | json | List of conference records with name, start/end times, and space |
|
||||
| `nextPageToken` | string | Token for next page of results |
|
||||
|
||||
### `google_meet_get_conference_record`
|
||||
|
||||
Get details of a specific conference record
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `conferenceName` | string | Yes | Conference record resource name \(e.g., conferenceRecords/abc123\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `name` | string | Conference record resource name |
|
||||
| `startTime` | string | Conference start time |
|
||||
| `endTime` | string | Conference end time |
|
||||
| `expireTime` | string | Conference record expiration time |
|
||||
| `space` | string | Associated space resource name |
|
||||
|
||||
### `google_meet_list_participants`
|
||||
|
||||
List participants of a conference record
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `conferenceName` | string | Yes | Conference record resource name \(e.g., conferenceRecords/abc123\) |
|
||||
| `filter` | string | No | Filter participants \(e.g., earliest_start_time > "2024-01-01T00:00:00Z"\) |
|
||||
| `pageSize` | number | No | Maximum number of participants to return \(default 100, max 250\) |
|
||||
| `pageToken` | string | No | Page token from a previous list request |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `participants` | json | List of participants with name, times, display name, and user type |
|
||||
| `nextPageToken` | string | Token for next page of results |
|
||||
| `totalSize` | number | Total number of participants |
|
||||
|
||||
|
||||
84
apps/docs/content/docs/en/tools/google_pagespeed.mdx
Normal file
84
apps/docs/content/docs/en/tools/google_pagespeed.mdx
Normal file
@@ -0,0 +1,84 @@
|
||||
---
|
||||
title: Google PageSpeed
|
||||
description: Analyze webpage performance with Google PageSpeed Insights
|
||||
---
|
||||
|
||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||
|
||||
<BlockInfoCard
|
||||
type="google_pagespeed"
|
||||
color="#E0E0E0"
|
||||
/>
|
||||
|
||||
{/* MANUAL-CONTENT-START:intro */}
|
||||
[Google PageSpeed Insights](https://pagespeed.web.dev/) is a web performance analysis tool powered by Lighthouse that evaluates the quality of web pages across multiple dimensions including performance, accessibility, SEO, and best practices.
|
||||
|
||||
With the Google PageSpeed integration in Sim, you can:
|
||||
|
||||
- **Analyze webpage performance**: Get detailed performance scores and metrics for any public URL, including First Contentful Paint, Largest Contentful Paint, and Speed Index
|
||||
- **Evaluate accessibility**: Check how well a webpage meets accessibility standards and identify areas for improvement
|
||||
- **Audit SEO**: Assess a page's search engine optimization and discover opportunities to improve rankings
|
||||
- **Review best practices**: Verify that a webpage follows modern web development best practices
|
||||
- **Compare strategies**: Run analyses using either desktop or mobile strategies to understand performance across device types
|
||||
- **Localize results**: Retrieve analysis results in different locales for internationalized reporting
|
||||
|
||||
In Sim, the Google PageSpeed integration enables your agents to programmatically audit web pages as part of automated workflows. This is useful for monitoring site performance over time, triggering alerts when scores drop below thresholds, generating performance reports, and ensuring that deployed changes meet quality standards before release.
|
||||
|
||||
### Getting Your API Key
|
||||
|
||||
1. Go to the [Google Cloud Console](https://console.cloud.google.com/)
|
||||
2. Create or select a project
|
||||
3. Enable the **PageSpeed Insights API** from the API Library
|
||||
4. Navigate to **Credentials** and create an API key
|
||||
5. Use the API key in the Sim block configuration
|
||||
{/* MANUAL-CONTENT-END */}
|
||||
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
Analyze web pages for performance, accessibility, SEO, and best practices using Google PageSpeed Insights API powered by Lighthouse.
|
||||
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
### `google_pagespeed_analyze`
|
||||
|
||||
Analyze a webpage for performance, accessibility, SEO, and best practices using Google PageSpeed Insights.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | Google PageSpeed Insights API Key |
|
||||
| `url` | string | Yes | The URL of the webpage to analyze |
|
||||
| `category` | string | No | Lighthouse categories to analyze \(comma-separated\): performance, accessibility, best-practices, seo |
|
||||
| `strategy` | string | No | Analysis strategy: desktop or mobile |
|
||||
| `locale` | string | No | Locale for results \(e.g., en, fr, de\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `finalUrl` | string | The final URL after redirects |
|
||||
| `performanceScore` | number | Performance category score \(0-1\) |
|
||||
| `accessibilityScore` | number | Accessibility category score \(0-1\) |
|
||||
| `bestPracticesScore` | number | Best Practices category score \(0-1\) |
|
||||
| `seoScore` | number | SEO category score \(0-1\) |
|
||||
| `firstContentfulPaint` | string | Time to First Contentful Paint \(display value\) |
|
||||
| `firstContentfulPaintMs` | number | Time to First Contentful Paint in milliseconds |
|
||||
| `largestContentfulPaint` | string | Time to Largest Contentful Paint \(display value\) |
|
||||
| `largestContentfulPaintMs` | number | Time to Largest Contentful Paint in milliseconds |
|
||||
| `totalBlockingTime` | string | Total Blocking Time \(display value\) |
|
||||
| `totalBlockingTimeMs` | number | Total Blocking Time in milliseconds |
|
||||
| `cumulativeLayoutShift` | string | Cumulative Layout Shift \(display value\) |
|
||||
| `cumulativeLayoutShiftValue` | number | Cumulative Layout Shift numeric value |
|
||||
| `speedIndex` | string | Speed Index \(display value\) |
|
||||
| `speedIndexMs` | number | Speed Index in milliseconds |
|
||||
| `interactive` | string | Time to Interactive \(display value\) |
|
||||
| `interactiveMs` | number | Time to Interactive in milliseconds |
|
||||
| `overallCategory` | string | Overall loading experience category \(FAST, AVERAGE, SLOW, or NONE\) |
|
||||
| `analysisTimestamp` | string | UTC timestamp of the analysis |
|
||||
| `lighthouseVersion` | string | Version of Lighthouse used for the analysis |
|
||||
|
||||
|
||||
@@ -6,12 +6,14 @@
|
||||
"airtable",
|
||||
"airweave",
|
||||
"algolia",
|
||||
"amplitude",
|
||||
"apify",
|
||||
"apollo",
|
||||
"arxiv",
|
||||
"asana",
|
||||
"ashby",
|
||||
"attio",
|
||||
"brandfetch",
|
||||
"browser_use",
|
||||
"calcom",
|
||||
"calendly",
|
||||
@@ -27,6 +29,7 @@
|
||||
"discord",
|
||||
"dropbox",
|
||||
"dspy",
|
||||
"dub",
|
||||
"duckduckgo",
|
||||
"dynamodb",
|
||||
"elasticsearch",
|
||||
@@ -50,6 +53,8 @@
|
||||
"google_forms",
|
||||
"google_groups",
|
||||
"google_maps",
|
||||
"google_meet",
|
||||
"google_pagespeed",
|
||||
"google_search",
|
||||
"google_sheets",
|
||||
"google_slides",
|
||||
@@ -97,6 +102,7 @@
|
||||
"onepassword",
|
||||
"openai",
|
||||
"outlook",
|
||||
"pagerduty",
|
||||
"parallel_ai",
|
||||
"perplexity",
|
||||
"pinecone",
|
||||
|
||||
217
apps/docs/content/docs/en/tools/pagerduty.mdx
Normal file
217
apps/docs/content/docs/en/tools/pagerduty.mdx
Normal file
@@ -0,0 +1,217 @@
|
||||
---
|
||||
title: PagerDuty
|
||||
description: Manage incidents and on-call schedules with PagerDuty
|
||||
---
|
||||
|
||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||
|
||||
<BlockInfoCard
|
||||
type="pagerduty"
|
||||
color="#06AC38"
|
||||
/>
|
||||
|
||||
{/* MANUAL-CONTENT-START:intro */}
|
||||
[PagerDuty](https://www.pagerduty.com/) is a leading incident management platform that helps engineering and operations teams detect, triage, and resolve infrastructure and application issues in real time. PagerDuty integrates with monitoring tools, orchestrates on-call schedules, and ensures the right people are alerted when incidents occur.
|
||||
|
||||
The PagerDuty integration in Sim connects with the PagerDuty REST API v2 using API key authentication, enabling your agents to manage the full incident lifecycle and query on-call information programmatically.
|
||||
|
||||
With the PagerDuty integration, your agents can:
|
||||
|
||||
- **List and filter incidents**: Retrieve incidents filtered by status (triggered, acknowledged, resolved), service, date range, and sort order to monitor your operational health
|
||||
- **Create incidents**: Trigger new incidents on specific services with custom titles, descriptions, urgency levels, and assignees directly from your workflows
|
||||
- **Update incidents**: Acknowledge or resolve incidents, change urgency, and add resolution notes to keep your incident management in sync with automated processes
|
||||
- **Add notes to incidents**: Attach contextual information, investigation findings, or automated diagnostics as notes on existing incidents
|
||||
- **List services**: Query your PagerDuty service catalog to discover service IDs and metadata for use in other operations
|
||||
- **Check on-call schedules**: Retrieve current on-call entries filtered by escalation policy or schedule to determine who is responsible at any given time
|
||||
|
||||
In Sim, the PagerDuty integration enables powerful incident automation scenarios. Your agents can automatically create incidents based on monitoring alerts, enrich incidents with diagnostic data from other tools, resolve incidents when automated remediation succeeds, or build escalation workflows that check on-call schedules and route notifications accordingly. By connecting Sim with PagerDuty, you can build intelligent agents that bridge the gap between detection and response, reducing mean time to resolution and ensuring consistent incident handling across your organization.
|
||||
{/* MANUAL-CONTENT-END */}
|
||||
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
Integrate PagerDuty into your workflow to list, create, and update incidents, add notes, list services, and check on-call schedules.
|
||||
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
### `pagerduty_list_incidents`
|
||||
|
||||
List incidents from PagerDuty with optional filters.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | PagerDuty REST API Key |
|
||||
| `statuses` | string | No | Comma-separated statuses to filter \(triggered, acknowledged, resolved\) |
|
||||
| `serviceIds` | string | No | Comma-separated service IDs to filter |
|
||||
| `since` | string | No | Start date filter \(ISO 8601 format\) |
|
||||
| `until` | string | No | End date filter \(ISO 8601 format\) |
|
||||
| `sortBy` | string | No | Sort field \(e.g., created_at:desc\) |
|
||||
| `limit` | string | No | Maximum number of results \(max 100\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `incidents` | array | Array of incidents |
|
||||
| ↳ `id` | string | Incident ID |
|
||||
| ↳ `incidentNumber` | number | Incident number |
|
||||
| ↳ `title` | string | Incident title |
|
||||
| ↳ `status` | string | Incident status |
|
||||
| ↳ `urgency` | string | Incident urgency |
|
||||
| ↳ `createdAt` | string | Creation timestamp |
|
||||
| ↳ `updatedAt` | string | Last updated timestamp |
|
||||
| ↳ `serviceName` | string | Service name |
|
||||
| ↳ `serviceId` | string | Service ID |
|
||||
| ↳ `assigneeName` | string | Assignee name |
|
||||
| ↳ `assigneeId` | string | Assignee ID |
|
||||
| ↳ `escalationPolicyName` | string | Escalation policy name |
|
||||
| ↳ `htmlUrl` | string | PagerDuty web URL |
|
||||
| `total` | number | Total number of matching incidents |
|
||||
| `more` | boolean | Whether more results are available |
|
||||
|
||||
### `pagerduty_create_incident`
|
||||
|
||||
Create a new incident in PagerDuty.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | PagerDuty REST API Key |
|
||||
| `fromEmail` | string | Yes | Email address of a valid PagerDuty user |
|
||||
| `title` | string | Yes | Incident title/summary |
|
||||
| `serviceId` | string | Yes | ID of the PagerDuty service |
|
||||
| `urgency` | string | No | Urgency level \(high or low\) |
|
||||
| `body` | string | No | Detailed description of the incident |
|
||||
| `escalationPolicyId` | string | No | Escalation policy ID to assign |
|
||||
| `assigneeId` | string | No | User ID to assign the incident to |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `id` | string | Created incident ID |
|
||||
| `incidentNumber` | number | Incident number |
|
||||
| `title` | string | Incident title |
|
||||
| `status` | string | Incident status |
|
||||
| `urgency` | string | Incident urgency |
|
||||
| `createdAt` | string | Creation timestamp |
|
||||
| `serviceName` | string | Service name |
|
||||
| `serviceId` | string | Service ID |
|
||||
| `htmlUrl` | string | PagerDuty web URL |
|
||||
|
||||
### `pagerduty_update_incident`
|
||||
|
||||
Update an incident in PagerDuty (acknowledge, resolve, change urgency, etc.).
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | PagerDuty REST API Key |
|
||||
| `fromEmail` | string | Yes | Email address of a valid PagerDuty user |
|
||||
| `incidentId` | string | Yes | ID of the incident to update |
|
||||
| `status` | string | No | New status \(acknowledged or resolved\) |
|
||||
| `title` | string | No | New incident title |
|
||||
| `urgency` | string | No | New urgency \(high or low\) |
|
||||
| `escalationLevel` | string | No | Escalation level to escalate to |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `id` | string | Incident ID |
|
||||
| `incidentNumber` | number | Incident number |
|
||||
| `title` | string | Incident title |
|
||||
| `status` | string | Updated status |
|
||||
| `urgency` | string | Updated urgency |
|
||||
| `updatedAt` | string | Last updated timestamp |
|
||||
| `htmlUrl` | string | PagerDuty web URL |
|
||||
|
||||
### `pagerduty_add_note`
|
||||
|
||||
Add a note to an existing PagerDuty incident.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | PagerDuty REST API Key |
|
||||
| `fromEmail` | string | Yes | Email address of a valid PagerDuty user |
|
||||
| `incidentId` | string | Yes | ID of the incident to add the note to |
|
||||
| `content` | string | Yes | Note content text |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `id` | string | Note ID |
|
||||
| `content` | string | Note content |
|
||||
| `createdAt` | string | Creation timestamp |
|
||||
| `userName` | string | Name of the user who created the note |
|
||||
|
||||
### `pagerduty_list_services`
|
||||
|
||||
List services from PagerDuty with optional name filter.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | PagerDuty REST API Key |
|
||||
| `query` | string | No | Filter services by name |
|
||||
| `limit` | string | No | Maximum number of results \(max 100\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `services` | array | Array of services |
|
||||
| ↳ `id` | string | Service ID |
|
||||
| ↳ `name` | string | Service name |
|
||||
| ↳ `description` | string | Service description |
|
||||
| ↳ `status` | string | Service status |
|
||||
| ↳ `escalationPolicyName` | string | Escalation policy name |
|
||||
| ↳ `escalationPolicyId` | string | Escalation policy ID |
|
||||
| ↳ `createdAt` | string | Creation timestamp |
|
||||
| ↳ `htmlUrl` | string | PagerDuty web URL |
|
||||
| `total` | number | Total number of matching services |
|
||||
| `more` | boolean | Whether more results are available |
|
||||
|
||||
### `pagerduty_list_oncalls`
|
||||
|
||||
List current on-call entries from PagerDuty.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `apiKey` | string | Yes | PagerDuty REST API Key |
|
||||
| `escalationPolicyIds` | string | No | Comma-separated escalation policy IDs to filter |
|
||||
| `scheduleIds` | string | No | Comma-separated schedule IDs to filter |
|
||||
| `since` | string | No | Start time filter \(ISO 8601 format\) |
|
||||
| `until` | string | No | End time filter \(ISO 8601 format\) |
|
||||
| `limit` | string | No | Maximum number of results \(max 100\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `oncalls` | array | Array of on-call entries |
|
||||
| ↳ `userName` | string | On-call user name |
|
||||
| ↳ `userId` | string | On-call user ID |
|
||||
| ↳ `escalationLevel` | number | Escalation level |
|
||||
| ↳ `escalationPolicyName` | string | Escalation policy name |
|
||||
| ↳ `escalationPolicyId` | string | Escalation policy ID |
|
||||
| ↳ `scheduleName` | string | Schedule name |
|
||||
| ↳ `scheduleId` | string | Schedule ID |
|
||||
| ↳ `start` | string | On-call start time |
|
||||
| ↳ `end` | string | On-call end time |
|
||||
| `total` | number | Total number of matching on-call entries |
|
||||
| `more` | boolean | Whether more results are available |
|
||||
|
||||
|
||||
@@ -24,7 +24,7 @@ These operations let your agents access and analyze Reddit content as part of yo
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
Integrate Reddit into workflows. Read posts, comments, and search content. Submit posts, vote, reply, edit, and manage your Reddit account.
|
||||
Integrate Reddit into workflows. Read posts, comments, and search content. Submit posts, vote, reply, edit, manage messages, and access user and subreddit info.
|
||||
|
||||
|
||||
|
||||
@@ -39,14 +39,15 @@ Fetch posts from a subreddit with different sorting options
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `subreddit` | string | Yes | The subreddit to fetch posts from \(e.g., "technology", "news"\) |
|
||||
| `sort` | string | No | Sort method for posts \(e.g., "hot", "new", "top", "rising"\). Default: "hot" |
|
||||
| `sort` | string | No | Sort method for posts \(e.g., "hot", "new", "top", "rising", "controversial"\). Default: "hot" |
|
||||
| `limit` | number | No | Maximum number of posts to return \(e.g., 25\). Default: 10, max: 100 |
|
||||
| `time` | string | No | Time filter for "top" sorted posts: "day", "week", "month", "year", or "all" \(default: "day"\) |
|
||||
| `time` | string | No | Time filter for "top" sorted posts: "day", "week", "month", "year", or "all" \(default: "all"\) |
|
||||
| `after` | string | No | Fullname of a thing to fetch items after \(for pagination\) |
|
||||
| `before` | string | No | Fullname of a thing to fetch items before \(for pagination\) |
|
||||
| `count` | number | No | A count of items already seen in the listing \(used for numbering\) |
|
||||
| `show` | string | No | Show items that would normally be filtered \(e.g., "all"\) |
|
||||
| `sr_detail` | boolean | No | Expand subreddit details in the response |
|
||||
| `g` | string | No | Geo filter for posts \(e.g., "GLOBAL", "US", "AR", etc.\) |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -55,6 +56,7 @@ Fetch posts from a subreddit with different sorting options
|
||||
| `subreddit` | string | Name of the subreddit where posts were fetched from |
|
||||
| `posts` | array | Array of posts with title, author, URL, score, comments count, and metadata |
|
||||
| ↳ `id` | string | Post ID |
|
||||
| ↳ `name` | string | Thing fullname \(t3_xxxxx\) |
|
||||
| ↳ `title` | string | Post title |
|
||||
| ↳ `author` | string | Author username |
|
||||
| ↳ `url` | string | Post URL |
|
||||
@@ -66,6 +68,8 @@ Fetch posts from a subreddit with different sorting options
|
||||
| ↳ `selftext` | string | Text content for self posts |
|
||||
| ↳ `thumbnail` | string | Thumbnail URL |
|
||||
| ↳ `subreddit` | string | Subreddit name |
|
||||
| `after` | string | Fullname of the last item for forward pagination |
|
||||
| `before` | string | Fullname of the first item for backward pagination |
|
||||
|
||||
### `reddit_get_comments`
|
||||
|
||||
@@ -83,12 +87,9 @@ Fetch comments from a specific Reddit post
|
||||
| `context` | number | No | Number of parent comments to include |
|
||||
| `showedits` | boolean | No | Show edit information for comments |
|
||||
| `showmore` | boolean | No | Include "load more comments" elements in the response |
|
||||
| `showtitle` | boolean | No | Include submission title in the response |
|
||||
| `threaded` | boolean | No | Return comments in threaded/nested format |
|
||||
| `truncate` | number | No | Integer to truncate comment depth |
|
||||
| `after` | string | No | Fullname of a thing to fetch items after \(for pagination\) |
|
||||
| `before` | string | No | Fullname of a thing to fetch items before \(for pagination\) |
|
||||
| `count` | number | No | A count of items already seen in the listing \(used for numbering\) |
|
||||
| `comment` | string | No | ID36 of a comment to focus on \(returns that comment thread\) |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -96,6 +97,7 @@ Fetch comments from a specific Reddit post
|
||||
| --------- | ---- | ----------- |
|
||||
| `post` | object | Post information including ID, title, author, content, and metadata |
|
||||
| ↳ `id` | string | Post ID |
|
||||
| ↳ `name` | string | Thing fullname \(t3_xxxxx\) |
|
||||
| ↳ `title` | string | Post title |
|
||||
| ↳ `author` | string | Post author |
|
||||
| ↳ `selftext` | string | Post text content |
|
||||
@@ -104,6 +106,7 @@ Fetch comments from a specific Reddit post
|
||||
| ↳ `permalink` | string | Reddit permalink |
|
||||
| `comments` | array | Nested comments with author, body, score, timestamps, and replies |
|
||||
| ↳ `id` | string | Comment ID |
|
||||
| ↳ `name` | string | Thing fullname \(t1_xxxxx\) |
|
||||
| ↳ `author` | string | Comment author |
|
||||
| ↳ `body` | string | Comment text |
|
||||
| ↳ `score` | number | Comment score |
|
||||
@@ -135,6 +138,7 @@ Fetch controversial posts from a subreddit
|
||||
| `subreddit` | string | Name of the subreddit where posts were fetched from |
|
||||
| `posts` | array | Array of controversial posts with title, author, URL, score, comments count, and metadata |
|
||||
| ↳ `id` | string | Post ID |
|
||||
| ↳ `name` | string | Thing fullname \(t3_xxxxx\) |
|
||||
| ↳ `title` | string | Post title |
|
||||
| ↳ `author` | string | Author username |
|
||||
| ↳ `url` | string | Post URL |
|
||||
@@ -146,6 +150,8 @@ Fetch controversial posts from a subreddit
|
||||
| ↳ `selftext` | string | Text content for self posts |
|
||||
| ↳ `thumbnail` | string | Thumbnail URL |
|
||||
| ↳ `subreddit` | string | Subreddit name |
|
||||
| `after` | string | Fullname of the last item for forward pagination |
|
||||
| `before` | string | Fullname of the first item for backward pagination |
|
||||
|
||||
### `reddit_search`
|
||||
|
||||
@@ -165,6 +171,8 @@ Search for posts within a subreddit
|
||||
| `before` | string | No | Fullname of a thing to fetch items before \(for pagination\) |
|
||||
| `count` | number | No | A count of items already seen in the listing \(used for numbering\) |
|
||||
| `show` | string | No | Show items that would normally be filtered \(e.g., "all"\) |
|
||||
| `type` | string | No | Type of search results: "link" \(posts\), "sr" \(subreddits\), or "user" \(users\). Default: "link" |
|
||||
| `sr_detail` | boolean | No | Expand subreddit details in the response |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -173,6 +181,7 @@ Search for posts within a subreddit
|
||||
| `subreddit` | string | Name of the subreddit where search was performed |
|
||||
| `posts` | array | Array of search result posts with title, author, URL, score, comments count, and metadata |
|
||||
| ↳ `id` | string | Post ID |
|
||||
| ↳ `name` | string | Thing fullname \(t3_xxxxx\) |
|
||||
| ↳ `title` | string | Post title |
|
||||
| ↳ `author` | string | Author username |
|
||||
| ↳ `url` | string | Post URL |
|
||||
@@ -184,6 +193,8 @@ Search for posts within a subreddit
|
||||
| ↳ `selftext` | string | Text content for self posts |
|
||||
| ↳ `thumbnail` | string | Thumbnail URL |
|
||||
| ↳ `subreddit` | string | Subreddit name |
|
||||
| `after` | string | Fullname of the last item for forward pagination |
|
||||
| `before` | string | Fullname of the first item for backward pagination |
|
||||
|
||||
### `reddit_submit_post`
|
||||
|
||||
@@ -200,6 +211,9 @@ Submit a new post to a subreddit (text or link)
|
||||
| `nsfw` | boolean | No | Mark post as NSFW |
|
||||
| `spoiler` | boolean | No | Mark post as spoiler |
|
||||
| `send_replies` | boolean | No | Send reply notifications to inbox \(default: true\) |
|
||||
| `flair_id` | string | No | Flair template UUID for the post \(max 36 characters\) |
|
||||
| `flair_text` | string | No | Flair text to display on the post \(max 64 characters\) |
|
||||
| `collection_id` | string | No | Collection UUID to add the post to |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -264,6 +278,21 @@ Save a Reddit post or comment to your saved items
|
||||
| `posts` | json | Posts data |
|
||||
| `post` | json | Single post data |
|
||||
| `comments` | json | Comments data |
|
||||
| `success` | boolean | Operation success status |
|
||||
| `message` | string | Result message |
|
||||
| `data` | json | Response data |
|
||||
| `after` | string | Pagination cursor \(next page\) |
|
||||
| `before` | string | Pagination cursor \(previous page\) |
|
||||
| `id` | string | Entity ID |
|
||||
| `name` | string | Entity fullname |
|
||||
| `messages` | json | Messages data |
|
||||
| `display_name` | string | Subreddit display name |
|
||||
| `subscribers` | number | Subscriber count |
|
||||
| `description` | string | Description text |
|
||||
| `link_karma` | number | Link karma |
|
||||
| `comment_karma` | number | Comment karma |
|
||||
| `total_karma` | number | Total karma |
|
||||
| `icon_img` | string | Icon image URL |
|
||||
|
||||
### `reddit_reply`
|
||||
|
||||
@@ -275,6 +304,7 @@ Add a comment reply to a Reddit post or comment
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `parent_id` | string | Yes | Thing fullname to reply to \(e.g., "t3_abc123" for post, "t1_def456" for comment\) |
|
||||
| `text` | string | Yes | Comment text in markdown format \(e.g., "Great post! Here is my **reply**"\) |
|
||||
| `return_rtjson` | boolean | No | Return response in Rich Text JSON format |
|
||||
|
||||
#### Output
|
||||
|
||||
@@ -345,4 +375,138 @@ Subscribe or unsubscribe from a subreddit
|
||||
| `success` | boolean | Whether the subscription action was successful |
|
||||
| `message` | string | Success or error message |
|
||||
|
||||
### `reddit_get_me`
|
||||
|
||||
Get information about the authenticated Reddit user
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `id` | string | User ID |
|
||||
| `name` | string | Username |
|
||||
| `created_utc` | number | Account creation time in UTC epoch seconds |
|
||||
| `link_karma` | number | Total link karma |
|
||||
| `comment_karma` | number | Total comment karma |
|
||||
| `total_karma` | number | Combined total karma |
|
||||
| `is_gold` | boolean | Whether user has Reddit Premium |
|
||||
| `is_mod` | boolean | Whether user is a moderator |
|
||||
| `has_verified_email` | boolean | Whether email is verified |
|
||||
| `icon_img` | string | User avatar/icon URL |
|
||||
|
||||
### `reddit_get_user`
|
||||
|
||||
Get public profile information about any Reddit user by username
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `username` | string | Yes | Reddit username to look up \(e.g., "spez", "example_user"\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `id` | string | User ID |
|
||||
| `name` | string | Username |
|
||||
| `created_utc` | number | Account creation time in UTC epoch seconds |
|
||||
| `link_karma` | number | Total link karma |
|
||||
| `comment_karma` | number | Total comment karma |
|
||||
| `total_karma` | number | Combined total karma |
|
||||
| `is_gold` | boolean | Whether user has Reddit Premium |
|
||||
| `is_mod` | boolean | Whether user is a moderator |
|
||||
| `has_verified_email` | boolean | Whether email is verified |
|
||||
| `icon_img` | string | User avatar/icon URL |
|
||||
|
||||
### `reddit_send_message`
|
||||
|
||||
Send a private message to a Reddit user
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `to` | string | Yes | Recipient username \(e.g., "example_user"\) or subreddit \(e.g., "/r/subreddit"\) |
|
||||
| `subject` | string | Yes | Message subject \(max 100 characters\) |
|
||||
| `text` | string | Yes | Message body in markdown format |
|
||||
| `from_sr` | string | No | Subreddit name to send the message from \(requires moderator mail permission\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `success` | boolean | Whether the message was sent successfully |
|
||||
| `message` | string | Success or error message |
|
||||
|
||||
### `reddit_get_messages`
|
||||
|
||||
Retrieve private messages from your Reddit inbox
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `where` | string | No | Message folder to retrieve: "inbox" \(all\), "unread", "sent", "messages" \(direct messages only\), "comments" \(comment replies\), "selfreply" \(self-post replies\), or "mentions" \(username mentions\). Default: "inbox" |
|
||||
| `limit` | number | No | Maximum number of messages to return \(e.g., 25\). Default: 25, max: 100 |
|
||||
| `after` | string | No | Fullname of a thing to fetch items after \(for pagination\) |
|
||||
| `before` | string | No | Fullname of a thing to fetch items before \(for pagination\) |
|
||||
| `mark` | boolean | No | Whether to mark fetched messages as read |
|
||||
| `count` | number | No | A count of items already seen in the listing \(used for numbering\) |
|
||||
| `show` | string | No | Show items that would normally be filtered \(e.g., "all"\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `messages` | array | Array of messages with sender, recipient, subject, body, and metadata |
|
||||
| ↳ `id` | string | Message ID |
|
||||
| ↳ `name` | string | Thing fullname \(t4_xxxxx\) |
|
||||
| ↳ `author` | string | Sender username |
|
||||
| ↳ `dest` | string | Recipient username |
|
||||
| ↳ `subject` | string | Message subject |
|
||||
| ↳ `body` | string | Message body text |
|
||||
| ↳ `created_utc` | number | Creation time in UTC epoch seconds |
|
||||
| ↳ `new` | boolean | Whether the message is unread |
|
||||
| ↳ `was_comment` | boolean | Whether the message is a comment reply |
|
||||
| ↳ `context` | string | Context URL for comment replies |
|
||||
| ↳ `distinguished` | string | Distinction: null/"moderator"/"admin" |
|
||||
| `after` | string | Fullname of the last item for forward pagination |
|
||||
| `before` | string | Fullname of the first item for backward pagination |
|
||||
|
||||
### `reddit_get_subreddit_info`
|
||||
|
||||
Get metadata and information about a subreddit
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `subreddit` | string | Yes | The subreddit to get info about \(e.g., "technology", "programming", "news"\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `id` | string | Subreddit ID |
|
||||
| `name` | string | Subreddit fullname \(t5_xxxxx\) |
|
||||
| `display_name` | string | Subreddit name without prefix |
|
||||
| `title` | string | Subreddit title |
|
||||
| `description` | string | Full subreddit description \(markdown\) |
|
||||
| `public_description` | string | Short public description |
|
||||
| `subscribers` | number | Number of subscribers |
|
||||
| `accounts_active` | number | Number of currently active users |
|
||||
| `created_utc` | number | Creation time in UTC epoch seconds |
|
||||
| `over18` | boolean | Whether the subreddit is NSFW |
|
||||
| `lang` | string | Primary language of the subreddit |
|
||||
| `subreddit_type` | string | Subreddit type: public, private, restricted, etc. |
|
||||
| `url` | string | Subreddit URL path \(e.g., /r/technology/\) |
|
||||
| `icon_img` | string | Subreddit icon URL |
|
||||
| `banner_img` | string | Subreddit banner URL |
|
||||
|
||||
|
||||
|
||||
@@ -69,7 +69,9 @@ Read records from a ServiceNow table
|
||||
| `number` | string | No | Record number \(e.g., INC0010001\) |
|
||||
| `query` | string | No | Encoded query string \(e.g., "active=true^priority=1"\) |
|
||||
| `limit` | number | No | Maximum number of records to return \(e.g., 10, 50, 100\) |
|
||||
| `offset` | number | No | Number of records to skip for pagination \(e.g., 0, 10, 20\) |
|
||||
| `fields` | string | No | Comma-separated list of fields to return \(e.g., sys_id,number,short_description,state\) |
|
||||
| `displayValue` | string | No | Return display values for reference fields: "true" \(display only\), "false" \(sys_id only\), or "all" \(both\) |
|
||||
|
||||
#### Output
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
---
|
||||
title: Slack
|
||||
description: Send, update, delete messages, send ephemeral messages, add reactions in Slack or trigger workflows from Slack events
|
||||
description: Send, update, delete messages, manage views and modals, add or remove reactions, manage canvases, get channel info and user presence in Slack
|
||||
---
|
||||
|
||||
import { BlockInfoCard } from "@/components/ui/block-info-card"
|
||||
@@ -39,7 +39,7 @@ If you encounter issues with the Slack integration, contact us at [help@sim.ai](
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
Integrate Slack into the workflow. Can send, update, and delete messages, send ephemeral messages visible only to a specific user, create canvases, read messages, and add reactions. Requires Bot Token instead of OAuth in advanced mode. Can be used in trigger mode to trigger a workflow when a message is sent to a channel.
|
||||
Integrate Slack into the workflow. Can send, update, and delete messages, send ephemeral messages visible only to a specific user, open/update/push modal views, publish Home tab views, create canvases, read messages, and add or remove reactions. Requires Bot Token instead of OAuth in advanced mode. Can be used in trigger mode to trigger a workflow when a message is sent to a channel.
|
||||
|
||||
|
||||
|
||||
@@ -799,4 +799,313 @@ Add an emoji reaction to a Slack message
|
||||
| ↳ `timestamp` | string | Message timestamp |
|
||||
| ↳ `reaction` | string | Emoji reaction name |
|
||||
|
||||
### `slack_remove_reaction`
|
||||
|
||||
Remove an emoji reaction from a Slack message
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `authMethod` | string | No | Authentication method: oauth or bot_token |
|
||||
| `botToken` | string | No | Bot token for Custom Bot |
|
||||
| `channel` | string | Yes | Channel ID where the message was posted \(e.g., C1234567890\) |
|
||||
| `timestamp` | string | Yes | Timestamp of the message to remove reaction from \(e.g., 1405894322.002768\) |
|
||||
| `name` | string | Yes | Name of the emoji reaction to remove \(without colons, e.g., thumbsup, heart, eyes\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `content` | string | Success message |
|
||||
| `metadata` | object | Reaction metadata |
|
||||
| ↳ `channel` | string | Channel ID |
|
||||
| ↳ `timestamp` | string | Message timestamp |
|
||||
| ↳ `reaction` | string | Emoji reaction name |
|
||||
|
||||
### `slack_get_channel_info`
|
||||
|
||||
Get detailed information about a Slack channel by its ID
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `authMethod` | string | No | Authentication method: oauth or bot_token |
|
||||
| `botToken` | string | No | Bot token for Custom Bot |
|
||||
| `channel` | string | Yes | Channel ID to get information about \(e.g., C1234567890\) |
|
||||
| `includeNumMembers` | boolean | No | Whether to include the member count in the response |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `channelInfo` | object | Detailed channel information |
|
||||
| ↳ `id` | string | Channel ID \(e.g., C1234567890\) |
|
||||
| ↳ `name` | string | Channel name without # prefix |
|
||||
| ↳ `is_channel` | boolean | Whether this is a channel |
|
||||
| ↳ `is_private` | boolean | Whether channel is private |
|
||||
| ↳ `is_archived` | boolean | Whether channel is archived |
|
||||
| ↳ `is_general` | boolean | Whether this is the general channel |
|
||||
| ↳ `is_member` | boolean | Whether the bot/user is a member |
|
||||
| ↳ `is_shared` | boolean | Whether channel is shared across workspaces |
|
||||
| ↳ `is_ext_shared` | boolean | Whether channel is externally shared |
|
||||
| ↳ `is_org_shared` | boolean | Whether channel is org-wide shared |
|
||||
| ↳ `num_members` | number | Number of members in the channel |
|
||||
| ↳ `topic` | string | Channel topic |
|
||||
| ↳ `purpose` | string | Channel purpose/description |
|
||||
| ↳ `created` | number | Unix timestamp when channel was created |
|
||||
| ↳ `creator` | string | User ID of channel creator |
|
||||
| ↳ `updated` | number | Unix timestamp of last update |
|
||||
|
||||
### `slack_get_user_presence`
|
||||
|
||||
Check whether a Slack user is currently active or away
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `authMethod` | string | No | Authentication method: oauth or bot_token |
|
||||
| `botToken` | string | No | Bot token for Custom Bot |
|
||||
| `userId` | string | Yes | User ID to check presence for \(e.g., U1234567890\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `presence` | string | User presence status: "active" or "away" |
|
||||
| `online` | boolean | Whether user has an active client connection \(only available when checking own presence\) |
|
||||
| `autoAway` | boolean | Whether user was automatically set to away due to inactivity \(only available when checking own presence\) |
|
||||
| `manualAway` | boolean | Whether user manually set themselves as away \(only available when checking own presence\) |
|
||||
| `connectionCount` | number | Total number of active connections for the user \(only available when checking own presence\) |
|
||||
| `lastActivity` | number | Unix timestamp of last detected activity \(only available when checking own presence\) |
|
||||
|
||||
### `slack_edit_canvas`
|
||||
|
||||
Edit an existing Slack canvas by inserting, replacing, or deleting content
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `authMethod` | string | No | Authentication method: oauth or bot_token |
|
||||
| `botToken` | string | No | Bot token for Custom Bot |
|
||||
| `canvasId` | string | Yes | Canvas ID to edit \(e.g., F1234ABCD\) |
|
||||
| `operation` | string | Yes | Edit operation: insert_at_start, insert_at_end, insert_after, insert_before, replace, delete, or rename |
|
||||
| `content` | string | No | Markdown content for the operation \(required for insert/replace operations\) |
|
||||
| `sectionId` | string | No | Section ID to target \(required for insert_after, insert_before, replace, and delete\) |
|
||||
| `title` | string | No | New title for the canvas \(only used with rename operation\) |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `content` | string | Success message |
|
||||
|
||||
### `slack_create_channel_canvas`
|
||||
|
||||
Create a canvas pinned to a Slack channel as its resource hub
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `authMethod` | string | No | Authentication method: oauth or bot_token |
|
||||
| `botToken` | string | No | Bot token for Custom Bot |
|
||||
| `channel` | string | Yes | Channel ID to create the canvas in \(e.g., C1234567890\) |
|
||||
| `title` | string | No | Title for the channel canvas |
|
||||
| `content` | string | No | Canvas content in markdown format |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `canvas_id` | string | ID of the created channel canvas |
|
||||
|
||||
### `slack_open_view`
|
||||
|
||||
Open a modal view in Slack using a trigger_id from an interaction payload. Used to display forms, confirmations, and other interactive modals.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `authMethod` | string | No | Authentication method: oauth or bot_token |
|
||||
| `botToken` | string | No | Bot token for Custom Bot |
|
||||
| `triggerId` | string | Yes | Exchange a trigger to post to the user. Obtained from an interaction payload \(e.g., slash command, button click\) |
|
||||
| `interactivityPointer` | string | No | Alternative to trigger_id for posting to user |
|
||||
| `view` | json | Yes | A view payload object defining the modal. Must include type \("modal"\), title, and blocks array |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `view` | object | The opened modal view object |
|
||||
| ↳ `id` | string | Unique view identifier |
|
||||
| ↳ `team_id` | string | Workspace/team ID |
|
||||
| ↳ `type` | string | View type \(e.g., "modal"\) |
|
||||
| ↳ `title` | json | Plain text title object with type and text fields |
|
||||
| ↳ `type` | string | Text object type \(plain_text\) |
|
||||
| ↳ `text` | string | Title text content |
|
||||
| ↳ `submit` | json | Plain text submit button object |
|
||||
| ↳ `type` | string | Text object type \(plain_text\) |
|
||||
| ↳ `text` | string | Submit button text |
|
||||
| ↳ `close` | json | Plain text close button object |
|
||||
| ↳ `type` | string | Text object type \(plain_text\) |
|
||||
| ↳ `text` | string | Close button text |
|
||||
| ↳ `blocks` | array | Block Kit blocks in the view |
|
||||
| ↳ `type` | string | Block type \(section, divider, image, actions, etc.\) |
|
||||
| ↳ `block_id` | string | Unique block identifier |
|
||||
| ↳ `private_metadata` | string | Private metadata string passed with the view |
|
||||
| ↳ `callback_id` | string | Custom identifier for the view |
|
||||
| ↳ `external_id` | string | Custom external identifier \(max 255 chars, unique per workspace\) |
|
||||
| ↳ `state` | json | Current state of the view with input values |
|
||||
| ↳ `hash` | string | View version hash for updates |
|
||||
| ↳ `clear_on_close` | boolean | Whether to clear all views in the stack when this view is closed |
|
||||
| ↳ `notify_on_close` | boolean | Whether to send a view_closed event when this view is closed |
|
||||
| ↳ `root_view_id` | string | ID of the root view in the view stack |
|
||||
| ↳ `previous_view_id` | string | ID of the previous view in the view stack |
|
||||
| ↳ `app_id` | string | Application identifier |
|
||||
| ↳ `bot_id` | string | Bot identifier |
|
||||
|
||||
### `slack_update_view`
|
||||
|
||||
Update an existing modal view in Slack. Identify the view by view_id or external_id, and provide the updated view payload.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `authMethod` | string | No | Authentication method: oauth or bot_token |
|
||||
| `botToken` | string | No | Bot token for Custom Bot |
|
||||
| `viewId` | string | No | Unique identifier of the view to update. Either viewId or externalId is required |
|
||||
| `externalId` | string | No | Developer-set unique identifier of the view to update \(max 255 chars\). Either viewId or externalId is required |
|
||||
| `hash` | string | No | View state hash to protect against race conditions. Obtained from a previous views response |
|
||||
| `view` | json | Yes | A view payload object defining the updated modal. Must include type \("modal"\), title, and blocks array. Use identical block_id and action_id values to preserve input data |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `view` | object | The updated modal view object |
|
||||
| ↳ `id` | string | Unique view identifier |
|
||||
| ↳ `team_id` | string | Workspace/team ID |
|
||||
| ↳ `type` | string | View type \(e.g., "modal"\) |
|
||||
| ↳ `title` | json | Plain text title object with type and text fields |
|
||||
| ↳ `type` | string | Text object type \(plain_text\) |
|
||||
| ↳ `text` | string | Title text content |
|
||||
| ↳ `submit` | json | Plain text submit button object |
|
||||
| ↳ `type` | string | Text object type \(plain_text\) |
|
||||
| ↳ `text` | string | Submit button text |
|
||||
| ↳ `close` | json | Plain text close button object |
|
||||
| ↳ `type` | string | Text object type \(plain_text\) |
|
||||
| ↳ `text` | string | Close button text |
|
||||
| ↳ `blocks` | array | Block Kit blocks in the view |
|
||||
| ↳ `type` | string | Block type \(section, divider, image, actions, etc.\) |
|
||||
| ↳ `block_id` | string | Unique block identifier |
|
||||
| ↳ `private_metadata` | string | Private metadata string passed with the view |
|
||||
| ↳ `callback_id` | string | Custom identifier for the view |
|
||||
| ↳ `external_id` | string | Custom external identifier \(max 255 chars, unique per workspace\) |
|
||||
| ↳ `state` | json | Current state of the view with input values |
|
||||
| ↳ `hash` | string | View version hash for updates |
|
||||
| ↳ `clear_on_close` | boolean | Whether to clear all views in the stack when this view is closed |
|
||||
| ↳ `notify_on_close` | boolean | Whether to send a view_closed event when this view is closed |
|
||||
| ↳ `root_view_id` | string | ID of the root view in the view stack |
|
||||
| ↳ `previous_view_id` | string | ID of the previous view in the view stack |
|
||||
| ↳ `app_id` | string | Application identifier |
|
||||
| ↳ `bot_id` | string | Bot identifier |
|
||||
|
||||
### `slack_push_view`
|
||||
|
||||
Push a new view onto an existing modal stack in Slack. Limited to 2 additional views after the initial modal is opened.
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `authMethod` | string | No | Authentication method: oauth or bot_token |
|
||||
| `botToken` | string | No | Bot token for Custom Bot |
|
||||
| `triggerId` | string | Yes | Exchange a trigger to post to the user. Obtained from an interaction payload \(e.g., button click within an existing modal\) |
|
||||
| `interactivityPointer` | string | No | Alternative to trigger_id for posting to user |
|
||||
| `view` | json | Yes | A view payload object defining the modal to push. Must include type \("modal"\), title, and blocks array |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `view` | object | The pushed modal view object |
|
||||
| ↳ `id` | string | Unique view identifier |
|
||||
| ↳ `team_id` | string | Workspace/team ID |
|
||||
| ↳ `type` | string | View type \(e.g., "modal"\) |
|
||||
| ↳ `title` | json | Plain text title object with type and text fields |
|
||||
| ↳ `type` | string | Text object type \(plain_text\) |
|
||||
| ↳ `text` | string | Title text content |
|
||||
| ↳ `submit` | json | Plain text submit button object |
|
||||
| ↳ `type` | string | Text object type \(plain_text\) |
|
||||
| ↳ `text` | string | Submit button text |
|
||||
| ↳ `close` | json | Plain text close button object |
|
||||
| ↳ `type` | string | Text object type \(plain_text\) |
|
||||
| ↳ `text` | string | Close button text |
|
||||
| ↳ `blocks` | array | Block Kit blocks in the view |
|
||||
| ↳ `type` | string | Block type \(section, divider, image, actions, etc.\) |
|
||||
| ↳ `block_id` | string | Unique block identifier |
|
||||
| ↳ `private_metadata` | string | Private metadata string passed with the view |
|
||||
| ↳ `callback_id` | string | Custom identifier for the view |
|
||||
| ↳ `external_id` | string | Custom external identifier \(max 255 chars, unique per workspace\) |
|
||||
| ↳ `state` | json | Current state of the view with input values |
|
||||
| ↳ `hash` | string | View version hash for updates |
|
||||
| ↳ `clear_on_close` | boolean | Whether to clear all views in the stack when this view is closed |
|
||||
| ↳ `notify_on_close` | boolean | Whether to send a view_closed event when this view is closed |
|
||||
| ↳ `root_view_id` | string | ID of the root view in the view stack |
|
||||
| ↳ `previous_view_id` | string | ID of the previous view in the view stack |
|
||||
| ↳ `app_id` | string | Application identifier |
|
||||
| ↳ `bot_id` | string | Bot identifier |
|
||||
|
||||
### `slack_publish_view`
|
||||
|
||||
Publish a static view to a user
|
||||
|
||||
#### Input
|
||||
|
||||
| Parameter | Type | Required | Description |
|
||||
| --------- | ---- | -------- | ----------- |
|
||||
| `authMethod` | string | No | Authentication method: oauth or bot_token |
|
||||
| `botToken` | string | No | Bot token for Custom Bot |
|
||||
| `userId` | string | Yes | The user ID to publish the Home tab view to \(e.g., U0BPQUNTA\) |
|
||||
| `hash` | string | No | View state hash to protect against race conditions. Obtained from a previous views response |
|
||||
| `view` | json | Yes | A view payload object defining the Home tab. Must include type \("home"\) and blocks array |
|
||||
|
||||
#### Output
|
||||
|
||||
| Parameter | Type | Description |
|
||||
| --------- | ---- | ----------- |
|
||||
| `view` | object | The published Home tab view object |
|
||||
| ↳ `id` | string | Unique view identifier |
|
||||
| ↳ `team_id` | string | Workspace/team ID |
|
||||
| ↳ `type` | string | View type \(e.g., "modal"\) |
|
||||
| ↳ `title` | json | Plain text title object with type and text fields |
|
||||
| ↳ `type` | string | Text object type \(plain_text\) |
|
||||
| ↳ `text` | string | Title text content |
|
||||
| ↳ `submit` | json | Plain text submit button object |
|
||||
| ↳ `type` | string | Text object type \(plain_text\) |
|
||||
| ↳ `text` | string | Submit button text |
|
||||
| ↳ `close` | json | Plain text close button object |
|
||||
| ↳ `type` | string | Text object type \(plain_text\) |
|
||||
| ↳ `text` | string | Close button text |
|
||||
| ↳ `blocks` | array | Block Kit blocks in the view |
|
||||
| ↳ `type` | string | Block type \(section, divider, image, actions, etc.\) |
|
||||
| ↳ `block_id` | string | Unique block identifier |
|
||||
| ↳ `private_metadata` | string | Private metadata string passed with the view |
|
||||
| ↳ `callback_id` | string | Custom identifier for the view |
|
||||
| ↳ `external_id` | string | Custom external identifier \(max 255 chars, unique per workspace\) |
|
||||
| ↳ `state` | json | Current state of the view with input values |
|
||||
| ↳ `hash` | string | View version hash for updates |
|
||||
| ↳ `clear_on_close` | boolean | Whether to clear all views in the stack when this view is closed |
|
||||
| ↳ `notify_on_close` | boolean | Whether to send a view_closed event when this view is closed |
|
||||
| ↳ `root_view_id` | string | ID of the root view in the view stack |
|
||||
| ↳ `previous_view_id` | string | ID of the previous view in the view stack |
|
||||
| ↳ `app_id` | string | Application identifier |
|
||||
| ↳ `bot_id` | string | Bot identifier |
|
||||
|
||||
|
||||
|
||||
94
apps/docs/content/docs/es/api-reference/authentication.mdx
Normal file
94
apps/docs/content/docs/es/api-reference/authentication.mdx
Normal file
@@ -0,0 +1,94 @@
|
||||
---
|
||||
title: Authentication
|
||||
description: API key types, generation, and how to authenticate requests
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
|
||||
To access the Sim API, you need an API key. Sim supports two types of API keys — **personal keys** and **workspace keys** — each with different billing and access behaviors.
|
||||
|
||||
## Key Types
|
||||
|
||||
| | **Personal Keys** | **Workspace Keys** |
|
||||
| --- | --- | --- |
|
||||
| **Billed to** | Your individual account | Workspace owner |
|
||||
| **Scope** | Across workspaces you have access to | Shared across the workspace |
|
||||
| **Managed by** | Each user individually | Workspace admins |
|
||||
| **Permissions** | Must be enabled at workspace level | Require admin permissions |
|
||||
|
||||
<Callout type="info">
|
||||
Workspace admins can disable personal API key usage for their workspace. If disabled, only workspace keys can be used.
|
||||
</Callout>
|
||||
|
||||
## Generating API Keys
|
||||
|
||||
To generate a key, open the Sim dashboard and navigate to **Settings**, then go to **Sim Keys** and click **Create**.
|
||||
|
||||
<Callout type="warn">
|
||||
API keys are only shown once when generated. Store your key securely — you will not be able to view it again.
|
||||
</Callout>
|
||||
|
||||
## Using API Keys
|
||||
|
||||
Pass your API key in the `X-API-Key` header with every request:
|
||||
|
||||
<Tabs items={['curl', 'TypeScript', 'Python']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch(
|
||||
'https://www.sim.ai/api/workflows/{workflowId}/execute',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': process.env.SIM_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify({ inputs: {} }),
|
||||
}
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
```python
|
||||
import requests
|
||||
|
||||
response = requests.post(
|
||||
"https://www.sim.ai/api/workflows/{workflowId}/execute",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": os.environ["SIM_API_KEY"],
|
||||
},
|
||||
json={"inputs": {}},
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Where Keys Are Used
|
||||
|
||||
API keys authenticate access to:
|
||||
|
||||
- **Workflow execution** — run deployed workflows via the API
|
||||
- **Logs API** — query workflow execution logs and metrics
|
||||
- **MCP servers** — authenticate connections to deployed MCP servers
|
||||
- **SDKs** — the [Python](/api-reference/python) and [TypeScript](/api-reference/typescript) SDKs use API keys for all operations
|
||||
|
||||
## Security
|
||||
|
||||
- Keys use the `sk-sim-` prefix and are encrypted at rest
|
||||
- Keys can be revoked at any time from the dashboard
|
||||
- Use environment variables to store keys — never hardcode them in source code
|
||||
- For browser-based applications, use a backend proxy to avoid exposing keys to the client
|
||||
|
||||
<Callout type="warn">
|
||||
Never expose your API key in client-side code. Use a server-side proxy to make authenticated requests on behalf of your frontend.
|
||||
</Callout>
|
||||
210
apps/docs/content/docs/es/api-reference/getting-started.mdx
Normal file
210
apps/docs/content/docs/es/api-reference/getting-started.mdx
Normal file
@@ -0,0 +1,210 @@
|
||||
---
|
||||
title: Getting Started
|
||||
description: Base URL, first API call, response format, error handling, and pagination
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
|
||||
## Base URL
|
||||
|
||||
All API requests are made to:
|
||||
|
||||
```
|
||||
https://www.sim.ai
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step>
|
||||
### Get your API key
|
||||
|
||||
Go to the Sim platform and navigate to **Settings**, then go to **Sim Keys** and click **Create**. See [Authentication](/api-reference/authentication) for details on key types.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Find your workflow ID
|
||||
|
||||
Open a workflow in the Sim editor. The workflow ID is in the URL:
|
||||
|
||||
```
|
||||
https://www.sim.ai/workspace/{workspaceId}/w/{workflowId}
|
||||
```
|
||||
|
||||
You can also use the [List Workflows](/api-reference/workflows/listWorkflows) endpoint to get all workflow IDs in a workspace.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Deploy your workflow
|
||||
|
||||
A workflow must be deployed before it can be executed via the API. Click the **Deploy** button in the editor toolbar, or use the dashboard to manage deployments.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Make your first request
|
||||
|
||||
<Tabs items={['curl', 'TypeScript', 'Python']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch(
|
||||
`https://www.sim.ai/api/workflows/${workflowId}/execute`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': process.env.SIM_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify({ inputs: {} }),
|
||||
}
|
||||
)
|
||||
|
||||
const data = await response.json()
|
||||
console.log(data.output)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
```python
|
||||
import requests
|
||||
import os
|
||||
|
||||
response = requests.post(
|
||||
f"https://www.sim.ai/api/workflows/{workflow_id}/execute",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": os.environ["SIM_API_KEY"],
|
||||
},
|
||||
json={"inputs": {}},
|
||||
)
|
||||
|
||||
data = response.json()
|
||||
print(data["output"])
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## Sync vs Async Execution
|
||||
|
||||
By default, workflow executions are **synchronous** — the API blocks until the workflow completes and returns the result directly.
|
||||
|
||||
For long-running workflows, use **asynchronous execution** by passing `async: true`:
|
||||
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}, "async": true}'
|
||||
```
|
||||
|
||||
This returns immediately with a `taskId`:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"taskId": "job_abc123",
|
||||
"status": "queued"
|
||||
}
|
||||
```
|
||||
|
||||
Poll the [Get Job Status](/api-reference/workflows/getJobStatus) endpoint until the status is `completed` or `failed`:
|
||||
|
||||
```bash
|
||||
curl https://www.sim.ai/api/jobs/{taskId} \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
```
|
||||
|
||||
<Callout type="info">
|
||||
Job status transitions follow: `queued` → `processing` → `completed` or `failed`. The `output` field is only present when status is `completed`.
|
||||
</Callout>
|
||||
|
||||
## Response Format
|
||||
|
||||
Successful responses include an `output` object with your workflow results and a `limits` object with your current rate limit and usage status:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"output": {
|
||||
"result": "Hello, world!"
|
||||
},
|
||||
"limits": {
|
||||
"workflowExecutionRateLimit": {
|
||||
"sync": {
|
||||
"requestsPerMinute": 60,
|
||||
"maxBurst": 10,
|
||||
"remaining": 59,
|
||||
"resetAt": "2025-01-01T00:01:00Z"
|
||||
},
|
||||
"async": {
|
||||
"requestsPerMinute": 30,
|
||||
"maxBurst": 5,
|
||||
"remaining": 30,
|
||||
"resetAt": "2025-01-01T00:01:00Z"
|
||||
}
|
||||
},
|
||||
"usage": {
|
||||
"currentPeriodCost": 1.25,
|
||||
"limit": 50.00,
|
||||
"plan": "pro",
|
||||
"isExceeded": false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The API uses standard HTTP status codes. Error responses include a human-readable `error` message:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Workflow not found"
|
||||
}
|
||||
```
|
||||
|
||||
| Status | Meaning | What to do |
|
||||
| --- | --- | --- |
|
||||
| `400` | Invalid request parameters | Check the `details` array for specific field errors |
|
||||
| `401` | Missing or invalid API key | Verify your `X-API-Key` header |
|
||||
| `403` | Access denied | Check you have permission for this resource |
|
||||
| `404` | Resource not found | Verify the ID exists and belongs to your workspace |
|
||||
| `429` | Rate limit exceeded | Wait for the duration in the `Retry-After` header |
|
||||
|
||||
<Callout type="info">
|
||||
Use the [Get Usage Limits](/api-reference/usage/getUsageLimits) endpoint to check your current rate limit status and billing usage at any time.
|
||||
</Callout>
|
||||
|
||||
## Rate Limits
|
||||
|
||||
Rate limits depend on your subscription plan and apply separately to synchronous and asynchronous executions. Every execution response includes a `limits` object showing your current rate limit status.
|
||||
|
||||
When rate limited, the API returns a `429` response with a `Retry-After` header indicating how many seconds to wait before retrying.
|
||||
|
||||
## Pagination
|
||||
|
||||
List endpoints (workflows, logs, audit logs) use **cursor-based pagination**:
|
||||
|
||||
```bash
|
||||
# First page
|
||||
curl "https://www.sim.ai/api/v1/logs?limit=20" \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
|
||||
# Next page — use the nextCursor from the previous response
|
||||
curl "https://www.sim.ai/api/v1/logs?limit=20&cursor=abc123" \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
```
|
||||
|
||||
The response includes a `nextCursor` field. When `nextCursor` is absent or `null`, you have reached the last page.
|
||||
16
apps/docs/content/docs/es/api-reference/meta.json
Normal file
16
apps/docs/content/docs/es/api-reference/meta.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"title": "API Reference",
|
||||
"root": true,
|
||||
"pages": [
|
||||
"getting-started",
|
||||
"authentication",
|
||||
"---SDKs---",
|
||||
"python",
|
||||
"typescript",
|
||||
"---Endpoints---",
|
||||
"(generated)/workflows",
|
||||
"(generated)/logs",
|
||||
"(generated)/usage",
|
||||
"(generated)/audit-logs"
|
||||
]
|
||||
}
|
||||
766
apps/docs/content/docs/es/api-reference/python.mdx
Normal file
766
apps/docs/content/docs/es/api-reference/python.mdx
Normal file
@@ -0,0 +1,766 @@
|
||||
---
|
||||
title: Python
|
||||
---
|
||||
|
||||
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'
|
||||
|
||||
El SDK oficial de Python para Sim te permite ejecutar flujos de trabajo programáticamente desde tus aplicaciones Python utilizando el SDK oficial de Python.
|
||||
|
||||
<Callout type="info">
|
||||
El SDK de Python es compatible con Python 3.8+ con soporte para ejecución asíncrona, limitación automática de velocidad con retroceso exponencial y seguimiento de uso.
|
||||
</Callout>
|
||||
|
||||
## Instalación
|
||||
|
||||
Instala el SDK usando pip:
|
||||
|
||||
```bash
|
||||
pip install simstudio-sdk
|
||||
```
|
||||
|
||||
## Inicio rápido
|
||||
|
||||
Aquí tienes un ejemplo sencillo para empezar:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Initialize the client
|
||||
client = SimStudioClient(
|
||||
api_key="your-api-key-here",
|
||||
base_url="https://sim.ai" # optional, defaults to https://sim.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)
|
||||
```
|
||||
|
||||
## Referencia de la API
|
||||
|
||||
### SimStudioClient
|
||||
|
||||
#### Constructor
|
||||
|
||||
```python
|
||||
SimStudioClient(api_key: str, base_url: str = "https://sim.ai")
|
||||
```
|
||||
|
||||
**Parámetros:**
|
||||
- `api_key` (str): Tu clave API de Sim
|
||||
- `base_url` (str, opcional): URL base para la API de Sim
|
||||
|
||||
#### Métodos
|
||||
|
||||
##### execute_workflow()
|
||||
|
||||
Ejecuta un flujo de trabajo con datos de entrada opcionales.
|
||||
|
||||
```python
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"message": "Hello, world!"},
|
||||
timeout=30.0 # 30 seconds
|
||||
)
|
||||
```
|
||||
|
||||
**Parámetros:**
|
||||
- `workflow_id` (str): El ID del flujo de trabajo a ejecutar
|
||||
- `input_data` (dict, opcional): Datos de entrada para pasar al flujo de trabajo
|
||||
- `timeout` (float, opcional): Tiempo de espera en segundos (predeterminado: 30.0)
|
||||
- `stream` (bool, opcional): Habilitar respuestas en streaming (predeterminado: False)
|
||||
- `selected_outputs` (list[str], opcional): Salidas de bloque para transmitir en formato `blockName.attribute` (p. ej., `["agent1.content"]`)
|
||||
- `async_execution` (bool, opcional): Ejecutar de forma asíncrona (predeterminado: False)
|
||||
|
||||
**Devuelve:** `WorkflowExecutionResult | AsyncExecutionResult`
|
||||
|
||||
Cuando `async_execution=True`, devuelve inmediatamente un ID de tarea para sondeo. De lo contrario, espera a que se complete.
|
||||
|
||||
##### get_workflow_status()
|
||||
|
||||
Obtener el estado de un flujo de trabajo (estado de implementación, etc.).
|
||||
|
||||
```python
|
||||
status = client.get_workflow_status("workflow-id")
|
||||
print("Is deployed:", status.is_deployed)
|
||||
```
|
||||
|
||||
**Parámetros:**
|
||||
- `workflow_id` (str): El ID del flujo de trabajo
|
||||
|
||||
**Devuelve:** `WorkflowStatus`
|
||||
|
||||
##### validate_workflow()
|
||||
|
||||
Validar que un flujo de trabajo está listo para su ejecución.
|
||||
|
||||
```python
|
||||
is_ready = client.validate_workflow("workflow-id")
|
||||
if is_ready:
|
||||
# Workflow is deployed and ready
|
||||
pass
|
||||
```
|
||||
|
||||
**Parámetros:**
|
||||
- `workflow_id` (str): El ID del flujo de trabajo
|
||||
|
||||
**Devuelve:** `bool`
|
||||
|
||||
##### get_job_status()
|
||||
|
||||
Obtener el estado de una ejecución de trabajo asíncrono.
|
||||
|
||||
```python
|
||||
status = client.get_job_status("task-id-from-async-execution")
|
||||
print("Status:", status["status"]) # 'queued', 'processing', 'completed', 'failed'
|
||||
if status["status"] == "completed":
|
||||
print("Output:", status["output"])
|
||||
```
|
||||
|
||||
**Parámetros:**
|
||||
- `task_id` (str): El ID de tarea devuelto de la ejecución asíncrona
|
||||
|
||||
**Devuelve:** `Dict[str, Any]`
|
||||
|
||||
**Campos de respuesta:**
|
||||
- `success` (bool): Si la solicitud fue exitosa
|
||||
- `taskId` (str): El ID de la tarea
|
||||
- `status` (str): Uno de `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
|
||||
- `metadata` (dict): Contiene `startedAt`, `completedAt`, y `duration`
|
||||
- `output` (any, opcional): La salida del flujo de trabajo (cuando se completa)
|
||||
- `error` (any, opcional): Detalles del error (cuando falla)
|
||||
- `estimatedDuration` (int, opcional): Duración estimada en milisegundos (cuando está procesando/en cola)
|
||||
|
||||
##### execute_with_retry()
|
||||
|
||||
Ejecutar un flujo de trabajo con reintento automático en errores de límite de velocidad usando retroceso exponencial.
|
||||
|
||||
```python
|
||||
result = client.execute_with_retry(
|
||||
"workflow-id",
|
||||
input_data={"message": "Hello"},
|
||||
timeout=30.0,
|
||||
max_retries=3, # Maximum number of retries
|
||||
initial_delay=1.0, # Initial delay in seconds
|
||||
max_delay=30.0, # Maximum delay in seconds
|
||||
backoff_multiplier=2.0 # Exponential backoff multiplier
|
||||
)
|
||||
```
|
||||
|
||||
**Parámetros:**
|
||||
- `workflow_id` (str): El ID del flujo de trabajo a ejecutar
|
||||
- `input_data` (dict, opcional): Datos de entrada para pasar al flujo de trabajo
|
||||
- `timeout` (float, opcional): Tiempo de espera en segundos
|
||||
- `stream` (bool, opcional): Habilitar respuestas en streaming
|
||||
- `selected_outputs` (list, opcional): Salidas de bloque para transmitir
|
||||
- `async_execution` (bool, opcional): Ejecutar de forma asíncrona
|
||||
- `max_retries` (int, opcional): Número máximo de reintentos (predeterminado: 3)
|
||||
- `initial_delay` (float, opcional): Retraso inicial en segundos (predeterminado: 1.0)
|
||||
- `max_delay` (float, opcional): Retraso máximo en segundos (predeterminado: 30.0)
|
||||
- `backoff_multiplier` (float, opcional): Multiplicador de retroceso (predeterminado: 2.0)
|
||||
|
||||
**Devuelve:** `WorkflowExecutionResult | AsyncExecutionResult`
|
||||
|
||||
La lógica de reintento utiliza retroceso exponencial (1s → 2s → 4s → 8s...) con fluctuación de ±25% para evitar el efecto de manada. Si la API proporciona un encabezado `retry-after`, se utilizará en su lugar.
|
||||
|
||||
##### get_rate_limit_info()
|
||||
|
||||
Obtiene la información actual del límite de tasa de la última respuesta de la API.
|
||||
|
||||
```python
|
||||
rate_limit_info = client.get_rate_limit_info()
|
||||
if rate_limit_info:
|
||||
print("Limit:", rate_limit_info.limit)
|
||||
print("Remaining:", rate_limit_info.remaining)
|
||||
print("Reset:", datetime.fromtimestamp(rate_limit_info.reset))
|
||||
```
|
||||
|
||||
**Devuelve:** `RateLimitInfo | None`
|
||||
|
||||
##### get_usage_limits()
|
||||
|
||||
Obtiene los límites de uso actuales y la información de cuota para tu cuenta.
|
||||
|
||||
```python
|
||||
limits = client.get_usage_limits()
|
||||
print("Sync requests remaining:", limits.rate_limit["sync"]["remaining"])
|
||||
print("Async requests remaining:", limits.rate_limit["async"]["remaining"])
|
||||
print("Current period cost:", limits.usage["currentPeriodCost"])
|
||||
print("Plan:", limits.usage["plan"])
|
||||
```
|
||||
|
||||
**Devuelve:** `UsageLimits`
|
||||
|
||||
**Estructura de respuesta:**
|
||||
|
||||
```python
|
||||
{
|
||||
"success": bool,
|
||||
"rateLimit": {
|
||||
"sync": {
|
||||
"isLimited": bool,
|
||||
"limit": int,
|
||||
"remaining": int,
|
||||
"resetAt": str
|
||||
},
|
||||
"async": {
|
||||
"isLimited": bool,
|
||||
"limit": int,
|
||||
"remaining": int,
|
||||
"resetAt": str
|
||||
},
|
||||
"authType": str # 'api' or 'manual'
|
||||
},
|
||||
"usage": {
|
||||
"currentPeriodCost": float,
|
||||
"limit": float,
|
||||
"plan": str # e.g., 'free', 'pro'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### set_api_key()
|
||||
|
||||
Actualiza la clave API.
|
||||
|
||||
```python
|
||||
client.set_api_key("new-api-key")
|
||||
```
|
||||
|
||||
##### set_base_url()
|
||||
|
||||
Actualiza la URL base.
|
||||
|
||||
```python
|
||||
client.set_base_url("https://my-custom-domain.com")
|
||||
```
|
||||
|
||||
##### close()
|
||||
|
||||
Cierra la sesión HTTP subyacente.
|
||||
|
||||
```python
|
||||
client.close()
|
||||
```
|
||||
|
||||
## Clases de datos
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
### AsyncExecutionResult
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class AsyncExecutionResult:
|
||||
success: bool
|
||||
task_id: str
|
||||
status: str # 'queued'
|
||||
created_at: str
|
||||
links: Dict[str, str] # e.g., {"status": "/api/jobs/{taskId}"}
|
||||
```
|
||||
|
||||
### WorkflowStatus
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class WorkflowStatus:
|
||||
is_deployed: bool
|
||||
deployed_at: Optional[str] = None
|
||||
needs_redeployment: bool = False
|
||||
```
|
||||
|
||||
### RateLimitInfo
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class RateLimitInfo:
|
||||
limit: int
|
||||
remaining: int
|
||||
reset: int
|
||||
retry_after: Optional[int] = None
|
||||
```
|
||||
|
||||
### UsageLimits
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class UsageLimits:
|
||||
success: bool
|
||||
rate_limit: Dict[str, Any]
|
||||
usage: Dict[str, Any]
|
||||
```
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
**Códigos de error comunes:**
|
||||
- `UNAUTHORIZED`: Clave API inválida
|
||||
- `TIMEOUT`: Tiempo de espera agotado
|
||||
- `RATE_LIMIT_EXCEEDED`: Límite de tasa excedido
|
||||
- `USAGE_LIMIT_EXCEEDED`: Límite de uso excedido
|
||||
- `EXECUTION_ERROR`: Ejecución del flujo de trabajo fallida
|
||||
|
||||
## Ejemplos
|
||||
|
||||
### Ejecución básica de flujo de trabajo
|
||||
|
||||
<Steps>
|
||||
<Step title="Inicializar el cliente">
|
||||
Configura el SimStudioClient con tu clave API.
|
||||
</Step>
|
||||
<Step title="Validar el flujo de trabajo">
|
||||
Comprueba si el flujo de trabajo está desplegado y listo para su ejecución.
|
||||
</Step>
|
||||
<Step title="Ejecutar el flujo de trabajo">
|
||||
Ejecuta el flujo de trabajo con tus datos de entrada.
|
||||
</Step>
|
||||
<Step title="Manejar el resultado">
|
||||
Procesa el resultado de la ejecución y gestiona cualquier error.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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()
|
||||
```
|
||||
|
||||
### Manejo de errores
|
||||
|
||||
Maneja diferentes tipos de errores que pueden ocurrir durante la ejecución del flujo de trabajo:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient, SimStudioError
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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
|
||||
```
|
||||
|
||||
### Uso del gestor de contexto
|
||||
|
||||
Usa el cliente como un gestor de contexto para manejar automáticamente la limpieza de recursos:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
# Using context manager to automatically close the session
|
||||
with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client:
|
||||
result = client.execute_workflow("workflow-id")
|
||||
print("Result:", result)
|
||||
# Session is automatically closed here
|
||||
```
|
||||
|
||||
### Ejecución de flujos de trabajo por lotes
|
||||
|
||||
Ejecuta múltiples flujos de trabajo de manera eficiente:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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'}")
|
||||
```
|
||||
|
||||
### Ejecución asíncrona de flujos de trabajo
|
||||
|
||||
Ejecuta flujos de trabajo de forma asíncrona para tareas de larga duración:
|
||||
|
||||
```python
|
||||
import os
|
||||
import time
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_async():
|
||||
try:
|
||||
# Start async execution
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"data": "large dataset"},
|
||||
async_execution=True # Execute asynchronously
|
||||
)
|
||||
|
||||
# Check if result is an async execution
|
||||
if hasattr(result, 'task_id'):
|
||||
print(f"Task ID: {result.task_id}")
|
||||
print(f"Status endpoint: {result.links['status']}")
|
||||
|
||||
# Poll for completion
|
||||
status = client.get_job_status(result.task_id)
|
||||
|
||||
while status["status"] in ["queued", "processing"]:
|
||||
print(f"Current status: {status['status']}")
|
||||
time.sleep(2) # Wait 2 seconds
|
||||
status = client.get_job_status(result.task_id)
|
||||
|
||||
if status["status"] == "completed":
|
||||
print("Workflow completed!")
|
||||
print(f"Output: {status['output']}")
|
||||
print(f"Duration: {status['metadata']['duration']}")
|
||||
else:
|
||||
print(f"Workflow failed: {status['error']}")
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error: {error}")
|
||||
|
||||
execute_async()
|
||||
```
|
||||
|
||||
### Límite de tasa y reintentos
|
||||
|
||||
Maneja los límites de tasa automáticamente con retroceso exponencial:
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient, SimStudioError
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_with_retry_handling():
|
||||
try:
|
||||
# Automatically retries on rate limit
|
||||
result = client.execute_with_retry(
|
||||
"workflow-id",
|
||||
input_data={"message": "Process this"},
|
||||
max_retries=5,
|
||||
initial_delay=1.0,
|
||||
max_delay=60.0,
|
||||
backoff_multiplier=2.0
|
||||
)
|
||||
|
||||
print(f"Success: {result}")
|
||||
except SimStudioError as error:
|
||||
if error.code == "RATE_LIMIT_EXCEEDED":
|
||||
print("Rate limit exceeded after all retries")
|
||||
|
||||
# Check rate limit info
|
||||
rate_limit_info = client.get_rate_limit_info()
|
||||
if rate_limit_info:
|
||||
from datetime import datetime
|
||||
reset_time = datetime.fromtimestamp(rate_limit_info.reset)
|
||||
print(f"Rate limit resets at: {reset_time}")
|
||||
|
||||
execute_with_retry_handling()
|
||||
```
|
||||
|
||||
### Monitoreo de uso
|
||||
|
||||
Monitorea el uso de tu cuenta y sus límites:
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def check_usage():
|
||||
try:
|
||||
limits = client.get_usage_limits()
|
||||
|
||||
print("=== Rate Limits ===")
|
||||
print("Sync requests:")
|
||||
print(f" Limit: {limits.rate_limit['sync']['limit']}")
|
||||
print(f" Remaining: {limits.rate_limit['sync']['remaining']}")
|
||||
print(f" Resets at: {limits.rate_limit['sync']['resetAt']}")
|
||||
print(f" Is limited: {limits.rate_limit['sync']['isLimited']}")
|
||||
|
||||
print("\nAsync requests:")
|
||||
print(f" Limit: {limits.rate_limit['async']['limit']}")
|
||||
print(f" Remaining: {limits.rate_limit['async']['remaining']}")
|
||||
print(f" Resets at: {limits.rate_limit['async']['resetAt']}")
|
||||
print(f" Is limited: {limits.rate_limit['async']['isLimited']}")
|
||||
|
||||
print("\n=== Usage ===")
|
||||
print(f"Current period cost: ${limits.usage['currentPeriodCost']:.2f}")
|
||||
print(f"Limit: ${limits.usage['limit']:.2f}")
|
||||
print(f"Plan: {limits.usage['plan']}")
|
||||
|
||||
percent_used = (limits.usage['currentPeriodCost'] / limits.usage['limit']) * 100
|
||||
print(f"Usage: {percent_used:.1f}%")
|
||||
|
||||
if percent_used > 80:
|
||||
print("⚠️ Warning: You are approaching your usage limit!")
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error checking usage: {error}")
|
||||
|
||||
check_usage()
|
||||
```
|
||||
|
||||
### Ejecución de flujo de trabajo en streaming
|
||||
|
||||
Ejecuta flujos de trabajo con respuestas en tiempo real:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_with_streaming():
|
||||
"""Execute workflow with streaming enabled."""
|
||||
try:
|
||||
# Enable streaming for specific block outputs
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"message": "Count to five"},
|
||||
stream=True,
|
||||
selected_outputs=["agent1.content"] # Use blockName.attribute format
|
||||
)
|
||||
|
||||
print("Workflow result:", result)
|
||||
except Exception as error:
|
||||
print("Error:", error)
|
||||
|
||||
execute_with_streaming()
|
||||
```
|
||||
|
||||
La respuesta en streaming sigue el formato de Server-Sent Events (SSE):
|
||||
|
||||
```
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
|
||||
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"}
|
||||
|
||||
data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
|
||||
|
||||
data: [DONE]
|
||||
```
|
||||
|
||||
**Ejemplo de streaming con Flask:**
|
||||
|
||||
```python
|
||||
from flask import Flask, Response, stream_with_context
|
||||
import requests
|
||||
import json
|
||||
import os
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route('/stream-workflow')
|
||||
def stream_workflow():
|
||||
"""Stream workflow execution to the client."""
|
||||
|
||||
def generate():
|
||||
response = requests.post(
|
||||
'https://sim.ai/api/workflows/WORKFLOW_ID/execute',
|
||||
headers={
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': os.getenv('SIM_API_KEY')
|
||||
},
|
||||
json={
|
||||
'message': 'Generate a story',
|
||||
'stream': True,
|
||||
'selectedOutputs': ['agent1.content']
|
||||
},
|
||||
stream=True
|
||||
)
|
||||
|
||||
for line in response.iter_lines():
|
||||
if line:
|
||||
decoded_line = line.decode('utf-8')
|
||||
if decoded_line.startswith('data: '):
|
||||
data = decoded_line[6:] # Remove 'data: ' prefix
|
||||
|
||||
if data == '[DONE]':
|
||||
break
|
||||
|
||||
try:
|
||||
parsed = json.loads(data)
|
||||
if 'chunk' in parsed:
|
||||
yield f"data: {json.dumps(parsed)}\n\n"
|
||||
elif parsed.get('event') == 'done':
|
||||
yield f"data: {json.dumps(parsed)}\n\n"
|
||||
print("Execution complete:", parsed.get('metadata'))
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
return Response(
|
||||
stream_with_context(generate()),
|
||||
mimetype='text/event-stream'
|
||||
)
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
```
|
||||
|
||||
### Configuración del entorno
|
||||
|
||||
Configura el cliente usando variables de entorno:
|
||||
|
||||
<Tabs items={['Development', 'Production']}>
|
||||
<Tab value="Development">
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Development configuration
|
||||
client = SimStudioClient(
|
||||
api_key=os.getenv("SIM_API_KEY")
|
||||
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
|
||||
)
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value="Production">
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Production configuration with error handling
|
||||
api_key = os.getenv("SIM_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("SIM_API_KEY environment variable is required")
|
||||
|
||||
client = SimStudioClient(
|
||||
api_key=api_key,
|
||||
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
|
||||
)
|
||||
```
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Obtener tu clave API
|
||||
|
||||
<Steps>
|
||||
<Step title="Inicia sesión en Sim">
|
||||
Navega a [Sim](https://sim.ai) e inicia sesión en tu cuenta.
|
||||
</Step>
|
||||
<Step title="Abre tu flujo de trabajo">
|
||||
Navega al flujo de trabajo que quieres ejecutar programáticamente.
|
||||
</Step>
|
||||
<Step title="Despliega tu flujo de trabajo">
|
||||
Haz clic en "Deploy" para desplegar tu flujo de trabajo si aún no ha sido desplegado.
|
||||
</Step>
|
||||
<Step title="Crea o selecciona una clave API">
|
||||
Durante el proceso de despliegue, selecciona o crea una clave API.
|
||||
</Step>
|
||||
<Step title="Copia la clave API">
|
||||
Copia la clave API para usarla en tu aplicación Python.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Requisitos
|
||||
|
||||
- Python 3.8+
|
||||
- requests >= 2.25.0
|
||||
|
||||
## Licencia
|
||||
|
||||
Apache-2.0
|
||||
1052
apps/docs/content/docs/es/api-reference/typescript.mdx
Normal file
1052
apps/docs/content/docs/es/api-reference/typescript.mdx
Normal file
File diff suppressed because it is too large
Load Diff
24
apps/docs/content/docs/es/meta.json
Normal file
24
apps/docs/content/docs/es/meta.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"title": "Sim Documentation",
|
||||
"pages": [
|
||||
"./introduction/index",
|
||||
"./getting-started/index",
|
||||
"./quick-reference/index",
|
||||
"triggers",
|
||||
"blocks",
|
||||
"tools",
|
||||
"connections",
|
||||
"mcp",
|
||||
"copilot",
|
||||
"skills",
|
||||
"knowledgebase",
|
||||
"variables",
|
||||
"credentials",
|
||||
"execution",
|
||||
"permissions",
|
||||
"self-hosting",
|
||||
"./enterprise/index",
|
||||
"./keyboard-shortcuts/index"
|
||||
],
|
||||
"defaultOpen": false
|
||||
}
|
||||
94
apps/docs/content/docs/fr/api-reference/authentication.mdx
Normal file
94
apps/docs/content/docs/fr/api-reference/authentication.mdx
Normal file
@@ -0,0 +1,94 @@
|
||||
---
|
||||
title: Authentication
|
||||
description: API key types, generation, and how to authenticate requests
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
|
||||
To access the Sim API, you need an API key. Sim supports two types of API keys — **personal keys** and **workspace keys** — each with different billing and access behaviors.
|
||||
|
||||
## Key Types
|
||||
|
||||
| | **Personal Keys** | **Workspace Keys** |
|
||||
| --- | --- | --- |
|
||||
| **Billed to** | Your individual account | Workspace owner |
|
||||
| **Scope** | Across workspaces you have access to | Shared across the workspace |
|
||||
| **Managed by** | Each user individually | Workspace admins |
|
||||
| **Permissions** | Must be enabled at workspace level | Require admin permissions |
|
||||
|
||||
<Callout type="info">
|
||||
Workspace admins can disable personal API key usage for their workspace. If disabled, only workspace keys can be used.
|
||||
</Callout>
|
||||
|
||||
## Generating API Keys
|
||||
|
||||
To generate a key, open the Sim dashboard and navigate to **Settings**, then go to **Sim Keys** and click **Create**.
|
||||
|
||||
<Callout type="warn">
|
||||
API keys are only shown once when generated. Store your key securely — you will not be able to view it again.
|
||||
</Callout>
|
||||
|
||||
## Using API Keys
|
||||
|
||||
Pass your API key in the `X-API-Key` header with every request:
|
||||
|
||||
<Tabs items={['curl', 'TypeScript', 'Python']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch(
|
||||
'https://www.sim.ai/api/workflows/{workflowId}/execute',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': process.env.SIM_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify({ inputs: {} }),
|
||||
}
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
```python
|
||||
import requests
|
||||
|
||||
response = requests.post(
|
||||
"https://www.sim.ai/api/workflows/{workflowId}/execute",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": os.environ["SIM_API_KEY"],
|
||||
},
|
||||
json={"inputs": {}},
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Where Keys Are Used
|
||||
|
||||
API keys authenticate access to:
|
||||
|
||||
- **Workflow execution** — run deployed workflows via the API
|
||||
- **Logs API** — query workflow execution logs and metrics
|
||||
- **MCP servers** — authenticate connections to deployed MCP servers
|
||||
- **SDKs** — the [Python](/api-reference/python) and [TypeScript](/api-reference/typescript) SDKs use API keys for all operations
|
||||
|
||||
## Security
|
||||
|
||||
- Keys use the `sk-sim-` prefix and are encrypted at rest
|
||||
- Keys can be revoked at any time from the dashboard
|
||||
- Use environment variables to store keys — never hardcode them in source code
|
||||
- For browser-based applications, use a backend proxy to avoid exposing keys to the client
|
||||
|
||||
<Callout type="warn">
|
||||
Never expose your API key in client-side code. Use a server-side proxy to make authenticated requests on behalf of your frontend.
|
||||
</Callout>
|
||||
210
apps/docs/content/docs/fr/api-reference/getting-started.mdx
Normal file
210
apps/docs/content/docs/fr/api-reference/getting-started.mdx
Normal file
@@ -0,0 +1,210 @@
|
||||
---
|
||||
title: Getting Started
|
||||
description: Base URL, first API call, response format, error handling, and pagination
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
|
||||
## Base URL
|
||||
|
||||
All API requests are made to:
|
||||
|
||||
```
|
||||
https://www.sim.ai
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step>
|
||||
### Get your API key
|
||||
|
||||
Go to the Sim platform and navigate to **Settings**, then go to **Sim Keys** and click **Create**. See [Authentication](/api-reference/authentication) for details on key types.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Find your workflow ID
|
||||
|
||||
Open a workflow in the Sim editor. The workflow ID is in the URL:
|
||||
|
||||
```
|
||||
https://www.sim.ai/workspace/{workspaceId}/w/{workflowId}
|
||||
```
|
||||
|
||||
You can also use the [List Workflows](/api-reference/workflows/listWorkflows) endpoint to get all workflow IDs in a workspace.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Deploy your workflow
|
||||
|
||||
A workflow must be deployed before it can be executed via the API. Click the **Deploy** button in the editor toolbar, or use the dashboard to manage deployments.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Make your first request
|
||||
|
||||
<Tabs items={['curl', 'TypeScript', 'Python']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch(
|
||||
`https://www.sim.ai/api/workflows/${workflowId}/execute`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': process.env.SIM_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify({ inputs: {} }),
|
||||
}
|
||||
)
|
||||
|
||||
const data = await response.json()
|
||||
console.log(data.output)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
```python
|
||||
import requests
|
||||
import os
|
||||
|
||||
response = requests.post(
|
||||
f"https://www.sim.ai/api/workflows/{workflow_id}/execute",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": os.environ["SIM_API_KEY"],
|
||||
},
|
||||
json={"inputs": {}},
|
||||
)
|
||||
|
||||
data = response.json()
|
||||
print(data["output"])
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## Sync vs Async Execution
|
||||
|
||||
By default, workflow executions are **synchronous** — the API blocks until the workflow completes and returns the result directly.
|
||||
|
||||
For long-running workflows, use **asynchronous execution** by passing `async: true`:
|
||||
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}, "async": true}'
|
||||
```
|
||||
|
||||
This returns immediately with a `taskId`:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"taskId": "job_abc123",
|
||||
"status": "queued"
|
||||
}
|
||||
```
|
||||
|
||||
Poll the [Get Job Status](/api-reference/workflows/getJobStatus) endpoint until the status is `completed` or `failed`:
|
||||
|
||||
```bash
|
||||
curl https://www.sim.ai/api/jobs/{taskId} \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
```
|
||||
|
||||
<Callout type="info">
|
||||
Job status transitions follow: `queued` → `processing` → `completed` or `failed`. The `output` field is only present when status is `completed`.
|
||||
</Callout>
|
||||
|
||||
## Response Format
|
||||
|
||||
Successful responses include an `output` object with your workflow results and a `limits` object with your current rate limit and usage status:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"output": {
|
||||
"result": "Hello, world!"
|
||||
},
|
||||
"limits": {
|
||||
"workflowExecutionRateLimit": {
|
||||
"sync": {
|
||||
"requestsPerMinute": 60,
|
||||
"maxBurst": 10,
|
||||
"remaining": 59,
|
||||
"resetAt": "2025-01-01T00:01:00Z"
|
||||
},
|
||||
"async": {
|
||||
"requestsPerMinute": 30,
|
||||
"maxBurst": 5,
|
||||
"remaining": 30,
|
||||
"resetAt": "2025-01-01T00:01:00Z"
|
||||
}
|
||||
},
|
||||
"usage": {
|
||||
"currentPeriodCost": 1.25,
|
||||
"limit": 50.00,
|
||||
"plan": "pro",
|
||||
"isExceeded": false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The API uses standard HTTP status codes. Error responses include a human-readable `error` message:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Workflow not found"
|
||||
}
|
||||
```
|
||||
|
||||
| Status | Meaning | What to do |
|
||||
| --- | --- | --- |
|
||||
| `400` | Invalid request parameters | Check the `details` array for specific field errors |
|
||||
| `401` | Missing or invalid API key | Verify your `X-API-Key` header |
|
||||
| `403` | Access denied | Check you have permission for this resource |
|
||||
| `404` | Resource not found | Verify the ID exists and belongs to your workspace |
|
||||
| `429` | Rate limit exceeded | Wait for the duration in the `Retry-After` header |
|
||||
|
||||
<Callout type="info">
|
||||
Use the [Get Usage Limits](/api-reference/usage/getUsageLimits) endpoint to check your current rate limit status and billing usage at any time.
|
||||
</Callout>
|
||||
|
||||
## Rate Limits
|
||||
|
||||
Rate limits depend on your subscription plan and apply separately to synchronous and asynchronous executions. Every execution response includes a `limits` object showing your current rate limit status.
|
||||
|
||||
When rate limited, the API returns a `429` response with a `Retry-After` header indicating how many seconds to wait before retrying.
|
||||
|
||||
## Pagination
|
||||
|
||||
List endpoints (workflows, logs, audit logs) use **cursor-based pagination**:
|
||||
|
||||
```bash
|
||||
# First page
|
||||
curl "https://www.sim.ai/api/v1/logs?limit=20" \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
|
||||
# Next page — use the nextCursor from the previous response
|
||||
curl "https://www.sim.ai/api/v1/logs?limit=20&cursor=abc123" \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
```
|
||||
|
||||
The response includes a `nextCursor` field. When `nextCursor` is absent or `null`, you have reached the last page.
|
||||
16
apps/docs/content/docs/fr/api-reference/meta.json
Normal file
16
apps/docs/content/docs/fr/api-reference/meta.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"title": "API Reference",
|
||||
"root": true,
|
||||
"pages": [
|
||||
"getting-started",
|
||||
"authentication",
|
||||
"---SDKs---",
|
||||
"python",
|
||||
"typescript",
|
||||
"---Endpoints---",
|
||||
"(generated)/workflows",
|
||||
"(generated)/logs",
|
||||
"(generated)/usage",
|
||||
"(generated)/audit-logs"
|
||||
]
|
||||
}
|
||||
766
apps/docs/content/docs/fr/api-reference/python.mdx
Normal file
766
apps/docs/content/docs/fr/api-reference/python.mdx
Normal file
@@ -0,0 +1,766 @@
|
||||
---
|
||||
title: Python
|
||||
---
|
||||
|
||||
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'
|
||||
|
||||
Le SDK Python officiel pour Sim vous permet d'exécuter des workflows de manière programmatique à partir de vos applications Python en utilisant le SDK Python officiel.
|
||||
|
||||
<Callout type="info">
|
||||
Le SDK Python prend en charge Python 3.8+ avec support d'exécution asynchrone, limitation automatique du débit avec backoff exponentiel, et suivi d'utilisation.
|
||||
</Callout>
|
||||
|
||||
## Installation
|
||||
|
||||
Installez le SDK en utilisant pip :
|
||||
|
||||
```bash
|
||||
pip install simstudio-sdk
|
||||
```
|
||||
|
||||
## Démarrage rapide
|
||||
|
||||
Voici un exemple simple pour commencer :
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Initialize the client
|
||||
client = SimStudioClient(
|
||||
api_key="your-api-key-here",
|
||||
base_url="https://sim.ai" # optional, defaults to https://sim.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)
|
||||
```
|
||||
|
||||
## Référence de l'API
|
||||
|
||||
### SimStudioClient
|
||||
|
||||
#### Constructeur
|
||||
|
||||
```python
|
||||
SimStudioClient(api_key: str, base_url: str = "https://sim.ai")
|
||||
```
|
||||
|
||||
**Paramètres :**
|
||||
- `api_key` (str) : Votre clé API Sim
|
||||
- `base_url` (str, facultatif) : URL de base pour l'API Sim
|
||||
|
||||
#### Méthodes
|
||||
|
||||
##### execute_workflow()
|
||||
|
||||
Exécuter un workflow avec des données d'entrée facultatives.
|
||||
|
||||
```python
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"message": "Hello, world!"},
|
||||
timeout=30.0 # 30 seconds
|
||||
)
|
||||
```
|
||||
|
||||
**Paramètres :**
|
||||
- `workflow_id` (str) : L'identifiant du workflow à exécuter
|
||||
- `input_data` (dict, facultatif) : Données d'entrée à transmettre au workflow
|
||||
- `timeout` (float, facultatif) : Délai d'expiration en secondes (par défaut : 30.0)
|
||||
- `stream` (bool, facultatif) : Activer les réponses en streaming (par défaut : False)
|
||||
- `selected_outputs` (list[str], facultatif) : Sorties de blocs à diffuser au format `blockName.attribute` (par exemple, `["agent1.content"]`)
|
||||
- `async_execution` (bool, facultatif) : Exécuter de manière asynchrone (par défaut : False)
|
||||
|
||||
**Retourne :** `WorkflowExecutionResult | AsyncExecutionResult`
|
||||
|
||||
Lorsque `async_execution=True`, retourne immédiatement un identifiant de tâche pour l'interrogation. Sinon, attend la fin de l'exécution.
|
||||
|
||||
##### get_workflow_status()
|
||||
|
||||
Obtenir le statut d'un workflow (statut de déploiement, etc.).
|
||||
|
||||
```python
|
||||
status = client.get_workflow_status("workflow-id")
|
||||
print("Is deployed:", status.is_deployed)
|
||||
```
|
||||
|
||||
**Paramètres :**
|
||||
- `workflow_id` (str) : L'identifiant du workflow
|
||||
|
||||
**Retourne :** `WorkflowStatus`
|
||||
|
||||
##### validate_workflow()
|
||||
|
||||
Valider qu'un workflow est prêt pour l'exécution.
|
||||
|
||||
```python
|
||||
is_ready = client.validate_workflow("workflow-id")
|
||||
if is_ready:
|
||||
# Workflow is deployed and ready
|
||||
pass
|
||||
```
|
||||
|
||||
**Paramètres :**
|
||||
- `workflow_id` (str) : L'identifiant du workflow
|
||||
|
||||
**Retourne :** `bool`
|
||||
|
||||
##### get_job_status()
|
||||
|
||||
Obtenir le statut d'une exécution de tâche asynchrone.
|
||||
|
||||
```python
|
||||
status = client.get_job_status("task-id-from-async-execution")
|
||||
print("Status:", status["status"]) # 'queued', 'processing', 'completed', 'failed'
|
||||
if status["status"] == "completed":
|
||||
print("Output:", status["output"])
|
||||
```
|
||||
|
||||
**Paramètres :**
|
||||
- `task_id` (str) : L'identifiant de tâche retourné par l'exécution asynchrone
|
||||
|
||||
**Retourne :** `Dict[str, Any]`
|
||||
|
||||
**Champs de réponse :**
|
||||
- `success` (bool) : Si la requête a réussi
|
||||
- `taskId` (str) : L'identifiant de la tâche
|
||||
- `status` (str) : L'un des états suivants : `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
|
||||
- `metadata` (dict) : Contient `startedAt`, `completedAt`, et `duration`
|
||||
- `output` (any, facultatif) : La sortie du workflow (une fois terminé)
|
||||
- `error` (any, facultatif) : Détails de l'erreur (en cas d'échec)
|
||||
- `estimatedDuration` (int, facultatif) : Durée estimée en millisecondes (lors du traitement/mise en file d'attente)
|
||||
|
||||
##### execute_with_retry()
|
||||
|
||||
Exécuter un workflow avec réessai automatique en cas d'erreurs de limitation de débit, en utilisant un backoff exponentiel.
|
||||
|
||||
```python
|
||||
result = client.execute_with_retry(
|
||||
"workflow-id",
|
||||
input_data={"message": "Hello"},
|
||||
timeout=30.0,
|
||||
max_retries=3, # Maximum number of retries
|
||||
initial_delay=1.0, # Initial delay in seconds
|
||||
max_delay=30.0, # Maximum delay in seconds
|
||||
backoff_multiplier=2.0 # Exponential backoff multiplier
|
||||
)
|
||||
```
|
||||
|
||||
**Paramètres :**
|
||||
- `workflow_id` (str) : L'identifiant du workflow à exécuter
|
||||
- `input_data` (dict, facultatif) : Données d'entrée à transmettre au workflow
|
||||
- `timeout` (float, facultatif) : Délai d'expiration en secondes
|
||||
- `stream` (bool, facultatif) : Activer les réponses en streaming
|
||||
- `selected_outputs` (list, facultatif) : Sorties de blocs à diffuser
|
||||
- `async_execution` (bool, facultatif) : Exécuter de manière asynchrone
|
||||
- `max_retries` (int, facultatif) : Nombre maximum de tentatives (par défaut : 3)
|
||||
- `initial_delay` (float, facultatif) : Délai initial en secondes (par défaut : 1.0)
|
||||
- `max_delay` (float, facultatif) : Délai maximum en secondes (par défaut : 30.0)
|
||||
- `backoff_multiplier` (float, facultatif) : Multiplicateur de backoff (par défaut : 2.0)
|
||||
|
||||
**Retourne :** `WorkflowExecutionResult | AsyncExecutionResult`
|
||||
|
||||
La logique de nouvelle tentative utilise un backoff exponentiel (1s → 2s → 4s → 8s...) avec une variation aléatoire de ±25% pour éviter l'effet de horde. Si l'API fournit un en-tête `retry-after`, celui-ci sera utilisé à la place.
|
||||
|
||||
##### get_rate_limit_info()
|
||||
|
||||
Obtenir les informations actuelles sur les limites de débit à partir de la dernière réponse de l'API.
|
||||
|
||||
```python
|
||||
rate_limit_info = client.get_rate_limit_info()
|
||||
if rate_limit_info:
|
||||
print("Limit:", rate_limit_info.limit)
|
||||
print("Remaining:", rate_limit_info.remaining)
|
||||
print("Reset:", datetime.fromtimestamp(rate_limit_info.reset))
|
||||
```
|
||||
|
||||
**Retourne :** `RateLimitInfo | None`
|
||||
|
||||
##### get_usage_limits()
|
||||
|
||||
Obtenir les limites d'utilisation actuelles et les informations de quota pour votre compte.
|
||||
|
||||
```python
|
||||
limits = client.get_usage_limits()
|
||||
print("Sync requests remaining:", limits.rate_limit["sync"]["remaining"])
|
||||
print("Async requests remaining:", limits.rate_limit["async"]["remaining"])
|
||||
print("Current period cost:", limits.usage["currentPeriodCost"])
|
||||
print("Plan:", limits.usage["plan"])
|
||||
```
|
||||
|
||||
**Retourne :** `UsageLimits`
|
||||
|
||||
**Structure de la réponse :**
|
||||
|
||||
```python
|
||||
{
|
||||
"success": bool,
|
||||
"rateLimit": {
|
||||
"sync": {
|
||||
"isLimited": bool,
|
||||
"limit": int,
|
||||
"remaining": int,
|
||||
"resetAt": str
|
||||
},
|
||||
"async": {
|
||||
"isLimited": bool,
|
||||
"limit": int,
|
||||
"remaining": int,
|
||||
"resetAt": str
|
||||
},
|
||||
"authType": str # 'api' or 'manual'
|
||||
},
|
||||
"usage": {
|
||||
"currentPeriodCost": float,
|
||||
"limit": float,
|
||||
"plan": str # e.g., 'free', 'pro'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### set_api_key()
|
||||
|
||||
Mettre à jour la clé API.
|
||||
|
||||
```python
|
||||
client.set_api_key("new-api-key")
|
||||
```
|
||||
|
||||
##### set_base_url()
|
||||
|
||||
Mettre à jour l'URL de base.
|
||||
|
||||
```python
|
||||
client.set_base_url("https://my-custom-domain.com")
|
||||
```
|
||||
|
||||
##### close()
|
||||
|
||||
Fermer la session HTTP sous-jacente.
|
||||
|
||||
```python
|
||||
client.close()
|
||||
```
|
||||
|
||||
## Classes de données
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
### AsyncExecutionResult
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class AsyncExecutionResult:
|
||||
success: bool
|
||||
task_id: str
|
||||
status: str # 'queued'
|
||||
created_at: str
|
||||
links: Dict[str, str] # e.g., {"status": "/api/jobs/{taskId}"}
|
||||
```
|
||||
|
||||
### WorkflowStatus
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class WorkflowStatus:
|
||||
is_deployed: bool
|
||||
deployed_at: Optional[str] = None
|
||||
needs_redeployment: bool = False
|
||||
```
|
||||
|
||||
### RateLimitInfo
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class RateLimitInfo:
|
||||
limit: int
|
||||
remaining: int
|
||||
reset: int
|
||||
retry_after: Optional[int] = None
|
||||
```
|
||||
|
||||
### UsageLimits
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class UsageLimits:
|
||||
success: bool
|
||||
rate_limit: Dict[str, Any]
|
||||
usage: Dict[str, Any]
|
||||
```
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
**Codes d'erreur courants :**
|
||||
- `UNAUTHORIZED` : Clé API invalide
|
||||
- `TIMEOUT` : Délai d'attente de la requête dépassé
|
||||
- `RATE_LIMIT_EXCEEDED` : Limite de débit dépassée
|
||||
- `USAGE_LIMIT_EXCEEDED` : Limite d'utilisation dépassée
|
||||
- `EXECUTION_ERROR` : Échec de l'exécution du workflow
|
||||
|
||||
## Exemples
|
||||
|
||||
### Exécution basique d'un workflow
|
||||
|
||||
<Steps>
|
||||
<Step title="Initialiser le client">
|
||||
Configurez le SimStudioClient avec votre clé API.
|
||||
</Step>
|
||||
<Step title="Valider le workflow">
|
||||
Vérifiez si le workflow est déployé et prêt pour l'exécution.
|
||||
</Step>
|
||||
<Step title="Exécuter le workflow">
|
||||
Lancez le workflow avec vos données d'entrée.
|
||||
</Step>
|
||||
<Step title="Gérer le résultat">
|
||||
Traitez le résultat de l'exécution et gérez les éventuelles erreurs.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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()
|
||||
```
|
||||
|
||||
### Gestion des erreurs
|
||||
|
||||
Gérez différents types d'erreurs qui peuvent survenir pendant l'exécution du workflow :
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient, SimStudioError
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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
|
||||
```
|
||||
|
||||
### Utilisation du gestionnaire de contexte
|
||||
|
||||
Utilisez le client comme gestionnaire de contexte pour gérer automatiquement le nettoyage des ressources :
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
# Using context manager to automatically close the session
|
||||
with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client:
|
||||
result = client.execute_workflow("workflow-id")
|
||||
print("Result:", result)
|
||||
# Session is automatically closed here
|
||||
```
|
||||
|
||||
### Exécution de workflows par lots
|
||||
|
||||
Exécutez plusieurs workflows efficacement :
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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'}")
|
||||
```
|
||||
|
||||
### Exécution asynchrone de workflow
|
||||
|
||||
Exécutez des workflows de manière asynchrone pour les tâches de longue durée :
|
||||
|
||||
```python
|
||||
import os
|
||||
import time
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_async():
|
||||
try:
|
||||
# Start async execution
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"data": "large dataset"},
|
||||
async_execution=True # Execute asynchronously
|
||||
)
|
||||
|
||||
# Check if result is an async execution
|
||||
if hasattr(result, 'task_id'):
|
||||
print(f"Task ID: {result.task_id}")
|
||||
print(f"Status endpoint: {result.links['status']}")
|
||||
|
||||
# Poll for completion
|
||||
status = client.get_job_status(result.task_id)
|
||||
|
||||
while status["status"] in ["queued", "processing"]:
|
||||
print(f"Current status: {status['status']}")
|
||||
time.sleep(2) # Wait 2 seconds
|
||||
status = client.get_job_status(result.task_id)
|
||||
|
||||
if status["status"] == "completed":
|
||||
print("Workflow completed!")
|
||||
print(f"Output: {status['output']}")
|
||||
print(f"Duration: {status['metadata']['duration']}")
|
||||
else:
|
||||
print(f"Workflow failed: {status['error']}")
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error: {error}")
|
||||
|
||||
execute_async()
|
||||
```
|
||||
|
||||
### Limitation de débit et nouvelle tentative
|
||||
|
||||
Gérez les limites de débit automatiquement avec un retrait exponentiel :
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient, SimStudioError
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_with_retry_handling():
|
||||
try:
|
||||
# Automatically retries on rate limit
|
||||
result = client.execute_with_retry(
|
||||
"workflow-id",
|
||||
input_data={"message": "Process this"},
|
||||
max_retries=5,
|
||||
initial_delay=1.0,
|
||||
max_delay=60.0,
|
||||
backoff_multiplier=2.0
|
||||
)
|
||||
|
||||
print(f"Success: {result}")
|
||||
except SimStudioError as error:
|
||||
if error.code == "RATE_LIMIT_EXCEEDED":
|
||||
print("Rate limit exceeded after all retries")
|
||||
|
||||
# Check rate limit info
|
||||
rate_limit_info = client.get_rate_limit_info()
|
||||
if rate_limit_info:
|
||||
from datetime import datetime
|
||||
reset_time = datetime.fromtimestamp(rate_limit_info.reset)
|
||||
print(f"Rate limit resets at: {reset_time}")
|
||||
|
||||
execute_with_retry_handling()
|
||||
```
|
||||
|
||||
### Surveillance de l'utilisation
|
||||
|
||||
Surveillez l'utilisation et les limites de votre compte :
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def check_usage():
|
||||
try:
|
||||
limits = client.get_usage_limits()
|
||||
|
||||
print("=== Rate Limits ===")
|
||||
print("Sync requests:")
|
||||
print(f" Limit: {limits.rate_limit['sync']['limit']}")
|
||||
print(f" Remaining: {limits.rate_limit['sync']['remaining']}")
|
||||
print(f" Resets at: {limits.rate_limit['sync']['resetAt']}")
|
||||
print(f" Is limited: {limits.rate_limit['sync']['isLimited']}")
|
||||
|
||||
print("\nAsync requests:")
|
||||
print(f" Limit: {limits.rate_limit['async']['limit']}")
|
||||
print(f" Remaining: {limits.rate_limit['async']['remaining']}")
|
||||
print(f" Resets at: {limits.rate_limit['async']['resetAt']}")
|
||||
print(f" Is limited: {limits.rate_limit['async']['isLimited']}")
|
||||
|
||||
print("\n=== Usage ===")
|
||||
print(f"Current period cost: ${limits.usage['currentPeriodCost']:.2f}")
|
||||
print(f"Limit: ${limits.usage['limit']:.2f}")
|
||||
print(f"Plan: {limits.usage['plan']}")
|
||||
|
||||
percent_used = (limits.usage['currentPeriodCost'] / limits.usage['limit']) * 100
|
||||
print(f"Usage: {percent_used:.1f}%")
|
||||
|
||||
if percent_used > 80:
|
||||
print("⚠️ Warning: You are approaching your usage limit!")
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error checking usage: {error}")
|
||||
|
||||
check_usage()
|
||||
```
|
||||
|
||||
### Exécution de workflow en streaming
|
||||
|
||||
Exécutez des workflows avec des réponses en streaming en temps réel :
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_with_streaming():
|
||||
"""Execute workflow with streaming enabled."""
|
||||
try:
|
||||
# Enable streaming for specific block outputs
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"message": "Count to five"},
|
||||
stream=True,
|
||||
selected_outputs=["agent1.content"] # Use blockName.attribute format
|
||||
)
|
||||
|
||||
print("Workflow result:", result)
|
||||
except Exception as error:
|
||||
print("Error:", error)
|
||||
|
||||
execute_with_streaming()
|
||||
```
|
||||
|
||||
La réponse en streaming suit le format Server-Sent Events (SSE) :
|
||||
|
||||
```
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
|
||||
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"}
|
||||
|
||||
data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
|
||||
|
||||
data: [DONE]
|
||||
```
|
||||
|
||||
**Exemple de streaming avec Flask :**
|
||||
|
||||
```python
|
||||
from flask import Flask, Response, stream_with_context
|
||||
import requests
|
||||
import json
|
||||
import os
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route('/stream-workflow')
|
||||
def stream_workflow():
|
||||
"""Stream workflow execution to the client."""
|
||||
|
||||
def generate():
|
||||
response = requests.post(
|
||||
'https://sim.ai/api/workflows/WORKFLOW_ID/execute',
|
||||
headers={
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': os.getenv('SIM_API_KEY')
|
||||
},
|
||||
json={
|
||||
'message': 'Generate a story',
|
||||
'stream': True,
|
||||
'selectedOutputs': ['agent1.content']
|
||||
},
|
||||
stream=True
|
||||
)
|
||||
|
||||
for line in response.iter_lines():
|
||||
if line:
|
||||
decoded_line = line.decode('utf-8')
|
||||
if decoded_line.startswith('data: '):
|
||||
data = decoded_line[6:] # Remove 'data: ' prefix
|
||||
|
||||
if data == '[DONE]':
|
||||
break
|
||||
|
||||
try:
|
||||
parsed = json.loads(data)
|
||||
if 'chunk' in parsed:
|
||||
yield f"data: {json.dumps(parsed)}\n\n"
|
||||
elif parsed.get('event') == 'done':
|
||||
yield f"data: {json.dumps(parsed)}\n\n"
|
||||
print("Execution complete:", parsed.get('metadata'))
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
return Response(
|
||||
stream_with_context(generate()),
|
||||
mimetype='text/event-stream'
|
||||
)
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
```
|
||||
|
||||
### Configuration de l'environnement
|
||||
|
||||
Configurez le client en utilisant des variables d'environnement :
|
||||
|
||||
<Tabs items={['Development', 'Production']}>
|
||||
<Tab value="Development">
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Development configuration
|
||||
client = SimStudioClient(
|
||||
api_key=os.getenv("SIM_API_KEY")
|
||||
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
|
||||
)
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value="Production">
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Production configuration with error handling
|
||||
api_key = os.getenv("SIM_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("SIM_API_KEY environment variable is required")
|
||||
|
||||
client = SimStudioClient(
|
||||
api_key=api_key,
|
||||
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
|
||||
)
|
||||
```
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Obtention de votre clé API
|
||||
|
||||
<Steps>
|
||||
<Step title="Connectez-vous à Sim">
|
||||
Accédez à [Sim](https://sim.ai) et connectez-vous à votre compte.
|
||||
</Step>
|
||||
<Step title="Ouvrez votre workflow">
|
||||
Accédez au workflow que vous souhaitez exécuter par programmation.
|
||||
</Step>
|
||||
<Step title="Déployez votre workflow">
|
||||
Cliquez sur "Déployer" pour déployer votre workflow s'il n'a pas encore été déployé.
|
||||
</Step>
|
||||
<Step title="Créez ou sélectionnez une clé API">
|
||||
Pendant le processus de déploiement, sélectionnez ou créez une clé API.
|
||||
</Step>
|
||||
<Step title="Copiez la clé API">
|
||||
Copiez la clé API pour l'utiliser dans votre application Python.
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## Prérequis
|
||||
|
||||
- Python 3.8+
|
||||
- requests >= 2.25.0
|
||||
|
||||
## Licence
|
||||
|
||||
Apache-2.0
|
||||
1052
apps/docs/content/docs/fr/api-reference/typescript.mdx
Normal file
1052
apps/docs/content/docs/fr/api-reference/typescript.mdx
Normal file
File diff suppressed because it is too large
Load Diff
24
apps/docs/content/docs/fr/meta.json
Normal file
24
apps/docs/content/docs/fr/meta.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"title": "Sim Documentation",
|
||||
"pages": [
|
||||
"./introduction/index",
|
||||
"./getting-started/index",
|
||||
"./quick-reference/index",
|
||||
"triggers",
|
||||
"blocks",
|
||||
"tools",
|
||||
"connections",
|
||||
"mcp",
|
||||
"copilot",
|
||||
"skills",
|
||||
"knowledgebase",
|
||||
"variables",
|
||||
"credentials",
|
||||
"execution",
|
||||
"permissions",
|
||||
"self-hosting",
|
||||
"./enterprise/index",
|
||||
"./keyboard-shortcuts/index"
|
||||
],
|
||||
"defaultOpen": false
|
||||
}
|
||||
94
apps/docs/content/docs/ja/api-reference/authentication.mdx
Normal file
94
apps/docs/content/docs/ja/api-reference/authentication.mdx
Normal file
@@ -0,0 +1,94 @@
|
||||
---
|
||||
title: Authentication
|
||||
description: API key types, generation, and how to authenticate requests
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
|
||||
To access the Sim API, you need an API key. Sim supports two types of API keys — **personal keys** and **workspace keys** — each with different billing and access behaviors.
|
||||
|
||||
## Key Types
|
||||
|
||||
| | **Personal Keys** | **Workspace Keys** |
|
||||
| --- | --- | --- |
|
||||
| **Billed to** | Your individual account | Workspace owner |
|
||||
| **Scope** | Across workspaces you have access to | Shared across the workspace |
|
||||
| **Managed by** | Each user individually | Workspace admins |
|
||||
| **Permissions** | Must be enabled at workspace level | Require admin permissions |
|
||||
|
||||
<Callout type="info">
|
||||
Workspace admins can disable personal API key usage for their workspace. If disabled, only workspace keys can be used.
|
||||
</Callout>
|
||||
|
||||
## Generating API Keys
|
||||
|
||||
To generate a key, open the Sim dashboard and navigate to **Settings**, then go to **Sim Keys** and click **Create**.
|
||||
|
||||
<Callout type="warn">
|
||||
API keys are only shown once when generated. Store your key securely — you will not be able to view it again.
|
||||
</Callout>
|
||||
|
||||
## Using API Keys
|
||||
|
||||
Pass your API key in the `X-API-Key` header with every request:
|
||||
|
||||
<Tabs items={['curl', 'TypeScript', 'Python']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch(
|
||||
'https://www.sim.ai/api/workflows/{workflowId}/execute',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': process.env.SIM_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify({ inputs: {} }),
|
||||
}
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
```python
|
||||
import requests
|
||||
|
||||
response = requests.post(
|
||||
"https://www.sim.ai/api/workflows/{workflowId}/execute",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": os.environ["SIM_API_KEY"],
|
||||
},
|
||||
json={"inputs": {}},
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Where Keys Are Used
|
||||
|
||||
API keys authenticate access to:
|
||||
|
||||
- **Workflow execution** — run deployed workflows via the API
|
||||
- **Logs API** — query workflow execution logs and metrics
|
||||
- **MCP servers** — authenticate connections to deployed MCP servers
|
||||
- **SDKs** — the [Python](/api-reference/python) and [TypeScript](/api-reference/typescript) SDKs use API keys for all operations
|
||||
|
||||
## Security
|
||||
|
||||
- Keys use the `sk-sim-` prefix and are encrypted at rest
|
||||
- Keys can be revoked at any time from the dashboard
|
||||
- Use environment variables to store keys — never hardcode them in source code
|
||||
- For browser-based applications, use a backend proxy to avoid exposing keys to the client
|
||||
|
||||
<Callout type="warn">
|
||||
Never expose your API key in client-side code. Use a server-side proxy to make authenticated requests on behalf of your frontend.
|
||||
</Callout>
|
||||
210
apps/docs/content/docs/ja/api-reference/getting-started.mdx
Normal file
210
apps/docs/content/docs/ja/api-reference/getting-started.mdx
Normal file
@@ -0,0 +1,210 @@
|
||||
---
|
||||
title: Getting Started
|
||||
description: Base URL, first API call, response format, error handling, and pagination
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
|
||||
## Base URL
|
||||
|
||||
All API requests are made to:
|
||||
|
||||
```
|
||||
https://www.sim.ai
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step>
|
||||
### Get your API key
|
||||
|
||||
Go to the Sim platform and navigate to **Settings**, then go to **Sim Keys** and click **Create**. See [Authentication](/api-reference/authentication) for details on key types.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Find your workflow ID
|
||||
|
||||
Open a workflow in the Sim editor. The workflow ID is in the URL:
|
||||
|
||||
```
|
||||
https://www.sim.ai/workspace/{workspaceId}/w/{workflowId}
|
||||
```
|
||||
|
||||
You can also use the [List Workflows](/api-reference/workflows/listWorkflows) endpoint to get all workflow IDs in a workspace.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Deploy your workflow
|
||||
|
||||
A workflow must be deployed before it can be executed via the API. Click the **Deploy** button in the editor toolbar, or use the dashboard to manage deployments.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Make your first request
|
||||
|
||||
<Tabs items={['curl', 'TypeScript', 'Python']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch(
|
||||
`https://www.sim.ai/api/workflows/${workflowId}/execute`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': process.env.SIM_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify({ inputs: {} }),
|
||||
}
|
||||
)
|
||||
|
||||
const data = await response.json()
|
||||
console.log(data.output)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
```python
|
||||
import requests
|
||||
import os
|
||||
|
||||
response = requests.post(
|
||||
f"https://www.sim.ai/api/workflows/{workflow_id}/execute",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": os.environ["SIM_API_KEY"],
|
||||
},
|
||||
json={"inputs": {}},
|
||||
)
|
||||
|
||||
data = response.json()
|
||||
print(data["output"])
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## Sync vs Async Execution
|
||||
|
||||
By default, workflow executions are **synchronous** — the API blocks until the workflow completes and returns the result directly.
|
||||
|
||||
For long-running workflows, use **asynchronous execution** by passing `async: true`:
|
||||
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}, "async": true}'
|
||||
```
|
||||
|
||||
This returns immediately with a `taskId`:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"taskId": "job_abc123",
|
||||
"status": "queued"
|
||||
}
|
||||
```
|
||||
|
||||
Poll the [Get Job Status](/api-reference/workflows/getJobStatus) endpoint until the status is `completed` or `failed`:
|
||||
|
||||
```bash
|
||||
curl https://www.sim.ai/api/jobs/{taskId} \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
```
|
||||
|
||||
<Callout type="info">
|
||||
Job status transitions follow: `queued` → `processing` → `completed` or `failed`. The `output` field is only present when status is `completed`.
|
||||
</Callout>
|
||||
|
||||
## Response Format
|
||||
|
||||
Successful responses include an `output` object with your workflow results and a `limits` object with your current rate limit and usage status:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"output": {
|
||||
"result": "Hello, world!"
|
||||
},
|
||||
"limits": {
|
||||
"workflowExecutionRateLimit": {
|
||||
"sync": {
|
||||
"requestsPerMinute": 60,
|
||||
"maxBurst": 10,
|
||||
"remaining": 59,
|
||||
"resetAt": "2025-01-01T00:01:00Z"
|
||||
},
|
||||
"async": {
|
||||
"requestsPerMinute": 30,
|
||||
"maxBurst": 5,
|
||||
"remaining": 30,
|
||||
"resetAt": "2025-01-01T00:01:00Z"
|
||||
}
|
||||
},
|
||||
"usage": {
|
||||
"currentPeriodCost": 1.25,
|
||||
"limit": 50.00,
|
||||
"plan": "pro",
|
||||
"isExceeded": false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The API uses standard HTTP status codes. Error responses include a human-readable `error` message:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Workflow not found"
|
||||
}
|
||||
```
|
||||
|
||||
| Status | Meaning | What to do |
|
||||
| --- | --- | --- |
|
||||
| `400` | Invalid request parameters | Check the `details` array for specific field errors |
|
||||
| `401` | Missing or invalid API key | Verify your `X-API-Key` header |
|
||||
| `403` | Access denied | Check you have permission for this resource |
|
||||
| `404` | Resource not found | Verify the ID exists and belongs to your workspace |
|
||||
| `429` | Rate limit exceeded | Wait for the duration in the `Retry-After` header |
|
||||
|
||||
<Callout type="info">
|
||||
Use the [Get Usage Limits](/api-reference/usage/getUsageLimits) endpoint to check your current rate limit status and billing usage at any time.
|
||||
</Callout>
|
||||
|
||||
## Rate Limits
|
||||
|
||||
Rate limits depend on your subscription plan and apply separately to synchronous and asynchronous executions. Every execution response includes a `limits` object showing your current rate limit status.
|
||||
|
||||
When rate limited, the API returns a `429` response with a `Retry-After` header indicating how many seconds to wait before retrying.
|
||||
|
||||
## Pagination
|
||||
|
||||
List endpoints (workflows, logs, audit logs) use **cursor-based pagination**:
|
||||
|
||||
```bash
|
||||
# First page
|
||||
curl "https://www.sim.ai/api/v1/logs?limit=20" \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
|
||||
# Next page — use the nextCursor from the previous response
|
||||
curl "https://www.sim.ai/api/v1/logs?limit=20&cursor=abc123" \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
```
|
||||
|
||||
The response includes a `nextCursor` field. When `nextCursor` is absent or `null`, you have reached the last page.
|
||||
16
apps/docs/content/docs/ja/api-reference/meta.json
Normal file
16
apps/docs/content/docs/ja/api-reference/meta.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"title": "API Reference",
|
||||
"root": true,
|
||||
"pages": [
|
||||
"getting-started",
|
||||
"authentication",
|
||||
"---SDKs---",
|
||||
"python",
|
||||
"typescript",
|
||||
"---Endpoints---",
|
||||
"(generated)/workflows",
|
||||
"(generated)/logs",
|
||||
"(generated)/usage",
|
||||
"(generated)/audit-logs"
|
||||
]
|
||||
}
|
||||
766
apps/docs/content/docs/ja/api-reference/python.mdx
Normal file
766
apps/docs/content/docs/ja/api-reference/python.mdx
Normal file
@@ -0,0 +1,766 @@
|
||||
---
|
||||
title: Python
|
||||
---
|
||||
|
||||
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'
|
||||
|
||||
Simの公式Python SDKを使用すると、公式Python SDKを使用してPythonアプリケーションからプログラムでワークフローを実行できます。
|
||||
|
||||
<Callout type="info">
|
||||
Python SDKはPython 3.8以上をサポートし、非同期実行、指数バックオフによる自動レート制限、使用状況追跡機能を提供します。
|
||||
</Callout>
|
||||
|
||||
## インストール
|
||||
|
||||
pipを使用してSDKをインストールします:
|
||||
|
||||
```bash
|
||||
pip install simstudio-sdk
|
||||
```
|
||||
|
||||
## クイックスタート
|
||||
|
||||
以下は、始めるための簡単な例です:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Initialize the client
|
||||
client = SimStudioClient(
|
||||
api_key="your-api-key-here",
|
||||
base_url="https://sim.ai" # optional, defaults to https://sim.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リファレンス
|
||||
|
||||
### SimStudioClient
|
||||
|
||||
#### コンストラクタ
|
||||
|
||||
```python
|
||||
SimStudioClient(api_key: str, base_url: str = "https://sim.ai")
|
||||
```
|
||||
|
||||
**パラメータ:**
|
||||
- `api_key` (str): SimのAPIキー
|
||||
- `base_url` (str, オプション): Sim APIのベースURL
|
||||
|
||||
#### メソッド
|
||||
|
||||
##### execute_workflow()
|
||||
|
||||
オプションの入力データでワークフローを実行します。
|
||||
|
||||
```python
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"message": "Hello, world!"},
|
||||
timeout=30.0 # 30 seconds
|
||||
)
|
||||
```
|
||||
|
||||
**パラメータ:**
|
||||
- `workflow_id` (str): 実行するワークフローのID
|
||||
- `input_data` (dict, オプション): ワークフローに渡す入力データ
|
||||
- `timeout` (float, オプション): タイムアウト(秒)(デフォルト: 30.0)
|
||||
- `stream` (bool, オプション): ストリーミングレスポンスを有効にする(デフォルト: False)
|
||||
- `selected_outputs` (list[str], オプション): `blockName.attribute`形式でストリーミングするブロック出力(例: `["agent1.content"]`)
|
||||
- `async_execution` (bool, オプション): 非同期実行(デフォルト: False)
|
||||
|
||||
**戻り値:** `WorkflowExecutionResult | AsyncExecutionResult`
|
||||
|
||||
`async_execution=True`の場合、ポーリング用のタスクIDをすぐに返します。それ以外の場合は、完了を待ちます。
|
||||
|
||||
##### get_workflow_status()
|
||||
|
||||
ワークフローのステータス(デプロイメントステータスなど)を取得します。
|
||||
|
||||
```python
|
||||
status = client.get_workflow_status("workflow-id")
|
||||
print("Is deployed:", status.is_deployed)
|
||||
```
|
||||
|
||||
**パラメータ:**
|
||||
- `workflow_id` (str): ワークフローのID
|
||||
|
||||
**戻り値:** `WorkflowStatus`
|
||||
|
||||
##### validate_workflow()
|
||||
|
||||
ワークフローが実行準備ができているかを検証します。
|
||||
|
||||
```python
|
||||
is_ready = client.validate_workflow("workflow-id")
|
||||
if is_ready:
|
||||
# Workflow is deployed and ready
|
||||
pass
|
||||
```
|
||||
|
||||
**パラメータ:**
|
||||
- `workflow_id` (str): ワークフローのID
|
||||
|
||||
**戻り値:** `bool`
|
||||
|
||||
##### get_job_status()
|
||||
|
||||
非同期ジョブ実行のステータスを取得します。
|
||||
|
||||
```python
|
||||
status = client.get_job_status("task-id-from-async-execution")
|
||||
print("Status:", status["status"]) # 'queued', 'processing', 'completed', 'failed'
|
||||
if status["status"] == "completed":
|
||||
print("Output:", status["output"])
|
||||
```
|
||||
|
||||
**パラメータ:**
|
||||
- `task_id` (str): 非同期実行から返されたタスクID
|
||||
|
||||
**戻り値:** `Dict[str, Any]`
|
||||
|
||||
**レスポンスフィールド:**
|
||||
- `success` (bool): リクエストが成功したかどうか
|
||||
- `taskId` (str): タスクID
|
||||
- `status` (str): 次のいずれか: `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
|
||||
- `metadata` (dict): `startedAt`, `completedAt`, `duration`を含む
|
||||
- `output` (any, オプション): ワークフロー出力(完了時)
|
||||
- `error` (any, オプション): エラー詳細(失敗時)
|
||||
- `estimatedDuration` (int, オプション): 推定所要時間(ミリ秒)(処理中/キュー時)
|
||||
|
||||
##### execute_with_retry()
|
||||
|
||||
指数バックオフを使用してレート制限エラーで自動的に再試行するワークフロー実行。
|
||||
|
||||
```python
|
||||
result = client.execute_with_retry(
|
||||
"workflow-id",
|
||||
input_data={"message": "Hello"},
|
||||
timeout=30.0,
|
||||
max_retries=3, # Maximum number of retries
|
||||
initial_delay=1.0, # Initial delay in seconds
|
||||
max_delay=30.0, # Maximum delay in seconds
|
||||
backoff_multiplier=2.0 # Exponential backoff multiplier
|
||||
)
|
||||
```
|
||||
|
||||
**パラメータ:**
|
||||
- `workflow_id` (str): 実行するワークフローのID
|
||||
- `input_data` (dict, オプション): ワークフローに渡す入力データ
|
||||
- `timeout` (float, オプション): タイムアウト(秒)
|
||||
- `stream` (bool, オプション): ストリーミングレスポンスを有効にする
|
||||
- `selected_outputs` (list, オプション): ストリーミングするブロック出力
|
||||
- `async_execution` (bool, オプション): 非同期実行
|
||||
- `max_retries` (int, オプション): 最大再試行回数(デフォルト: 3)
|
||||
- `initial_delay` (float, オプション): 初期遅延(秒)(デフォルト: 1.0)
|
||||
- `max_delay` (float, オプション): 最大遅延(秒)(デフォルト: 30.0)
|
||||
- `backoff_multiplier` (float, オプション): バックオフ乗数(デフォルト: 2.0)
|
||||
|
||||
**戻り値:** `WorkflowExecutionResult | AsyncExecutionResult`
|
||||
|
||||
リトライロジックは、サンダリングハード問題を防ぐために±25%のジッターを伴う指数バックオフ(1秒→2秒→4秒→8秒...)を使用します。APIが `retry-after` ヘッダーを提供する場合、代わりにそれが使用されます。
|
||||
|
||||
##### get_rate_limit_info()
|
||||
|
||||
最後のAPIレスポンスから現在のレート制限情報を取得します。
|
||||
|
||||
```python
|
||||
rate_limit_info = client.get_rate_limit_info()
|
||||
if rate_limit_info:
|
||||
print("Limit:", rate_limit_info.limit)
|
||||
print("Remaining:", rate_limit_info.remaining)
|
||||
print("Reset:", datetime.fromtimestamp(rate_limit_info.reset))
|
||||
```
|
||||
|
||||
**戻り値:** `RateLimitInfo | None`
|
||||
|
||||
##### get_usage_limits()
|
||||
|
||||
アカウントの現在の使用制限とクォータ情報を取得します。
|
||||
|
||||
```python
|
||||
limits = client.get_usage_limits()
|
||||
print("Sync requests remaining:", limits.rate_limit["sync"]["remaining"])
|
||||
print("Async requests remaining:", limits.rate_limit["async"]["remaining"])
|
||||
print("Current period cost:", limits.usage["currentPeriodCost"])
|
||||
print("Plan:", limits.usage["plan"])
|
||||
```
|
||||
|
||||
**戻り値:** `UsageLimits`
|
||||
|
||||
**レスポンス構造:**
|
||||
|
||||
```python
|
||||
{
|
||||
"success": bool,
|
||||
"rateLimit": {
|
||||
"sync": {
|
||||
"isLimited": bool,
|
||||
"limit": int,
|
||||
"remaining": int,
|
||||
"resetAt": str
|
||||
},
|
||||
"async": {
|
||||
"isLimited": bool,
|
||||
"limit": int,
|
||||
"remaining": int,
|
||||
"resetAt": str
|
||||
},
|
||||
"authType": str # 'api' or 'manual'
|
||||
},
|
||||
"usage": {
|
||||
"currentPeriodCost": float,
|
||||
"limit": float,
|
||||
"plan": str # e.g., 'free', 'pro'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### set_api_key()
|
||||
|
||||
APIキーを更新します。
|
||||
|
||||
```python
|
||||
client.set_api_key("new-api-key")
|
||||
```
|
||||
|
||||
##### set_base_url()
|
||||
|
||||
ベースURLを更新します。
|
||||
|
||||
```python
|
||||
client.set_base_url("https://my-custom-domain.com")
|
||||
```
|
||||
|
||||
##### close()
|
||||
|
||||
基盤となるHTTPセッションを閉じます。
|
||||
|
||||
```python
|
||||
client.close()
|
||||
```
|
||||
|
||||
## データクラス
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
### AsyncExecutionResult
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class AsyncExecutionResult:
|
||||
success: bool
|
||||
task_id: str
|
||||
status: str # 'queued'
|
||||
created_at: str
|
||||
links: Dict[str, str] # e.g., {"status": "/api/jobs/{taskId}"}
|
||||
```
|
||||
|
||||
### WorkflowStatus
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class WorkflowStatus:
|
||||
is_deployed: bool
|
||||
deployed_at: Optional[str] = None
|
||||
needs_redeployment: bool = False
|
||||
```
|
||||
|
||||
### RateLimitInfo
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class RateLimitInfo:
|
||||
limit: int
|
||||
remaining: int
|
||||
reset: int
|
||||
retry_after: Optional[int] = None
|
||||
```
|
||||
|
||||
### UsageLimits
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class UsageLimits:
|
||||
success: bool
|
||||
rate_limit: Dict[str, Any]
|
||||
usage: Dict[str, Any]
|
||||
```
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
**一般的なエラーコード:**
|
||||
- `UNAUTHORIZED`: 無効なAPIキー
|
||||
- `TIMEOUT`: リクエストがタイムアウトしました
|
||||
- `RATE_LIMIT_EXCEEDED`: レート制限を超えました
|
||||
- `USAGE_LIMIT_EXCEEDED`: 使用制限を超えました
|
||||
- `EXECUTION_ERROR`: ワークフローの実行に失敗しました
|
||||
|
||||
## 例
|
||||
|
||||
### 基本的なワークフロー実行
|
||||
|
||||
<Steps>
|
||||
<Step title="クライアントの初期化">
|
||||
APIキーを使用してSimStudioClientをセットアップします。
|
||||
</Step>
|
||||
<Step title="ワークフローの検証">
|
||||
ワークフローがデプロイされ、実行準備ができているか確認します。
|
||||
</Step>
|
||||
<Step title="ワークフローの実行">
|
||||
入力データでワークフローを実行します。
|
||||
</Step>
|
||||
<Step title="結果の処理">
|
||||
実行結果を処理し、エラーがあれば対処します。
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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()
|
||||
```
|
||||
|
||||
### エラー処理
|
||||
|
||||
ワークフロー実行中に発生する可能性のある様々なタイプのエラーを処理します:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient, SimStudioError
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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
|
||||
```
|
||||
|
||||
### コンテキストマネージャーの使用
|
||||
|
||||
リソースのクリーンアップを自動的に処理するためにクライアントをコンテキストマネージャーとして使用します:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
# Using context manager to automatically close the session
|
||||
with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client:
|
||||
result = client.execute_workflow("workflow-id")
|
||||
print("Result:", result)
|
||||
# Session is automatically closed here
|
||||
```
|
||||
|
||||
### バッチワークフロー実行
|
||||
|
||||
複数のワークフローを効率的に実行します:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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'}")
|
||||
```
|
||||
|
||||
### 非同期ワークフロー実行
|
||||
|
||||
長時間実行されるタスクのためにワークフローを非同期で実行します:
|
||||
|
||||
```python
|
||||
import os
|
||||
import time
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_async():
|
||||
try:
|
||||
# Start async execution
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"data": "large dataset"},
|
||||
async_execution=True # Execute asynchronously
|
||||
)
|
||||
|
||||
# Check if result is an async execution
|
||||
if hasattr(result, 'task_id'):
|
||||
print(f"Task ID: {result.task_id}")
|
||||
print(f"Status endpoint: {result.links['status']}")
|
||||
|
||||
# Poll for completion
|
||||
status = client.get_job_status(result.task_id)
|
||||
|
||||
while status["status"] in ["queued", "processing"]:
|
||||
print(f"Current status: {status['status']}")
|
||||
time.sleep(2) # Wait 2 seconds
|
||||
status = client.get_job_status(result.task_id)
|
||||
|
||||
if status["status"] == "completed":
|
||||
print("Workflow completed!")
|
||||
print(f"Output: {status['output']}")
|
||||
print(f"Duration: {status['metadata']['duration']}")
|
||||
else:
|
||||
print(f"Workflow failed: {status['error']}")
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error: {error}")
|
||||
|
||||
execute_async()
|
||||
```
|
||||
|
||||
### レート制限とリトライ
|
||||
|
||||
指数バックオフを使用して自動的にレート制限を処理します:
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient, SimStudioError
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_with_retry_handling():
|
||||
try:
|
||||
# Automatically retries on rate limit
|
||||
result = client.execute_with_retry(
|
||||
"workflow-id",
|
||||
input_data={"message": "Process this"},
|
||||
max_retries=5,
|
||||
initial_delay=1.0,
|
||||
max_delay=60.0,
|
||||
backoff_multiplier=2.0
|
||||
)
|
||||
|
||||
print(f"Success: {result}")
|
||||
except SimStudioError as error:
|
||||
if error.code == "RATE_LIMIT_EXCEEDED":
|
||||
print("Rate limit exceeded after all retries")
|
||||
|
||||
# Check rate limit info
|
||||
rate_limit_info = client.get_rate_limit_info()
|
||||
if rate_limit_info:
|
||||
from datetime import datetime
|
||||
reset_time = datetime.fromtimestamp(rate_limit_info.reset)
|
||||
print(f"Rate limit resets at: {reset_time}")
|
||||
|
||||
execute_with_retry_handling()
|
||||
```
|
||||
|
||||
### 使用状況モニタリング
|
||||
|
||||
アカウントの使用状況と制限をモニタリングします:
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def check_usage():
|
||||
try:
|
||||
limits = client.get_usage_limits()
|
||||
|
||||
print("=== Rate Limits ===")
|
||||
print("Sync requests:")
|
||||
print(f" Limit: {limits.rate_limit['sync']['limit']}")
|
||||
print(f" Remaining: {limits.rate_limit['sync']['remaining']}")
|
||||
print(f" Resets at: {limits.rate_limit['sync']['resetAt']}")
|
||||
print(f" Is limited: {limits.rate_limit['sync']['isLimited']}")
|
||||
|
||||
print("\nAsync requests:")
|
||||
print(f" Limit: {limits.rate_limit['async']['limit']}")
|
||||
print(f" Remaining: {limits.rate_limit['async']['remaining']}")
|
||||
print(f" Resets at: {limits.rate_limit['async']['resetAt']}")
|
||||
print(f" Is limited: {limits.rate_limit['async']['isLimited']}")
|
||||
|
||||
print("\n=== Usage ===")
|
||||
print(f"Current period cost: ${limits.usage['currentPeriodCost']:.2f}")
|
||||
print(f"Limit: ${limits.usage['limit']:.2f}")
|
||||
print(f"Plan: {limits.usage['plan']}")
|
||||
|
||||
percent_used = (limits.usage['currentPeriodCost'] / limits.usage['limit']) * 100
|
||||
print(f"Usage: {percent_used:.1f}%")
|
||||
|
||||
if percent_used > 80:
|
||||
print("⚠️ Warning: You are approaching your usage limit!")
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error checking usage: {error}")
|
||||
|
||||
check_usage()
|
||||
```
|
||||
|
||||
### ワークフローの実行ストリーミング
|
||||
|
||||
リアルタイムのストリーミングレスポンスでワークフローを実行します:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_with_streaming():
|
||||
"""Execute workflow with streaming enabled."""
|
||||
try:
|
||||
# Enable streaming for specific block outputs
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"message": "Count to five"},
|
||||
stream=True,
|
||||
selected_outputs=["agent1.content"] # Use blockName.attribute format
|
||||
)
|
||||
|
||||
print("Workflow result:", result)
|
||||
except Exception as error:
|
||||
print("Error:", error)
|
||||
|
||||
execute_with_streaming()
|
||||
```
|
||||
|
||||
ストリーミングレスポンスはServer-Sent Events(SSE)形式に従います:
|
||||
|
||||
```
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
|
||||
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"}
|
||||
|
||||
data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
|
||||
|
||||
data: [DONE]
|
||||
```
|
||||
|
||||
**Flaskストリーミングの例:**
|
||||
|
||||
```python
|
||||
from flask import Flask, Response, stream_with_context
|
||||
import requests
|
||||
import json
|
||||
import os
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route('/stream-workflow')
|
||||
def stream_workflow():
|
||||
"""Stream workflow execution to the client."""
|
||||
|
||||
def generate():
|
||||
response = requests.post(
|
||||
'https://sim.ai/api/workflows/WORKFLOW_ID/execute',
|
||||
headers={
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': os.getenv('SIM_API_KEY')
|
||||
},
|
||||
json={
|
||||
'message': 'Generate a story',
|
||||
'stream': True,
|
||||
'selectedOutputs': ['agent1.content']
|
||||
},
|
||||
stream=True
|
||||
)
|
||||
|
||||
for line in response.iter_lines():
|
||||
if line:
|
||||
decoded_line = line.decode('utf-8')
|
||||
if decoded_line.startswith('data: '):
|
||||
data = decoded_line[6:] # Remove 'data: ' prefix
|
||||
|
||||
if data == '[DONE]':
|
||||
break
|
||||
|
||||
try:
|
||||
parsed = json.loads(data)
|
||||
if 'chunk' in parsed:
|
||||
yield f"data: {json.dumps(parsed)}\n\n"
|
||||
elif parsed.get('event') == 'done':
|
||||
yield f"data: {json.dumps(parsed)}\n\n"
|
||||
print("Execution complete:", parsed.get('metadata'))
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
return Response(
|
||||
stream_with_context(generate()),
|
||||
mimetype='text/event-stream'
|
||||
)
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
```
|
||||
|
||||
### 環境設定
|
||||
|
||||
環境変数を使用してクライアントを設定します:
|
||||
|
||||
<Tabs items={['Development', 'Production']}>
|
||||
<Tab value="Development">
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Development configuration
|
||||
client = SimStudioClient(
|
||||
api_key=os.getenv("SIM_API_KEY")
|
||||
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
|
||||
)
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value="Production">
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Production configuration with error handling
|
||||
api_key = os.getenv("SIM_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("SIM_API_KEY environment variable is required")
|
||||
|
||||
client = SimStudioClient(
|
||||
api_key=api_key,
|
||||
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
|
||||
)
|
||||
```
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## APIキーの取得方法
|
||||
|
||||
<Steps>
|
||||
<Step title="Simにログイン">
|
||||
[Sim](https://sim.ai)に移動してアカウントにログインします。
|
||||
</Step>
|
||||
<Step title="ワークフローを開く">
|
||||
プログラムで実行したいワークフローに移動します。
|
||||
</Step>
|
||||
<Step title="ワークフローをデプロイする">
|
||||
まだデプロイされていない場合は、「デプロイ」をクリックしてワークフローをデプロイします。
|
||||
</Step>
|
||||
<Step title="APIキーを作成または選択する">
|
||||
デプロイプロセス中に、APIキーを選択または作成します。
|
||||
</Step>
|
||||
<Step title="APIキーをコピーする">
|
||||
Pythonアプリケーションで使用するAPIキーをコピーします。
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## 要件
|
||||
|
||||
- Python 3.8+
|
||||
- requests >= 2.25.0
|
||||
|
||||
## ライセンス
|
||||
|
||||
Apache-2.0
|
||||
1052
apps/docs/content/docs/ja/api-reference/typescript.mdx
Normal file
1052
apps/docs/content/docs/ja/api-reference/typescript.mdx
Normal file
File diff suppressed because it is too large
Load Diff
24
apps/docs/content/docs/ja/meta.json
Normal file
24
apps/docs/content/docs/ja/meta.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"title": "Sim Documentation",
|
||||
"pages": [
|
||||
"./introduction/index",
|
||||
"./getting-started/index",
|
||||
"./quick-reference/index",
|
||||
"triggers",
|
||||
"blocks",
|
||||
"tools",
|
||||
"connections",
|
||||
"mcp",
|
||||
"copilot",
|
||||
"skills",
|
||||
"knowledgebase",
|
||||
"variables",
|
||||
"credentials",
|
||||
"execution",
|
||||
"permissions",
|
||||
"self-hosting",
|
||||
"./enterprise/index",
|
||||
"./keyboard-shortcuts/index"
|
||||
],
|
||||
"defaultOpen": false
|
||||
}
|
||||
94
apps/docs/content/docs/zh/api-reference/authentication.mdx
Normal file
94
apps/docs/content/docs/zh/api-reference/authentication.mdx
Normal file
@@ -0,0 +1,94 @@
|
||||
---
|
||||
title: Authentication
|
||||
description: API key types, generation, and how to authenticate requests
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
|
||||
To access the Sim API, you need an API key. Sim supports two types of API keys — **personal keys** and **workspace keys** — each with different billing and access behaviors.
|
||||
|
||||
## Key Types
|
||||
|
||||
| | **Personal Keys** | **Workspace Keys** |
|
||||
| --- | --- | --- |
|
||||
| **Billed to** | Your individual account | Workspace owner |
|
||||
| **Scope** | Across workspaces you have access to | Shared across the workspace |
|
||||
| **Managed by** | Each user individually | Workspace admins |
|
||||
| **Permissions** | Must be enabled at workspace level | Require admin permissions |
|
||||
|
||||
<Callout type="info">
|
||||
Workspace admins can disable personal API key usage for their workspace. If disabled, only workspace keys can be used.
|
||||
</Callout>
|
||||
|
||||
## Generating API Keys
|
||||
|
||||
To generate a key, open the Sim platform and navigate to **Settings**, then go to **Sim Keys** and click **Create**.
|
||||
|
||||
<Callout type="warn">
|
||||
API keys are only shown once when generated. Store your key securely — you will not be able to view it again.
|
||||
</Callout>
|
||||
|
||||
## Using API Keys
|
||||
|
||||
Pass your API key in the `X-API-Key` header with every request:
|
||||
|
||||
<Tabs items={['curl', 'TypeScript', 'Python']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch(
|
||||
'https://www.sim.ai/api/workflows/{workflowId}/execute',
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': process.env.SIM_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify({ inputs: {} }),
|
||||
}
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
```python
|
||||
import requests
|
||||
|
||||
response = requests.post(
|
||||
"https://www.sim.ai/api/workflows/{workflowId}/execute",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": os.environ["SIM_API_KEY"],
|
||||
},
|
||||
json={"inputs": {}},
|
||||
)
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## Where Keys Are Used
|
||||
|
||||
API keys authenticate access to:
|
||||
|
||||
- **Workflow execution** — run deployed workflows via the API
|
||||
- **Logs API** — query workflow execution logs and metrics
|
||||
- **MCP servers** — authenticate connections to deployed MCP servers
|
||||
- **SDKs** — the [Python](/api-reference/python) and [TypeScript](/api-reference/typescript) SDKs use API keys for all operations
|
||||
|
||||
## Security
|
||||
|
||||
- Keys use the `sk-sim-` prefix and are encrypted at rest
|
||||
- Keys can be revoked at any time from the dashboard
|
||||
- Use environment variables to store keys — never hardcode them in source code
|
||||
- For browser-based applications, use a backend proxy to avoid exposing keys to the client
|
||||
|
||||
<Callout type="warn">
|
||||
Never expose your API key in client-side code. Use a server-side proxy to make authenticated requests on behalf of your frontend.
|
||||
</Callout>
|
||||
210
apps/docs/content/docs/zh/api-reference/getting-started.mdx
Normal file
210
apps/docs/content/docs/zh/api-reference/getting-started.mdx
Normal file
@@ -0,0 +1,210 @@
|
||||
---
|
||||
title: Getting Started
|
||||
description: Base URL, first API call, response format, error handling, and pagination
|
||||
---
|
||||
|
||||
import { Callout } from 'fumadocs-ui/components/callout'
|
||||
import { Tab, Tabs } from 'fumadocs-ui/components/tabs'
|
||||
import { Step, Steps } from 'fumadocs-ui/components/steps'
|
||||
|
||||
## Base URL
|
||||
|
||||
All API requests are made to:
|
||||
|
||||
```
|
||||
https://www.sim.ai
|
||||
```
|
||||
|
||||
## Quick Start
|
||||
|
||||
<Steps>
|
||||
|
||||
<Step>
|
||||
### Get your API key
|
||||
|
||||
Go to the Sim platform and navigate to **Settings**, then go to **Sim Keys** and click **Create**. See [Authentication](/api-reference/authentication) for details on key types.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Find your workflow ID
|
||||
|
||||
Open a workflow in the Sim editor. The workflow ID is in the URL:
|
||||
|
||||
```
|
||||
https://www.sim.ai/workspace/{workspaceId}/w/{workflowId}
|
||||
```
|
||||
|
||||
You can also use the [List Workflows](/api-reference/workflows/listWorkflows) endpoint to get all workflow IDs in a workspace.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Deploy your workflow
|
||||
|
||||
A workflow must be deployed before it can be executed via the API. Click the **Deploy** button in the editor toolbar, or use the dashboard to manage deployments.
|
||||
</Step>
|
||||
|
||||
<Step>
|
||||
### Make your first request
|
||||
|
||||
<Tabs items={['curl', 'TypeScript', 'Python']}>
|
||||
<Tab value="curl">
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}}'
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="TypeScript">
|
||||
```typescript
|
||||
const response = await fetch(
|
||||
`https://www.sim.ai/api/workflows/${workflowId}/execute`,
|
||||
{
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': process.env.SIM_API_KEY!,
|
||||
},
|
||||
body: JSON.stringify({ inputs: {} }),
|
||||
}
|
||||
)
|
||||
|
||||
const data = await response.json()
|
||||
console.log(data.output)
|
||||
```
|
||||
</Tab>
|
||||
<Tab value="Python">
|
||||
```python
|
||||
import requests
|
||||
import os
|
||||
|
||||
response = requests.post(
|
||||
f"https://www.sim.ai/api/workflows/{workflow_id}/execute",
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"X-API-Key": os.environ["SIM_API_KEY"],
|
||||
},
|
||||
json={"inputs": {}},
|
||||
)
|
||||
|
||||
data = response.json()
|
||||
print(data["output"])
|
||||
```
|
||||
</Tab>
|
||||
</Tabs>
|
||||
</Step>
|
||||
|
||||
</Steps>
|
||||
|
||||
## Sync vs Async Execution
|
||||
|
||||
By default, workflow executions are **synchronous** — the API blocks until the workflow completes and returns the result directly.
|
||||
|
||||
For long-running workflows, use **asynchronous execution** by passing `async: true`:
|
||||
|
||||
```bash
|
||||
curl -X POST https://www.sim.ai/api/workflows/{workflowId}/execute \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "X-API-Key: YOUR_API_KEY" \
|
||||
-d '{"inputs": {}, "async": true}'
|
||||
```
|
||||
|
||||
This returns immediately with a `taskId`:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"taskId": "job_abc123",
|
||||
"status": "queued"
|
||||
}
|
||||
```
|
||||
|
||||
Poll the [Get Job Status](/api-reference/workflows/getJobStatus) endpoint until the status is `completed` or `failed`:
|
||||
|
||||
```bash
|
||||
curl https://www.sim.ai/api/jobs/{taskId} \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
```
|
||||
|
||||
<Callout type="info">
|
||||
Job status transitions follow: `queued` → `processing` → `completed` or `failed`. The `output` field is only present when status is `completed`.
|
||||
</Callout>
|
||||
|
||||
## Response Format
|
||||
|
||||
Successful responses include an `output` object with your workflow results and a `limits` object with your current rate limit and usage status:
|
||||
|
||||
```json
|
||||
{
|
||||
"success": true,
|
||||
"output": {
|
||||
"result": "Hello, world!"
|
||||
},
|
||||
"limits": {
|
||||
"workflowExecutionRateLimit": {
|
||||
"sync": {
|
||||
"requestsPerMinute": 60,
|
||||
"maxBurst": 10,
|
||||
"remaining": 59,
|
||||
"resetAt": "2025-01-01T00:01:00Z"
|
||||
},
|
||||
"async": {
|
||||
"requestsPerMinute": 30,
|
||||
"maxBurst": 5,
|
||||
"remaining": 30,
|
||||
"resetAt": "2025-01-01T00:01:00Z"
|
||||
}
|
||||
},
|
||||
"usage": {
|
||||
"currentPeriodCost": 1.25,
|
||||
"limit": 50.00,
|
||||
"plan": "pro",
|
||||
"isExceeded": false
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
## Error Handling
|
||||
|
||||
The API uses standard HTTP status codes. Error responses include a human-readable `error` message:
|
||||
|
||||
```json
|
||||
{
|
||||
"error": "Workflow not found"
|
||||
}
|
||||
```
|
||||
|
||||
| Status | Meaning | What to do |
|
||||
| --- | --- | --- |
|
||||
| `400` | Invalid request parameters | Check the `details` array for specific field errors |
|
||||
| `401` | Missing or invalid API key | Verify your `X-API-Key` header |
|
||||
| `403` | Access denied | Check you have permission for this resource |
|
||||
| `404` | Resource not found | Verify the ID exists and belongs to your workspace |
|
||||
| `429` | Rate limit exceeded | Wait for the duration in the `Retry-After` header |
|
||||
|
||||
<Callout type="info">
|
||||
Use the [Get Usage Limits](/api-reference/usage/getUsageLimits) endpoint to check your current rate limit status and billing usage at any time.
|
||||
</Callout>
|
||||
|
||||
## Rate Limits
|
||||
|
||||
Rate limits depend on your subscription plan and apply separately to synchronous and asynchronous executions. Every execution response includes a `limits` object showing your current rate limit status.
|
||||
|
||||
When rate limited, the API returns a `429` response with a `Retry-After` header indicating how many seconds to wait before retrying.
|
||||
|
||||
## Pagination
|
||||
|
||||
List endpoints (workflows, logs, audit logs) use **cursor-based pagination**:
|
||||
|
||||
```bash
|
||||
# First page
|
||||
curl "https://www.sim.ai/api/v1/logs?limit=20" \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
|
||||
# Next page — use the nextCursor from the previous response
|
||||
curl "https://www.sim.ai/api/v1/logs?limit=20&cursor=abc123" \
|
||||
-H "X-API-Key: YOUR_API_KEY"
|
||||
```
|
||||
|
||||
The response includes a `nextCursor` field. When `nextCursor` is absent or `null`, you have reached the last page.
|
||||
16
apps/docs/content/docs/zh/api-reference/meta.json
Normal file
16
apps/docs/content/docs/zh/api-reference/meta.json
Normal file
@@ -0,0 +1,16 @@
|
||||
{
|
||||
"title": "API Reference",
|
||||
"root": true,
|
||||
"pages": [
|
||||
"getting-started",
|
||||
"authentication",
|
||||
"---SDKs---",
|
||||
"python",
|
||||
"typescript",
|
||||
"---Endpoints---",
|
||||
"(generated)/workflows",
|
||||
"(generated)/logs",
|
||||
"(generated)/usage",
|
||||
"(generated)/audit-logs"
|
||||
]
|
||||
}
|
||||
766
apps/docs/content/docs/zh/api-reference/python.mdx
Normal file
766
apps/docs/content/docs/zh/api-reference/python.mdx
Normal file
@@ -0,0 +1,766 @@
|
||||
---
|
||||
title: Python
|
||||
---
|
||||
|
||||
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'
|
||||
|
||||
官方的 Python SDK 允许您通过 Python 应用程序以编程方式执行工作流。
|
||||
|
||||
<Callout type="info">
|
||||
Python SDK 支持 Python 3.8+,具备异步执行支持、自动速率限制(带指数退避)以及使用情况跟踪功能。
|
||||
</Callout>
|
||||
|
||||
## 安装
|
||||
|
||||
使用 pip 安装 SDK:
|
||||
|
||||
```bash
|
||||
pip install simstudio-sdk
|
||||
```
|
||||
|
||||
## 快速开始
|
||||
|
||||
以下是一个简单的示例,帮助您快速入门:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Initialize the client
|
||||
client = SimStudioClient(
|
||||
api_key="your-api-key-here",
|
||||
base_url="https://sim.ai" # optional, defaults to https://sim.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 参考
|
||||
|
||||
### SimStudioClient
|
||||
|
||||
#### 构造函数
|
||||
|
||||
```python
|
||||
SimStudioClient(api_key: str, base_url: str = "https://sim.ai")
|
||||
```
|
||||
|
||||
**参数:**
|
||||
- `api_key` (str): 您的 Sim API 密钥
|
||||
- `base_url` (str, 可选): Sim API 的基础 URL
|
||||
|
||||
#### 方法
|
||||
|
||||
##### execute_workflow()
|
||||
|
||||
执行带有可选输入数据的工作流。
|
||||
|
||||
```python
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"message": "Hello, world!"},
|
||||
timeout=30.0 # 30 seconds
|
||||
)
|
||||
```
|
||||
|
||||
**参数:**
|
||||
- `workflow_id` (str): 要执行的工作流 ID
|
||||
- `input_data` (dict, optional): 传递给工作流的输入数据
|
||||
- `timeout` (float, optional): 超时时间(以秒为单位,默认值:30.0)
|
||||
- `stream` (bool, optional): 启用流式响应(默认值:False)
|
||||
- `selected_outputs` (list[str], optional): 以 `blockName.attribute` 格式阻止输出流(例如,`["agent1.content"]`)
|
||||
- `async_execution` (bool, optional): 异步执行(默认值:False)
|
||||
|
||||
**返回值:** `WorkflowExecutionResult | AsyncExecutionResult`
|
||||
|
||||
当 `async_execution=True` 时,立即返回任务 ID 以供轮询。否则,等待完成。
|
||||
|
||||
##### get_workflow_status()
|
||||
|
||||
获取工作流的状态(部署状态等)。
|
||||
|
||||
```python
|
||||
status = client.get_workflow_status("workflow-id")
|
||||
print("Is deployed:", status.is_deployed)
|
||||
```
|
||||
|
||||
**参数:**
|
||||
- `workflow_id` (str): 工作流的 ID
|
||||
|
||||
**返回值:** `WorkflowStatus`
|
||||
|
||||
##### validate_workflow()
|
||||
|
||||
验证工作流是否已准备好执行。
|
||||
|
||||
```python
|
||||
is_ready = client.validate_workflow("workflow-id")
|
||||
if is_ready:
|
||||
# Workflow is deployed and ready
|
||||
pass
|
||||
```
|
||||
|
||||
**参数:**
|
||||
- `workflow_id` (str): 工作流的 ID
|
||||
|
||||
**返回值:** `bool`
|
||||
|
||||
##### get_job_status()
|
||||
|
||||
获取异步任务执行的状态。
|
||||
|
||||
```python
|
||||
status = client.get_job_status("task-id-from-async-execution")
|
||||
print("Status:", status["status"]) # 'queued', 'processing', 'completed', 'failed'
|
||||
if status["status"] == "completed":
|
||||
print("Output:", status["output"])
|
||||
```
|
||||
|
||||
**参数:**
|
||||
- `task_id` (str): 异步执行返回的任务 ID
|
||||
|
||||
**返回值:** `Dict[str, Any]`
|
||||
|
||||
**响应字段:**
|
||||
- `success` (bool): 请求是否成功
|
||||
- `taskId` (str): 任务 ID
|
||||
- `status` (str): 可能的值包括 `'queued'`, `'processing'`, `'completed'`, `'failed'`, `'cancelled'`
|
||||
- `metadata` (dict): 包含 `startedAt`, `completedAt` 和 `duration`
|
||||
- `output` (any, optional): 工作流输出(完成时)
|
||||
- `error` (any, optional): 错误详情(失败时)
|
||||
- `estimatedDuration` (int, optional): 估计持续时间(以毫秒为单位,处理中/排队时)
|
||||
|
||||
##### execute_with_retry()
|
||||
|
||||
使用指数退避在速率限制错误上自动重试执行工作流。
|
||||
|
||||
```python
|
||||
result = client.execute_with_retry(
|
||||
"workflow-id",
|
||||
input_data={"message": "Hello"},
|
||||
timeout=30.0,
|
||||
max_retries=3, # Maximum number of retries
|
||||
initial_delay=1.0, # Initial delay in seconds
|
||||
max_delay=30.0, # Maximum delay in seconds
|
||||
backoff_multiplier=2.0 # Exponential backoff multiplier
|
||||
)
|
||||
```
|
||||
|
||||
**参数:**
|
||||
- `workflow_id` (str): 要执行的工作流 ID
|
||||
- `input_data` (dict, optional): 传递给工作流的输入数据
|
||||
- `timeout` (float, optional): 超时时间(以秒为单位)
|
||||
- `stream` (bool, optional): 启用流式响应
|
||||
- `selected_outputs` (list, optional): 阻止输出流
|
||||
- `async_execution` (bool, optional): 异步执行
|
||||
- `max_retries` (int, optional): 最大重试次数(默认值:3)
|
||||
- `initial_delay` (float, optional): 初始延迟时间(以秒为单位,默认值:1.0)
|
||||
- `max_delay` (float, optional): 最大延迟时间(以秒为单位,默认值:30.0)
|
||||
- `backoff_multiplier` (float, optional): 退避倍数(默认值:2.0)
|
||||
|
||||
**返回值:** `WorkflowExecutionResult | AsyncExecutionResult`
|
||||
|
||||
重试逻辑使用指数退避(1 秒 → 2 秒 → 4 秒 → 8 秒...),并带有 ±25% 的抖动以防止惊群效应。如果 API 提供了 `retry-after` 标头,则会使用该标头。
|
||||
|
||||
##### get_rate_limit_info()
|
||||
|
||||
从上一次 API 响应中获取当前的速率限制信息。
|
||||
|
||||
```python
|
||||
rate_limit_info = client.get_rate_limit_info()
|
||||
if rate_limit_info:
|
||||
print("Limit:", rate_limit_info.limit)
|
||||
print("Remaining:", rate_limit_info.remaining)
|
||||
print("Reset:", datetime.fromtimestamp(rate_limit_info.reset))
|
||||
```
|
||||
|
||||
**返回值:** `RateLimitInfo | None`
|
||||
|
||||
##### get_usage_limits()
|
||||
|
||||
获取您的账户当前的使用限制和配额信息。
|
||||
|
||||
```python
|
||||
limits = client.get_usage_limits()
|
||||
print("Sync requests remaining:", limits.rate_limit["sync"]["remaining"])
|
||||
print("Async requests remaining:", limits.rate_limit["async"]["remaining"])
|
||||
print("Current period cost:", limits.usage["currentPeriodCost"])
|
||||
print("Plan:", limits.usage["plan"])
|
||||
```
|
||||
|
||||
**返回值:** `UsageLimits`
|
||||
|
||||
**响应结构:**
|
||||
|
||||
```python
|
||||
{
|
||||
"success": bool,
|
||||
"rateLimit": {
|
||||
"sync": {
|
||||
"isLimited": bool,
|
||||
"limit": int,
|
||||
"remaining": int,
|
||||
"resetAt": str
|
||||
},
|
||||
"async": {
|
||||
"isLimited": bool,
|
||||
"limit": int,
|
||||
"remaining": int,
|
||||
"resetAt": str
|
||||
},
|
||||
"authType": str # 'api' or 'manual'
|
||||
},
|
||||
"usage": {
|
||||
"currentPeriodCost": float,
|
||||
"limit": float,
|
||||
"plan": str # e.g., 'free', 'pro'
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
##### set_api_key()
|
||||
|
||||
更新 API 密钥。
|
||||
|
||||
```python
|
||||
client.set_api_key("new-api-key")
|
||||
```
|
||||
|
||||
##### set_base_url()
|
||||
|
||||
更新基础 URL。
|
||||
|
||||
```python
|
||||
client.set_base_url("https://my-custom-domain.com")
|
||||
```
|
||||
|
||||
##### close()
|
||||
|
||||
关闭底层 HTTP 会话。
|
||||
|
||||
```python
|
||||
client.close()
|
||||
```
|
||||
|
||||
## 数据类
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
### AsyncExecutionResult
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class AsyncExecutionResult:
|
||||
success: bool
|
||||
task_id: str
|
||||
status: str # 'queued'
|
||||
created_at: str
|
||||
links: Dict[str, str] # e.g., {"status": "/api/jobs/{taskId}"}
|
||||
```
|
||||
|
||||
### WorkflowStatus
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class WorkflowStatus:
|
||||
is_deployed: bool
|
||||
deployed_at: Optional[str] = None
|
||||
needs_redeployment: bool = False
|
||||
```
|
||||
|
||||
### RateLimitInfo
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class RateLimitInfo:
|
||||
limit: int
|
||||
remaining: int
|
||||
reset: int
|
||||
retry_after: Optional[int] = None
|
||||
```
|
||||
|
||||
### UsageLimits
|
||||
|
||||
```python
|
||||
@dataclass
|
||||
class UsageLimits:
|
||||
success: bool
|
||||
rate_limit: Dict[str, Any]
|
||||
usage: Dict[str, Any]
|
||||
```
|
||||
|
||||
### 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
|
||||
```
|
||||
|
||||
**常见错误代码:**
|
||||
- `UNAUTHORIZED`: 无效的 API 密钥
|
||||
- `TIMEOUT`: 请求超时
|
||||
- `RATE_LIMIT_EXCEEDED`: 超出速率限制
|
||||
- `USAGE_LIMIT_EXCEEDED`: 超出使用限制
|
||||
- `EXECUTION_ERROR`: 工作流执行失败
|
||||
|
||||
## 示例
|
||||
|
||||
### 基本工作流执行
|
||||
|
||||
<Steps>
|
||||
<Step title="初始化客户端">
|
||||
使用您的 API 密钥设置 SimStudioClient。
|
||||
</Step>
|
||||
<Step title="验证工作流">
|
||||
检查工作流是否已部署并准备好执行。
|
||||
</Step>
|
||||
<Step title="执行工作流">
|
||||
使用您的输入数据运行工作流。
|
||||
</Step>
|
||||
<Step title="处理结果">
|
||||
处理执行结果并处理任何错误。
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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()
|
||||
```
|
||||
|
||||
### 错误处理
|
||||
|
||||
处理工作流执行过程中可能发生的不同类型的错误:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient, SimStudioError
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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
|
||||
```
|
||||
|
||||
### 上下文管理器的使用
|
||||
|
||||
将客户端用作上下文管理器以自动处理资源清理:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
# Using context manager to automatically close the session
|
||||
with SimStudioClient(api_key=os.getenv("SIM_API_KEY")) as client:
|
||||
result = client.execute_workflow("workflow-id")
|
||||
print("Result:", result)
|
||||
# Session is automatically closed here
|
||||
```
|
||||
|
||||
### 批量工作流执行
|
||||
|
||||
高效地执行多个工作流:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_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'}")
|
||||
```
|
||||
|
||||
### 异步工作流执行
|
||||
|
||||
为长时间运行的任务异步执行工作流:
|
||||
|
||||
```python
|
||||
import os
|
||||
import time
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_async():
|
||||
try:
|
||||
# Start async execution
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"data": "large dataset"},
|
||||
async_execution=True # Execute asynchronously
|
||||
)
|
||||
|
||||
# Check if result is an async execution
|
||||
if hasattr(result, 'task_id'):
|
||||
print(f"Task ID: {result.task_id}")
|
||||
print(f"Status endpoint: {result.links['status']}")
|
||||
|
||||
# Poll for completion
|
||||
status = client.get_job_status(result.task_id)
|
||||
|
||||
while status["status"] in ["queued", "processing"]:
|
||||
print(f"Current status: {status['status']}")
|
||||
time.sleep(2) # Wait 2 seconds
|
||||
status = client.get_job_status(result.task_id)
|
||||
|
||||
if status["status"] == "completed":
|
||||
print("Workflow completed!")
|
||||
print(f"Output: {status['output']}")
|
||||
print(f"Duration: {status['metadata']['duration']}")
|
||||
else:
|
||||
print(f"Workflow failed: {status['error']}")
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error: {error}")
|
||||
|
||||
execute_async()
|
||||
```
|
||||
|
||||
### 速率限制与重试
|
||||
|
||||
通过指数退避自动处理速率限制:
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient, SimStudioError
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_with_retry_handling():
|
||||
try:
|
||||
# Automatically retries on rate limit
|
||||
result = client.execute_with_retry(
|
||||
"workflow-id",
|
||||
input_data={"message": "Process this"},
|
||||
max_retries=5,
|
||||
initial_delay=1.0,
|
||||
max_delay=60.0,
|
||||
backoff_multiplier=2.0
|
||||
)
|
||||
|
||||
print(f"Success: {result}")
|
||||
except SimStudioError as error:
|
||||
if error.code == "RATE_LIMIT_EXCEEDED":
|
||||
print("Rate limit exceeded after all retries")
|
||||
|
||||
# Check rate limit info
|
||||
rate_limit_info = client.get_rate_limit_info()
|
||||
if rate_limit_info:
|
||||
from datetime import datetime
|
||||
reset_time = datetime.fromtimestamp(rate_limit_info.reset)
|
||||
print(f"Rate limit resets at: {reset_time}")
|
||||
|
||||
execute_with_retry_handling()
|
||||
```
|
||||
|
||||
### 使用监控
|
||||
|
||||
监控您的账户使用情况和限制:
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def check_usage():
|
||||
try:
|
||||
limits = client.get_usage_limits()
|
||||
|
||||
print("=== Rate Limits ===")
|
||||
print("Sync requests:")
|
||||
print(f" Limit: {limits.rate_limit['sync']['limit']}")
|
||||
print(f" Remaining: {limits.rate_limit['sync']['remaining']}")
|
||||
print(f" Resets at: {limits.rate_limit['sync']['resetAt']}")
|
||||
print(f" Is limited: {limits.rate_limit['sync']['isLimited']}")
|
||||
|
||||
print("\nAsync requests:")
|
||||
print(f" Limit: {limits.rate_limit['async']['limit']}")
|
||||
print(f" Remaining: {limits.rate_limit['async']['remaining']}")
|
||||
print(f" Resets at: {limits.rate_limit['async']['resetAt']}")
|
||||
print(f" Is limited: {limits.rate_limit['async']['isLimited']}")
|
||||
|
||||
print("\n=== Usage ===")
|
||||
print(f"Current period cost: ${limits.usage['currentPeriodCost']:.2f}")
|
||||
print(f"Limit: ${limits.usage['limit']:.2f}")
|
||||
print(f"Plan: {limits.usage['plan']}")
|
||||
|
||||
percent_used = (limits.usage['currentPeriodCost'] / limits.usage['limit']) * 100
|
||||
print(f"Usage: {percent_used:.1f}%")
|
||||
|
||||
if percent_used > 80:
|
||||
print("⚠️ Warning: You are approaching your usage limit!")
|
||||
|
||||
except Exception as error:
|
||||
print(f"Error checking usage: {error}")
|
||||
|
||||
check_usage()
|
||||
```
|
||||
|
||||
### 流式工作流执行
|
||||
|
||||
通过实时流式响应执行工作流:
|
||||
|
||||
```python
|
||||
from simstudio import SimStudioClient
|
||||
import os
|
||||
|
||||
client = SimStudioClient(api_key=os.getenv("SIM_API_KEY"))
|
||||
|
||||
def execute_with_streaming():
|
||||
"""Execute workflow with streaming enabled."""
|
||||
try:
|
||||
# Enable streaming for specific block outputs
|
||||
result = client.execute_workflow(
|
||||
"workflow-id",
|
||||
input_data={"message": "Count to five"},
|
||||
stream=True,
|
||||
selected_outputs=["agent1.content"] # Use blockName.attribute format
|
||||
)
|
||||
|
||||
print("Workflow result:", result)
|
||||
except Exception as error:
|
||||
print("Error:", error)
|
||||
|
||||
execute_with_streaming()
|
||||
```
|
||||
|
||||
流式响应遵循服务器发送事件 (SSE) 格式:
|
||||
|
||||
```
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":"One"}
|
||||
|
||||
data: {"blockId":"7b7735b9-19e5-4bd6-818b-46aae2596e9f","chunk":", two"}
|
||||
|
||||
data: {"event":"done","success":true,"output":{},"metadata":{"duration":610}}
|
||||
|
||||
data: [DONE]
|
||||
```
|
||||
|
||||
**Flask 流式示例:**
|
||||
|
||||
```python
|
||||
from flask import Flask, Response, stream_with_context
|
||||
import requests
|
||||
import json
|
||||
import os
|
||||
|
||||
app = Flask(__name__)
|
||||
|
||||
@app.route('/stream-workflow')
|
||||
def stream_workflow():
|
||||
"""Stream workflow execution to the client."""
|
||||
|
||||
def generate():
|
||||
response = requests.post(
|
||||
'https://sim.ai/api/workflows/WORKFLOW_ID/execute',
|
||||
headers={
|
||||
'Content-Type': 'application/json',
|
||||
'X-API-Key': os.getenv('SIM_API_KEY')
|
||||
},
|
||||
json={
|
||||
'message': 'Generate a story',
|
||||
'stream': True,
|
||||
'selectedOutputs': ['agent1.content']
|
||||
},
|
||||
stream=True
|
||||
)
|
||||
|
||||
for line in response.iter_lines():
|
||||
if line:
|
||||
decoded_line = line.decode('utf-8')
|
||||
if decoded_line.startswith('data: '):
|
||||
data = decoded_line[6:] # Remove 'data: ' prefix
|
||||
|
||||
if data == '[DONE]':
|
||||
break
|
||||
|
||||
try:
|
||||
parsed = json.loads(data)
|
||||
if 'chunk' in parsed:
|
||||
yield f"data: {json.dumps(parsed)}\n\n"
|
||||
elif parsed.get('event') == 'done':
|
||||
yield f"data: {json.dumps(parsed)}\n\n"
|
||||
print("Execution complete:", parsed.get('metadata'))
|
||||
except json.JSONDecodeError:
|
||||
pass
|
||||
|
||||
return Response(
|
||||
stream_with_context(generate()),
|
||||
mimetype='text/event-stream'
|
||||
)
|
||||
|
||||
if __name__ == '__main__':
|
||||
app.run(debug=True)
|
||||
```
|
||||
|
||||
### 环境配置
|
||||
|
||||
使用环境变量配置客户端:
|
||||
|
||||
<Tabs items={['开发', '生产']}>
|
||||
<Tab value="开发">
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Development configuration
|
||||
client = SimStudioClient(
|
||||
api_key=os.getenv("SIM_API_KEY")
|
||||
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
|
||||
)
|
||||
```
|
||||
|
||||
</Tab>
|
||||
<Tab value="生产">
|
||||
|
||||
```python
|
||||
import os
|
||||
from simstudio import SimStudioClient
|
||||
|
||||
# Production configuration with error handling
|
||||
api_key = os.getenv("SIM_API_KEY")
|
||||
if not api_key:
|
||||
raise ValueError("SIM_API_KEY environment variable is required")
|
||||
|
||||
client = SimStudioClient(
|
||||
api_key=api_key,
|
||||
base_url=os.getenv("SIM_BASE_URL", "https://sim.ai")
|
||||
)
|
||||
```
|
||||
|
||||
</Tab>
|
||||
</Tabs>
|
||||
|
||||
## 获取您的 API 密钥
|
||||
|
||||
<Steps>
|
||||
<Step title="登录 Sim">
|
||||
前往 [Sim](https://sim.ai) 并登录您的账户。
|
||||
</Step>
|
||||
<Step title="打开您的工作流">
|
||||
前往您想要以编程方式执行的工作流。
|
||||
</Step>
|
||||
<Step title="部署您的工作流">
|
||||
如果尚未部署,请点击“部署”以部署您的工作流。
|
||||
</Step>
|
||||
<Step title="创建或选择一个 API 密钥">
|
||||
在部署过程中,选择或创建一个 API 密钥。
|
||||
</Step>
|
||||
<Step title="复制 API 密钥">
|
||||
复制 API 密钥以在您的 Python 应用程序中使用。
|
||||
</Step>
|
||||
</Steps>
|
||||
|
||||
## 系统要求
|
||||
|
||||
- Python 3.8+
|
||||
- requests >= 2.25.0
|
||||
|
||||
## 许可证
|
||||
|
||||
Apache-2.0
|
||||
1052
apps/docs/content/docs/zh/api-reference/typescript.mdx
Normal file
1052
apps/docs/content/docs/zh/api-reference/typescript.mdx
Normal file
File diff suppressed because it is too large
Load Diff
24
apps/docs/content/docs/zh/meta.json
Normal file
24
apps/docs/content/docs/zh/meta.json
Normal file
@@ -0,0 +1,24 @@
|
||||
{
|
||||
"title": "Sim Documentation",
|
||||
"pages": [
|
||||
"./introduction/index",
|
||||
"./getting-started/index",
|
||||
"./quick-reference/index",
|
||||
"triggers",
|
||||
"blocks",
|
||||
"tools",
|
||||
"connections",
|
||||
"mcp",
|
||||
"copilot",
|
||||
"skills",
|
||||
"knowledgebase",
|
||||
"variables",
|
||||
"credentials",
|
||||
"execution",
|
||||
"permissions",
|
||||
"self-hosting",
|
||||
"./enterprise/index",
|
||||
"./keyboard-shortcuts/index"
|
||||
],
|
||||
"defaultOpen": false
|
||||
}
|
||||
@@ -2,7 +2,8 @@ import type { InferPageType } from 'fumadocs-core/source'
|
||||
import type { PageData, source } from '@/lib/source'
|
||||
|
||||
export async function getLLMText(page: InferPageType<typeof source>) {
|
||||
const data = page.data as PageData
|
||||
const data = page.data as unknown as PageData
|
||||
if (typeof data.getText !== 'function') return ''
|
||||
const processed = await data.getText('processed')
|
||||
return `# ${data.title} (${page.url})
|
||||
|
||||
|
||||
132
apps/docs/lib/openapi.ts
Normal file
132
apps/docs/lib/openapi.ts
Normal file
@@ -0,0 +1,132 @@
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { createOpenAPI } from 'fumadocs-openapi/server'
|
||||
|
||||
export const openapi = createOpenAPI({
|
||||
input: ['./openapi.json'],
|
||||
})
|
||||
|
||||
interface OpenAPIOperation {
|
||||
path: string
|
||||
method: string
|
||||
}
|
||||
|
||||
function resolveRef(ref: string, spec: Record<string, unknown>): unknown {
|
||||
const parts = ref.replace('#/', '').split('/')
|
||||
let current: unknown = spec
|
||||
for (const part of parts) {
|
||||
if (current && typeof current === 'object') {
|
||||
current = (current as Record<string, unknown>)[part]
|
||||
} else {
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
return current
|
||||
}
|
||||
|
||||
function resolveRefs(obj: unknown, spec: Record<string, unknown>, depth = 0): unknown {
|
||||
if (depth > 10) return obj
|
||||
if (Array.isArray(obj)) {
|
||||
return obj.map((item) => resolveRefs(item, spec, depth + 1))
|
||||
}
|
||||
if (obj && typeof obj === 'object') {
|
||||
const record = obj as Record<string, unknown>
|
||||
if ('$ref' in record && typeof record.$ref === 'string') {
|
||||
const resolved = resolveRef(record.$ref, spec)
|
||||
return resolveRefs(resolved, spec, depth + 1)
|
||||
}
|
||||
const result: Record<string, unknown> = {}
|
||||
for (const [key, value] of Object.entries(record)) {
|
||||
result[key] = resolveRefs(value, spec, depth + 1)
|
||||
}
|
||||
return result
|
||||
}
|
||||
return obj
|
||||
}
|
||||
|
||||
function formatSchema(schema: unknown): string {
|
||||
return JSON.stringify(schema, null, 2)
|
||||
}
|
||||
|
||||
let cachedSpec: Record<string, unknown> | null = null
|
||||
|
||||
function getSpec(): Record<string, unknown> {
|
||||
if (!cachedSpec) {
|
||||
const specPath = join(process.cwd(), 'openapi.json')
|
||||
cachedSpec = JSON.parse(readFileSync(specPath, 'utf8')) as Record<string, unknown>
|
||||
}
|
||||
return cachedSpec
|
||||
}
|
||||
|
||||
export function getApiSpecContent(
|
||||
title: string,
|
||||
description: string | undefined,
|
||||
operations: OpenAPIOperation[]
|
||||
): string {
|
||||
const spec = getSpec()
|
||||
|
||||
if (!operations || operations.length === 0) {
|
||||
return `# ${title}\n\n${description || ''}`
|
||||
}
|
||||
|
||||
const op = operations[0]
|
||||
const method = op.method.toUpperCase()
|
||||
const pathObj = (spec.paths as Record<string, Record<string, unknown>>)?.[op.path]
|
||||
const operation = pathObj?.[op.method.toLowerCase()] as Record<string, unknown> | undefined
|
||||
|
||||
if (!operation) {
|
||||
return `# ${title}\n\n${description || ''}`
|
||||
}
|
||||
|
||||
const resolved = resolveRefs(operation, spec) as Record<string, unknown>
|
||||
const lines: string[] = []
|
||||
|
||||
lines.push(`# ${title}`)
|
||||
lines.push(`\`${method} ${op.path}\``)
|
||||
|
||||
if (resolved.description) {
|
||||
lines.push(`## Description\n${resolved.description}`)
|
||||
}
|
||||
|
||||
const parameters = resolved.parameters as Array<Record<string, unknown>> | undefined
|
||||
if (parameters && parameters.length > 0) {
|
||||
lines.push('## Parameters')
|
||||
for (const param of parameters) {
|
||||
const required = param.required ? ' (required)' : ''
|
||||
const schemaType = param.schema
|
||||
? ` — \`${(param.schema as Record<string, unknown>).type || 'string'}\``
|
||||
: ''
|
||||
lines.push(
|
||||
`- **${param.name}** (${param.in})${required}${schemaType}: ${param.description || ''}`
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
const requestBody = resolved.requestBody as Record<string, unknown> | undefined
|
||||
if (requestBody) {
|
||||
lines.push('## Request Body')
|
||||
if (requestBody.description) {
|
||||
lines.push(String(requestBody.description))
|
||||
}
|
||||
const content = requestBody.content as Record<string, Record<string, unknown>> | undefined
|
||||
const jsonContent = content?.['application/json']
|
||||
if (jsonContent?.schema) {
|
||||
lines.push(`\`\`\`json\n${formatSchema(jsonContent.schema)}\n\`\`\``)
|
||||
}
|
||||
}
|
||||
|
||||
const responses = resolved.responses as Record<string, Record<string, unknown>> | undefined
|
||||
if (responses) {
|
||||
lines.push('## Responses')
|
||||
for (const [status, response] of Object.entries(responses)) {
|
||||
lines.push(`### ${status} — ${response.description || ''}`)
|
||||
const content = response.content as Record<string, Record<string, unknown>> | undefined
|
||||
const jsonContent = content?.['application/json']
|
||||
if (jsonContent?.schema) {
|
||||
lines.push(`\`\`\`json\n${formatSchema(jsonContent.schema)}\n\`\`\``)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return lines.join('\n\n')
|
||||
}
|
||||
@@ -1,13 +1,93 @@
|
||||
import { type InferPageType, loader } from 'fumadocs-core/source'
|
||||
import { createElement, Fragment } from 'react'
|
||||
import { type InferPageType, loader, multiple } from 'fumadocs-core/source'
|
||||
import type { DocData, DocMethods } from 'fumadocs-mdx/runtime/types'
|
||||
import { openapiSource } from 'fumadocs-openapi/server'
|
||||
import { docs } from '@/.source/server'
|
||||
import { i18n } from './i18n'
|
||||
import { openapi } from './openapi'
|
||||
|
||||
export const source = loader({
|
||||
baseUrl: '/',
|
||||
source: docs.toFumadocsSource(),
|
||||
i18n,
|
||||
})
|
||||
const METHOD_COLORS: Record<string, string> = {
|
||||
GET: 'text-green-600 dark:text-green-400',
|
||||
HEAD: 'text-green-600 dark:text-green-400',
|
||||
OPTIONS: 'text-green-600 dark:text-green-400',
|
||||
POST: 'text-blue-600 dark:text-blue-400',
|
||||
PUT: 'text-yellow-600 dark:text-yellow-400',
|
||||
PATCH: 'text-orange-600 dark:text-orange-400',
|
||||
DELETE: 'text-red-600 dark:text-red-400',
|
||||
}
|
||||
|
||||
/**
|
||||
* Custom openapi plugin that places method badges BEFORE the page name
|
||||
* in the sidebar (like Mintlify/Gumloop) instead of after.
|
||||
*/
|
||||
function openapiPluginBadgeLeft() {
|
||||
return {
|
||||
name: 'fumadocs:openapi-badge-left',
|
||||
enforce: 'pre' as const,
|
||||
transformPageTree: {
|
||||
file(
|
||||
this: {
|
||||
storage: {
|
||||
read: (path: string) => { format: string; data: Record<string, unknown> } | undefined
|
||||
}
|
||||
},
|
||||
node: { name: React.ReactNode },
|
||||
filePath: string | undefined
|
||||
) {
|
||||
if (!filePath) return node
|
||||
const file = this.storage.read(filePath)
|
||||
if (!file || file.format !== 'page') return node
|
||||
const openApiData = file.data._openapi as { method?: string; webhook?: boolean } | undefined
|
||||
if (!openApiData || typeof openApiData !== 'object') return node
|
||||
if (openApiData.webhook) {
|
||||
node.name = createElement(
|
||||
Fragment,
|
||||
null,
|
||||
node.name,
|
||||
' ',
|
||||
createElement(
|
||||
'span',
|
||||
{
|
||||
className:
|
||||
'ms-auto border border-current px-1 rounded-lg text-xs text-nowrap font-mono',
|
||||
},
|
||||
'Webhook'
|
||||
)
|
||||
)
|
||||
} else if (openApiData.method) {
|
||||
const method = openApiData.method.toUpperCase()
|
||||
const colorClass = METHOD_COLORS[method] ?? METHOD_COLORS.GET
|
||||
node.name = createElement(
|
||||
Fragment,
|
||||
null,
|
||||
createElement(
|
||||
'span',
|
||||
{ className: `font-mono font-medium me-1.5 text-[10px] text-nowrap ${colorClass}` },
|
||||
method
|
||||
),
|
||||
node.name
|
||||
)
|
||||
}
|
||||
return node
|
||||
},
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
export const source = loader(
|
||||
multiple({
|
||||
docs: docs.toFumadocsSource(),
|
||||
openapi: await openapiSource(openapi, {
|
||||
baseDir: 'en/api-reference/(generated)',
|
||||
groupBy: 'tag',
|
||||
}),
|
||||
}),
|
||||
{
|
||||
baseUrl: '/',
|
||||
i18n,
|
||||
plugins: [openapiPluginBadgeLeft() as never],
|
||||
}
|
||||
)
|
||||
|
||||
/** Full page data type including MDX content and metadata */
|
||||
export type PageData = DocData &
|
||||
|
||||
1893
apps/docs/openapi.json
Normal file
1893
apps/docs/openapi.json
Normal file
File diff suppressed because it is too large
Load Diff
@@ -17,15 +17,17 @@
|
||||
"class-variance-authority": "^0.7.1",
|
||||
"clsx": "^2.1.1",
|
||||
"drizzle-orm": "^0.44.5",
|
||||
"fumadocs-core": "16.2.3",
|
||||
"fumadocs-mdx": "14.1.0",
|
||||
"fumadocs-ui": "16.2.3",
|
||||
"fumadocs-core": "16.6.7",
|
||||
"fumadocs-mdx": "14.2.8",
|
||||
"fumadocs-openapi": "10.3.13",
|
||||
"fumadocs-ui": "16.6.7",
|
||||
"lucide-react": "^0.511.0",
|
||||
"next": "16.1.6",
|
||||
"next-themes": "^0.4.6",
|
||||
"postgres": "^3.4.5",
|
||||
"react": "19.2.1",
|
||||
"react-dom": "19.2.1",
|
||||
"shiki": "4.0.0",
|
||||
"tailwind-merge": "^3.0.2"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
||||
@@ -1,534 +0,0 @@
|
||||
'use client'
|
||||
|
||||
import { useRef, useState } from 'react'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { X } from 'lucide-react'
|
||||
import { Textarea } from '@/components/emcn'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Label } from '@/components/ui/label'
|
||||
import {
|
||||
Select,
|
||||
SelectContent,
|
||||
SelectItem,
|
||||
SelectTrigger,
|
||||
SelectValue,
|
||||
} from '@/components/ui/select'
|
||||
import { isHosted } from '@/lib/core/config/feature-flags'
|
||||
import { cn } from '@/lib/core/utils/cn'
|
||||
import { quickValidateEmail } from '@/lib/messaging/email/validation'
|
||||
import { soehne } from '@/app/_styles/fonts/soehne/soehne'
|
||||
import { BrandedButton } from '@/app/(auth)/components/branded-button'
|
||||
import Footer from '@/app/(landing)/components/footer/footer'
|
||||
import Nav from '@/app/(landing)/components/nav/nav'
|
||||
|
||||
const logger = createLogger('CareersPage')
|
||||
|
||||
const validateName = (name: string): string[] => {
|
||||
const errors: string[] = []
|
||||
if (!name || name.trim().length < 2) {
|
||||
errors.push('Name must be at least 2 characters')
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
const validateEmail = (email: string): string[] => {
|
||||
const errors: string[] = []
|
||||
if (!email || !email.trim()) {
|
||||
errors.push('Email is required')
|
||||
return errors
|
||||
}
|
||||
const validation = quickValidateEmail(email.trim().toLowerCase())
|
||||
if (!validation.isValid) {
|
||||
errors.push(validation.reason || 'Please enter a valid email address')
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
const validatePosition = (position: string): string[] => {
|
||||
const errors: string[] = []
|
||||
if (!position || position.trim().length < 2) {
|
||||
errors.push('Please specify the position you are interested in')
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
const validateLinkedIn = (url: string): string[] => {
|
||||
if (!url || url.trim() === '') return []
|
||||
const errors: string[] = []
|
||||
try {
|
||||
new URL(url)
|
||||
} catch {
|
||||
errors.push('Please enter a valid LinkedIn URL')
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
const validatePortfolio = (url: string): string[] => {
|
||||
if (!url || url.trim() === '') return []
|
||||
const errors: string[] = []
|
||||
try {
|
||||
new URL(url)
|
||||
} catch {
|
||||
errors.push('Please enter a valid portfolio URL')
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
const validateLocation = (location: string): string[] => {
|
||||
const errors: string[] = []
|
||||
if (!location || location.trim().length < 2) {
|
||||
errors.push('Please enter your location')
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
const validateMessage = (message: string): string[] => {
|
||||
const errors: string[] = []
|
||||
if (!message || message.trim().length < 50) {
|
||||
errors.push('Please tell us more about yourself (at least 50 characters)')
|
||||
}
|
||||
return errors
|
||||
}
|
||||
|
||||
export default function CareersPage() {
|
||||
const [isSubmitting, setIsSubmitting] = useState(false)
|
||||
const [submitStatus, setSubmitStatus] = useState<'idle' | 'success' | 'error'>('idle')
|
||||
const [showErrors, setShowErrors] = useState(false)
|
||||
|
||||
// Form fields
|
||||
const [name, setName] = useState('')
|
||||
const [email, setEmail] = useState('')
|
||||
const [phone, setPhone] = useState('')
|
||||
const [position, setPosition] = useState('')
|
||||
const [linkedin, setLinkedin] = useState('')
|
||||
const [portfolio, setPortfolio] = useState('')
|
||||
const [experience, setExperience] = useState('')
|
||||
const [location, setLocation] = useState('')
|
||||
const [message, setMessage] = useState('')
|
||||
const [resume, setResume] = useState<File | null>(null)
|
||||
const fileInputRef = useRef<HTMLInputElement>(null)
|
||||
|
||||
// Field errors
|
||||
const [nameErrors, setNameErrors] = useState<string[]>([])
|
||||
const [emailErrors, setEmailErrors] = useState<string[]>([])
|
||||
const [positionErrors, setPositionErrors] = useState<string[]>([])
|
||||
const [linkedinErrors, setLinkedinErrors] = useState<string[]>([])
|
||||
const [portfolioErrors, setPortfolioErrors] = useState<string[]>([])
|
||||
const [experienceErrors, setExperienceErrors] = useState<string[]>([])
|
||||
const [locationErrors, setLocationErrors] = useState<string[]>([])
|
||||
const [messageErrors, setMessageErrors] = useState<string[]>([])
|
||||
const [resumeErrors, setResumeErrors] = useState<string[]>([])
|
||||
|
||||
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
const file = e.target.files?.[0] || null
|
||||
setResume(file)
|
||||
if (file) {
|
||||
setResumeErrors([])
|
||||
}
|
||||
}
|
||||
|
||||
async function onSubmit(e: React.FormEvent<HTMLFormElement>) {
|
||||
e.preventDefault()
|
||||
setShowErrors(true)
|
||||
|
||||
// Validate all fields
|
||||
const nameErrs = validateName(name)
|
||||
const emailErrs = validateEmail(email)
|
||||
const positionErrs = validatePosition(position)
|
||||
const linkedinErrs = validateLinkedIn(linkedin)
|
||||
const portfolioErrs = validatePortfolio(portfolio)
|
||||
const experienceErrs = experience ? [] : ['Please select your years of experience']
|
||||
const locationErrs = validateLocation(location)
|
||||
const messageErrs = validateMessage(message)
|
||||
const resumeErrs = resume ? [] : ['Resume is required']
|
||||
|
||||
setNameErrors(nameErrs)
|
||||
setEmailErrors(emailErrs)
|
||||
setPositionErrors(positionErrs)
|
||||
setLinkedinErrors(linkedinErrs)
|
||||
setPortfolioErrors(portfolioErrs)
|
||||
setExperienceErrors(experienceErrs)
|
||||
setLocationErrors(locationErrs)
|
||||
setMessageErrors(messageErrs)
|
||||
setResumeErrors(resumeErrs)
|
||||
|
||||
if (
|
||||
nameErrs.length > 0 ||
|
||||
emailErrs.length > 0 ||
|
||||
positionErrs.length > 0 ||
|
||||
linkedinErrs.length > 0 ||
|
||||
portfolioErrs.length > 0 ||
|
||||
experienceErrs.length > 0 ||
|
||||
locationErrs.length > 0 ||
|
||||
messageErrs.length > 0 ||
|
||||
resumeErrs.length > 0
|
||||
) {
|
||||
return
|
||||
}
|
||||
|
||||
setIsSubmitting(true)
|
||||
setSubmitStatus('idle')
|
||||
|
||||
try {
|
||||
const formData = new FormData()
|
||||
formData.append('name', name)
|
||||
formData.append('email', email)
|
||||
formData.append('phone', phone || '')
|
||||
formData.append('position', position)
|
||||
formData.append('linkedin', linkedin || '')
|
||||
formData.append('portfolio', portfolio || '')
|
||||
formData.append('experience', experience)
|
||||
formData.append('location', location)
|
||||
formData.append('message', message)
|
||||
if (resume) formData.append('resume', resume)
|
||||
|
||||
const response = await fetch('/api/careers/submit', {
|
||||
method: 'POST',
|
||||
body: formData,
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error('Failed to submit application')
|
||||
}
|
||||
|
||||
setSubmitStatus('success')
|
||||
} catch (error) {
|
||||
logger.error('Error submitting application:', error)
|
||||
setSubmitStatus('error')
|
||||
} finally {
|
||||
setIsSubmitting(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<main className={`${soehne.className} min-h-screen bg-white text-gray-900`}>
|
||||
<Nav variant='landing' />
|
||||
|
||||
{/* Content */}
|
||||
<div className='px-4 pt-[60px] pb-[80px] sm:px-8 md:px-[44px]'>
|
||||
<h1 className='mb-10 text-center font-bold text-4xl text-gray-900 md:text-5xl'>
|
||||
Join Our Team
|
||||
</h1>
|
||||
|
||||
<div className='mx-auto max-w-4xl'>
|
||||
{/* Form Section */}
|
||||
<section className='rounded-2xl border border-gray-200 bg-white p-6 shadow-sm sm:p-10'>
|
||||
<form onSubmit={onSubmit} className='space-y-5'>
|
||||
{/* Name and Email */}
|
||||
<div className='grid grid-cols-1 gap-4 sm:gap-6 md:grid-cols-2'>
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='name' className='font-medium text-sm'>
|
||||
Full Name *
|
||||
</Label>
|
||||
<Input
|
||||
id='name'
|
||||
placeholder='John Doe'
|
||||
value={name}
|
||||
onChange={(e) => setName(e.target.value)}
|
||||
className={cn(
|
||||
showErrors &&
|
||||
nameErrors.length > 0 &&
|
||||
'border-red-500 focus:border-red-500 focus:ring-red-100 focus-visible:ring-red-500'
|
||||
)}
|
||||
/>
|
||||
{showErrors && nameErrors.length > 0 && (
|
||||
<div className='mt-1 space-y-1 text-red-400 text-xs'>
|
||||
{nameErrors.map((error, index) => (
|
||||
<p key={index}>{error}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='email' className='font-medium text-sm'>
|
||||
Email *
|
||||
</Label>
|
||||
<Input
|
||||
id='email'
|
||||
type='email'
|
||||
placeholder='john@example.com'
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
className={cn(
|
||||
showErrors &&
|
||||
emailErrors.length > 0 &&
|
||||
'border-red-500 focus:border-red-500 focus:ring-red-100 focus-visible:ring-red-500'
|
||||
)}
|
||||
/>
|
||||
{showErrors && emailErrors.length > 0 && (
|
||||
<div className='mt-1 space-y-1 text-red-400 text-xs'>
|
||||
{emailErrors.map((error, index) => (
|
||||
<p key={index}>{error}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Phone and Position */}
|
||||
<div className='grid grid-cols-1 gap-4 sm:gap-6 md:grid-cols-2'>
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='phone' className='font-medium text-sm'>
|
||||
Phone Number
|
||||
</Label>
|
||||
<Input
|
||||
id='phone'
|
||||
type='tel'
|
||||
placeholder='+1 (555) 123-4567'
|
||||
value={phone}
|
||||
onChange={(e) => setPhone(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='position' className='font-medium text-sm'>
|
||||
Position of Interest *
|
||||
</Label>
|
||||
<Input
|
||||
id='position'
|
||||
placeholder='e.g. Full Stack Engineer, Product Designer'
|
||||
value={position}
|
||||
onChange={(e) => setPosition(e.target.value)}
|
||||
className={cn(
|
||||
showErrors &&
|
||||
positionErrors.length > 0 &&
|
||||
'border-red-500 focus:border-red-500 focus:ring-red-100 focus-visible:ring-red-500'
|
||||
)}
|
||||
/>
|
||||
{showErrors && positionErrors.length > 0 && (
|
||||
<div className='mt-1 space-y-1 text-red-400 text-xs'>
|
||||
{positionErrors.map((error, index) => (
|
||||
<p key={index}>{error}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* LinkedIn and Portfolio */}
|
||||
<div className='grid grid-cols-1 gap-4 sm:gap-6 md:grid-cols-2'>
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='linkedin' className='font-medium text-sm'>
|
||||
LinkedIn Profile
|
||||
</Label>
|
||||
<Input
|
||||
id='linkedin'
|
||||
placeholder='https://linkedin.com/in/yourprofile'
|
||||
value={linkedin}
|
||||
onChange={(e) => setLinkedin(e.target.value)}
|
||||
className={cn(
|
||||
showErrors &&
|
||||
linkedinErrors.length > 0 &&
|
||||
'border-red-500 focus:border-red-500 focus:ring-red-100 focus-visible:ring-red-500'
|
||||
)}
|
||||
/>
|
||||
{showErrors && linkedinErrors.length > 0 && (
|
||||
<div className='mt-1 space-y-1 text-red-400 text-xs'>
|
||||
{linkedinErrors.map((error, index) => (
|
||||
<p key={index}>{error}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='portfolio' className='font-medium text-sm'>
|
||||
Portfolio / Website
|
||||
</Label>
|
||||
<Input
|
||||
id='portfolio'
|
||||
placeholder='https://yourportfolio.com'
|
||||
value={portfolio}
|
||||
onChange={(e) => setPortfolio(e.target.value)}
|
||||
className={cn(
|
||||
showErrors &&
|
||||
portfolioErrors.length > 0 &&
|
||||
'border-red-500 focus:border-red-500 focus:ring-red-100 focus-visible:ring-red-500'
|
||||
)}
|
||||
/>
|
||||
{showErrors && portfolioErrors.length > 0 && (
|
||||
<div className='mt-1 space-y-1 text-red-400 text-xs'>
|
||||
{portfolioErrors.map((error, index) => (
|
||||
<p key={index}>{error}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Experience and Location */}
|
||||
<div className='grid grid-cols-1 gap-4 sm:gap-6 md:grid-cols-2'>
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='experience' className='font-medium text-sm'>
|
||||
Years of Experience *
|
||||
</Label>
|
||||
<Select value={experience} onValueChange={setExperience}>
|
||||
<SelectTrigger
|
||||
className={cn(
|
||||
showErrors &&
|
||||
experienceErrors.length > 0 &&
|
||||
'border-red-500 focus:border-red-500 focus:ring-red-100 focus-visible:ring-red-500'
|
||||
)}
|
||||
>
|
||||
<SelectValue placeholder='Select experience level' />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value='0-1'>0-1 years</SelectItem>
|
||||
<SelectItem value='1-3'>1-3 years</SelectItem>
|
||||
<SelectItem value='3-5'>3-5 years</SelectItem>
|
||||
<SelectItem value='5-10'>5-10 years</SelectItem>
|
||||
<SelectItem value='10+'>10+ years</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
{showErrors && experienceErrors.length > 0 && (
|
||||
<div className='mt-1 space-y-1 text-red-400 text-xs'>
|
||||
{experienceErrors.map((error, index) => (
|
||||
<p key={index}>{error}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='location' className='font-medium text-sm'>
|
||||
Location *
|
||||
</Label>
|
||||
<Input
|
||||
id='location'
|
||||
placeholder='e.g. San Francisco, CA'
|
||||
value={location}
|
||||
onChange={(e) => setLocation(e.target.value)}
|
||||
className={cn(
|
||||
showErrors &&
|
||||
locationErrors.length > 0 &&
|
||||
'border-red-500 focus:border-red-500 focus:ring-red-100 focus-visible:ring-red-500'
|
||||
)}
|
||||
/>
|
||||
{showErrors && locationErrors.length > 0 && (
|
||||
<div className='mt-1 space-y-1 text-red-400 text-xs'>
|
||||
{locationErrors.map((error, index) => (
|
||||
<p key={index}>{error}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Message */}
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='message' className='font-medium text-sm'>
|
||||
Tell us about yourself *
|
||||
</Label>
|
||||
<Textarea
|
||||
id='message'
|
||||
placeholder='Tell us about your experience, what excites you about Sim, and why you would be a great fit for this role...'
|
||||
className={cn(
|
||||
'min-h-[140px]',
|
||||
showErrors &&
|
||||
messageErrors.length > 0 &&
|
||||
'border-red-500 focus:border-red-500 focus:ring-red-100 focus-visible:ring-red-500'
|
||||
)}
|
||||
value={message}
|
||||
onChange={(e) => setMessage(e.target.value)}
|
||||
/>
|
||||
<p className='mt-1.5 text-gray-500 text-xs'>Minimum 50 characters</p>
|
||||
{showErrors && messageErrors.length > 0 && (
|
||||
<div className='mt-1 space-y-1 text-red-400 text-xs'>
|
||||
{messageErrors.map((error, index) => (
|
||||
<p key={index}>{error}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Resume Upload */}
|
||||
<div className='space-y-2'>
|
||||
<Label htmlFor='resume' className='font-medium text-sm'>
|
||||
Resume *
|
||||
</Label>
|
||||
<div className='relative'>
|
||||
{resume ? (
|
||||
<div className='flex items-center gap-2 rounded-md border border-input bg-background px-3 py-2'>
|
||||
<span className='flex-1 truncate text-sm'>{resume.name}</span>
|
||||
<button
|
||||
type='button'
|
||||
onClick={(e) => {
|
||||
e.preventDefault()
|
||||
setResume(null)
|
||||
if (fileInputRef.current) {
|
||||
fileInputRef.current.value = ''
|
||||
}
|
||||
}}
|
||||
className='flex-shrink-0 text-muted-foreground transition-colors hover:text-foreground'
|
||||
aria-label='Remove file'
|
||||
>
|
||||
<X className='h-4 w-4' />
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<Input
|
||||
id='resume'
|
||||
type='file'
|
||||
accept='.pdf,.doc,.docx'
|
||||
onChange={handleFileChange}
|
||||
ref={fileInputRef}
|
||||
className={cn(
|
||||
showErrors &&
|
||||
resumeErrors.length > 0 &&
|
||||
'border-red-500 focus:border-red-500 focus:ring-red-100 focus-visible:ring-red-500'
|
||||
)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
<p className='mt-1.5 text-gray-500 text-xs'>PDF or Word document, max 10MB</p>
|
||||
{showErrors && resumeErrors.length > 0 && (
|
||||
<div className='mt-1 space-y-1 text-red-400 text-xs'>
|
||||
{resumeErrors.map((error, index) => (
|
||||
<p key={index}>{error}</p>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Submit Button */}
|
||||
<div className='flex justify-end pt-2'>
|
||||
<BrandedButton
|
||||
type='submit'
|
||||
disabled={isSubmitting || submitStatus === 'success'}
|
||||
loading={isSubmitting}
|
||||
loadingText='Submitting'
|
||||
showArrow={false}
|
||||
fullWidth={false}
|
||||
className='min-w-[200px]'
|
||||
>
|
||||
{submitStatus === 'success' ? 'Submitted' : 'Submit Application'}
|
||||
</BrandedButton>
|
||||
</div>
|
||||
</form>
|
||||
</section>
|
||||
|
||||
{/* Additional Info */}
|
||||
<section className='mt-6 text-center text-gray-600 text-sm'>
|
||||
<p>
|
||||
Questions? Email us at{' '}
|
||||
<a
|
||||
href='mailto:careers@sim.ai'
|
||||
className='font-medium text-gray-900 underline transition-colors hover:text-gray-700'
|
||||
>
|
||||
careers@sim.ai
|
||||
</a>
|
||||
</p>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Footer - Only for hosted instances */}
|
||||
{isHosted && (
|
||||
<div className='relative z-20'>
|
||||
<Footer fullWidth={true} />
|
||||
</div>
|
||||
)}
|
||||
</main>
|
||||
)
|
||||
}
|
||||
@@ -77,12 +77,14 @@ export default function Footer({ fullWidth = false }: FooterProps) {
|
||||
>
|
||||
Status
|
||||
</Link>
|
||||
<Link
|
||||
href='/careers'
|
||||
<a
|
||||
href='https://jobs.ashbyhq.com/sim'
|
||||
target='_blank'
|
||||
rel='noopener noreferrer'
|
||||
className='text-[14px] text-muted-foreground transition-colors hover:text-foreground'
|
||||
>
|
||||
Careers
|
||||
</Link>
|
||||
</a>
|
||||
<Link
|
||||
href='/privacy'
|
||||
target='_blank'
|
||||
|
||||
@@ -91,12 +91,14 @@ export default function Nav({ hideAuthButtons = false, variant = 'landing' }: Na
|
||||
</button>
|
||||
</li>
|
||||
<li>
|
||||
<Link
|
||||
href='/careers'
|
||||
<a
|
||||
href='https://jobs.ashbyhq.com/sim'
|
||||
target='_blank'
|
||||
rel='noopener noreferrer'
|
||||
className='text-[16px] text-muted-foreground transition-colors hover:text-foreground'
|
||||
>
|
||||
Careers
|
||||
</Link>
|
||||
</a>
|
||||
</li>
|
||||
<li>
|
||||
<a
|
||||
|
||||
@@ -18,7 +18,6 @@ export function ThemeProvider({ children, ...props }: ThemeProviderProps) {
|
||||
pathname.startsWith('/privacy') ||
|
||||
pathname.startsWith('/invite') ||
|
||||
pathname.startsWith('/verify') ||
|
||||
pathname.startsWith('/careers') ||
|
||||
pathname.startsWith('/changelog') ||
|
||||
pathname.startsWith('/chat') ||
|
||||
pathname.startsWith('/studio') ||
|
||||
|
||||
@@ -833,15 +833,7 @@ input[type="search"]::-ms-clear {
|
||||
animation: growShrink 1.5s infinite ease-in-out;
|
||||
}
|
||||
|
||||
/* Subflow node z-index and drag-over styles */
|
||||
.workflow-container .react-flow__node-subflowNode {
|
||||
z-index: -1 !important;
|
||||
}
|
||||
|
||||
.workflow-container .react-flow__node-subflowNode:has([data-subflow-selected="true"]) {
|
||||
z-index: 10 !important;
|
||||
}
|
||||
|
||||
/* Subflow node drag-over styles */
|
||||
.loop-node-drag-over,
|
||||
.parallel-node-drag-over {
|
||||
box-shadow: 0 0 0 1.75px var(--brand-secondary) !important;
|
||||
|
||||
@@ -711,7 +711,7 @@ async function handleMessageStream(
|
||||
if (response.body && isStreamingResponse) {
|
||||
const reader = response.body.getReader()
|
||||
const decoder = new TextDecoder()
|
||||
let accumulatedContent = ''
|
||||
const contentChunks: string[] = []
|
||||
let finalContent: string | undefined
|
||||
|
||||
while (true) {
|
||||
@@ -722,7 +722,7 @@ async function handleMessageStream(
|
||||
const parsed = parseWorkflowSSEChunk(rawChunk)
|
||||
|
||||
if (parsed.content) {
|
||||
accumulatedContent += parsed.content
|
||||
contentChunks.push(parsed.content)
|
||||
sendEvent('message', {
|
||||
kind: 'message',
|
||||
taskId,
|
||||
@@ -738,6 +738,7 @@ async function handleMessageStream(
|
||||
}
|
||||
}
|
||||
|
||||
const accumulatedContent = contentChunks.join('')
|
||||
const messageContent =
|
||||
(finalContent !== undefined && finalContent.length > 0
|
||||
? finalContent
|
||||
|
||||
@@ -6,40 +6,33 @@
|
||||
import { createMockRequest } from '@sim/testing'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const {
|
||||
mockGetSession,
|
||||
mockDb,
|
||||
mockLogger,
|
||||
mockParseProvider,
|
||||
mockEvaluateScopeCoverage,
|
||||
mockJwtDecode,
|
||||
mockEq,
|
||||
} = vi.hoisted(() => {
|
||||
const db = {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
from: vi.fn().mockReturnThis(),
|
||||
where: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn(),
|
||||
const { mockGetSession, mockDb, mockLogger, mockParseProvider, mockJwtDecode, mockEq } = vi.hoisted(
|
||||
() => {
|
||||
const db = {
|
||||
select: vi.fn().mockReturnThis(),
|
||||
from: vi.fn().mockReturnThis(),
|
||||
where: vi.fn().mockReturnThis(),
|
||||
limit: vi.fn(),
|
||||
}
|
||||
const logger = {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
trace: vi.fn(),
|
||||
fatal: vi.fn(),
|
||||
child: vi.fn(),
|
||||
}
|
||||
return {
|
||||
mockGetSession: vi.fn(),
|
||||
mockDb: db,
|
||||
mockLogger: logger,
|
||||
mockParseProvider: vi.fn(),
|
||||
mockJwtDecode: vi.fn(),
|
||||
mockEq: vi.fn((field: unknown, value: unknown) => ({ field, value, type: 'eq' })),
|
||||
}
|
||||
}
|
||||
const logger = {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
error: vi.fn(),
|
||||
debug: vi.fn(),
|
||||
trace: vi.fn(),
|
||||
fatal: vi.fn(),
|
||||
child: vi.fn(),
|
||||
}
|
||||
return {
|
||||
mockGetSession: vi.fn(),
|
||||
mockDb: db,
|
||||
mockLogger: logger,
|
||||
mockParseProvider: vi.fn(),
|
||||
mockEvaluateScopeCoverage: vi.fn(),
|
||||
mockJwtDecode: vi.fn(),
|
||||
mockEq: vi.fn((field: unknown, value: unknown) => ({ field, value, type: 'eq' })),
|
||||
}
|
||||
})
|
||||
)
|
||||
|
||||
vi.mock('@/lib/auth', () => ({
|
||||
getSession: mockGetSession,
|
||||
@@ -66,7 +59,6 @@ vi.mock('@sim/logger', () => ({
|
||||
|
||||
vi.mock('@/lib/oauth/utils', () => ({
|
||||
parseProvider: mockParseProvider,
|
||||
evaluateScopeCoverage: mockEvaluateScopeCoverage,
|
||||
}))
|
||||
|
||||
import { GET } from '@/app/api/auth/oauth/connections/route'
|
||||
@@ -83,16 +75,6 @@ describe('OAuth Connections API Route', () => {
|
||||
baseProvider: providerId.split('-')[0] || providerId,
|
||||
featureType: providerId.split('-')[1] || 'default',
|
||||
}))
|
||||
|
||||
mockEvaluateScopeCoverage.mockImplementation(
|
||||
(_providerId: string, _grantedScopes: string[]) => ({
|
||||
canonicalScopes: ['email', 'profile'],
|
||||
grantedScopes: ['email', 'profile'],
|
||||
missingScopes: [],
|
||||
extraScopes: [],
|
||||
requiresReauthorization: false,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('should return connections successfully', async () => {
|
||||
|
||||
@@ -6,7 +6,7 @@ import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { getSession } from '@/lib/auth'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import type { OAuthProvider } from '@/lib/oauth'
|
||||
import { evaluateScopeCoverage, parseProvider } from '@/lib/oauth'
|
||||
import { parseProvider } from '@/lib/oauth'
|
||||
|
||||
const logger = createLogger('OAuthConnectionsAPI')
|
||||
|
||||
@@ -49,8 +49,7 @@ export async function GET(request: NextRequest) {
|
||||
|
||||
for (const acc of accounts) {
|
||||
const { baseProvider, featureType } = parseProvider(acc.providerId as OAuthProvider)
|
||||
const grantedScopes = acc.scope ? acc.scope.split(/\s+/).filter(Boolean) : []
|
||||
const scopeEvaluation = evaluateScopeCoverage(acc.providerId, grantedScopes)
|
||||
const scopes = acc.scope ? acc.scope.split(/\s+/).filter(Boolean) : []
|
||||
|
||||
if (baseProvider) {
|
||||
// Try multiple methods to get a user-friendly display name
|
||||
@@ -96,10 +95,6 @@ export async function GET(request: NextRequest) {
|
||||
const accountSummary = {
|
||||
id: acc.id,
|
||||
name: displayName,
|
||||
scopes: scopeEvaluation.grantedScopes,
|
||||
missingScopes: scopeEvaluation.missingScopes,
|
||||
extraScopes: scopeEvaluation.extraScopes,
|
||||
requiresReauthorization: scopeEvaluation.requiresReauthorization,
|
||||
}
|
||||
|
||||
if (existingConnection) {
|
||||
@@ -108,20 +103,8 @@ export async function GET(request: NextRequest) {
|
||||
existingConnection.accounts.push(accountSummary)
|
||||
|
||||
existingConnection.scopes = Array.from(
|
||||
new Set([...(existingConnection.scopes || []), ...scopeEvaluation.grantedScopes])
|
||||
new Set([...(existingConnection.scopes || []), ...scopes])
|
||||
)
|
||||
existingConnection.missingScopes = Array.from(
|
||||
new Set([...(existingConnection.missingScopes || []), ...scopeEvaluation.missingScopes])
|
||||
)
|
||||
existingConnection.extraScopes = Array.from(
|
||||
new Set([...(existingConnection.extraScopes || []), ...scopeEvaluation.extraScopes])
|
||||
)
|
||||
existingConnection.canonicalScopes =
|
||||
existingConnection.canonicalScopes && existingConnection.canonicalScopes.length > 0
|
||||
? existingConnection.canonicalScopes
|
||||
: scopeEvaluation.canonicalScopes
|
||||
existingConnection.requiresReauthorization =
|
||||
existingConnection.requiresReauthorization || scopeEvaluation.requiresReauthorization
|
||||
|
||||
const existingTimestamp = existingConnection.lastConnected
|
||||
? new Date(existingConnection.lastConnected).getTime()
|
||||
@@ -138,11 +121,7 @@ export async function GET(request: NextRequest) {
|
||||
baseProvider,
|
||||
featureType,
|
||||
isConnected: true,
|
||||
scopes: scopeEvaluation.grantedScopes,
|
||||
canonicalScopes: scopeEvaluation.canonicalScopes,
|
||||
missingScopes: scopeEvaluation.missingScopes,
|
||||
extraScopes: scopeEvaluation.extraScopes,
|
||||
requiresReauthorization: scopeEvaluation.requiresReauthorization,
|
||||
scopes,
|
||||
lastConnected: acc.updatedAt.toISOString(),
|
||||
accounts: [accountSummary],
|
||||
})
|
||||
|
||||
@@ -7,7 +7,7 @@
|
||||
import { NextRequest } from 'next/server'
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
const { mockCheckSessionOrInternalAuth, mockEvaluateScopeCoverage, mockLogger } = vi.hoisted(() => {
|
||||
const { mockCheckSessionOrInternalAuth, mockLogger } = vi.hoisted(() => {
|
||||
const logger = {
|
||||
info: vi.fn(),
|
||||
warn: vi.fn(),
|
||||
@@ -19,7 +19,6 @@ const { mockCheckSessionOrInternalAuth, mockEvaluateScopeCoverage, mockLogger }
|
||||
}
|
||||
return {
|
||||
mockCheckSessionOrInternalAuth: vi.fn(),
|
||||
mockEvaluateScopeCoverage: vi.fn(),
|
||||
mockLogger: logger,
|
||||
}
|
||||
})
|
||||
@@ -28,10 +27,6 @@ vi.mock('@/lib/auth/hybrid', () => ({
|
||||
checkSessionOrInternalAuth: mockCheckSessionOrInternalAuth,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/oauth', () => ({
|
||||
evaluateScopeCoverage: mockEvaluateScopeCoverage,
|
||||
}))
|
||||
|
||||
vi.mock('@/lib/core/utils/request', () => ({
|
||||
generateRequestId: vi.fn().mockReturnValue('mock-request-id'),
|
||||
}))
|
||||
@@ -87,16 +82,6 @@ describe('OAuth Credentials API Route', () => {
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
mockEvaluateScopeCoverage.mockImplementation(
|
||||
(_providerId: string, grantedScopes: string[]) => ({
|
||||
canonicalScopes: grantedScopes,
|
||||
grantedScopes,
|
||||
missingScopes: [],
|
||||
extraScopes: [],
|
||||
requiresReauthorization: false,
|
||||
})
|
||||
)
|
||||
})
|
||||
|
||||
it('should handle unauthenticated user', async () => {
|
||||
|
||||
@@ -7,7 +7,6 @@ import { z } from 'zod'
|
||||
import { checkSessionOrInternalAuth } from '@/lib/auth/hybrid'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { syncWorkspaceOAuthCredentialsForUser } from '@/lib/credentials/oauth'
|
||||
import { evaluateScopeCoverage } from '@/lib/oauth'
|
||||
import { authorizeWorkflowByWorkspacePermission } from '@/lib/workflows/utils'
|
||||
import { checkWorkspaceAccess } from '@/lib/workspaces/permissions/utils'
|
||||
|
||||
@@ -39,8 +38,7 @@ function toCredentialResponse(
|
||||
scope: string | null
|
||||
) {
|
||||
const storedScope = scope?.trim()
|
||||
const grantedScopes = storedScope ? storedScope.split(/[\s,]+/).filter(Boolean) : []
|
||||
const scopeEvaluation = evaluateScopeCoverage(providerId, grantedScopes)
|
||||
const scopes = storedScope ? storedScope.split(/[\s,]+/).filter(Boolean) : []
|
||||
const [_, featureType = 'default'] = providerId.split('-')
|
||||
|
||||
return {
|
||||
@@ -49,11 +47,7 @@ function toCredentialResponse(
|
||||
provider: providerId,
|
||||
lastUsed: updatedAt.toISOString(),
|
||||
isDefault: featureType === 'default',
|
||||
scopes: scopeEvaluation.grantedScopes,
|
||||
canonicalScopes: scopeEvaluation.canonicalScopes,
|
||||
missingScopes: scopeEvaluation.missingScopes,
|
||||
extraScopes: scopeEvaluation.extraScopes,
|
||||
requiresReauthorization: scopeEvaluation.requiresReauthorization,
|
||||
scopes,
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -1,192 +0,0 @@
|
||||
import { render } from '@react-email/components'
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { type NextRequest, NextResponse } from 'next/server'
|
||||
import { z } from 'zod'
|
||||
import { CareersConfirmationEmail, CareersSubmissionEmail } from '@/components/emails'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { sendEmail } from '@/lib/messaging/email/mailer'
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
const logger = createLogger('CareersAPI')
|
||||
|
||||
const MAX_FILE_SIZE = 10 * 1024 * 1024
|
||||
const ALLOWED_FILE_TYPES = [
|
||||
'application/pdf',
|
||||
'application/msword',
|
||||
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
|
||||
]
|
||||
|
||||
const CareersSubmissionSchema = z.object({
|
||||
name: z.string().min(2, 'Name must be at least 2 characters'),
|
||||
email: z.string().email('Please enter a valid email address'),
|
||||
phone: z.string().optional(),
|
||||
position: z.string().min(2, 'Please specify the position you are interested in'),
|
||||
linkedin: z.string().url('Please enter a valid LinkedIn URL').optional().or(z.literal('')),
|
||||
portfolio: z.string().url('Please enter a valid portfolio URL').optional().or(z.literal('')),
|
||||
experience: z.enum(['0-1', '1-3', '3-5', '5-10', '10+']),
|
||||
location: z.string().min(2, 'Please enter your location'),
|
||||
message: z.string().min(50, 'Please tell us more about yourself (at least 50 characters)'),
|
||||
})
|
||||
|
||||
export async function POST(request: NextRequest) {
|
||||
const requestId = generateRequestId()
|
||||
|
||||
try {
|
||||
const formData = await request.formData()
|
||||
|
||||
const data = {
|
||||
name: formData.get('name') as string,
|
||||
email: formData.get('email') as string,
|
||||
phone: formData.get('phone') as string,
|
||||
position: formData.get('position') as string,
|
||||
linkedin: formData.get('linkedin') as string,
|
||||
portfolio: formData.get('portfolio') as string,
|
||||
experience: formData.get('experience') as string,
|
||||
location: formData.get('location') as string,
|
||||
message: formData.get('message') as string,
|
||||
}
|
||||
|
||||
const resumeFile = formData.get('resume') as File | null
|
||||
if (!resumeFile) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
message: 'Resume is required',
|
||||
errors: [{ path: ['resume'], message: 'Resume is required' }],
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (resumeFile.size > MAX_FILE_SIZE) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
message: 'Resume file size must be less than 10MB',
|
||||
errors: [{ path: ['resume'], message: 'File size must be less than 10MB' }],
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
if (!ALLOWED_FILE_TYPES.includes(resumeFile.type)) {
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
message: 'Resume must be a PDF or Word document',
|
||||
errors: [{ path: ['resume'], message: 'File must be PDF or Word document' }],
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
const resumeBuffer = await resumeFile.arrayBuffer()
|
||||
const resumeBase64 = Buffer.from(resumeBuffer).toString('base64')
|
||||
|
||||
const validatedData = CareersSubmissionSchema.parse(data)
|
||||
|
||||
logger.info(`[${requestId}] Processing career application`, {
|
||||
name: validatedData.name,
|
||||
email: validatedData.email,
|
||||
position: validatedData.position,
|
||||
resumeSize: resumeFile.size,
|
||||
resumeType: resumeFile.type,
|
||||
})
|
||||
|
||||
const submittedDate = new Date()
|
||||
|
||||
const careersEmailHtml = await render(
|
||||
CareersSubmissionEmail({
|
||||
name: validatedData.name,
|
||||
email: validatedData.email,
|
||||
phone: validatedData.phone,
|
||||
position: validatedData.position,
|
||||
linkedin: validatedData.linkedin,
|
||||
portfolio: validatedData.portfolio,
|
||||
experience: validatedData.experience,
|
||||
location: validatedData.location,
|
||||
message: validatedData.message,
|
||||
submittedDate,
|
||||
})
|
||||
)
|
||||
|
||||
const confirmationEmailHtml = await render(
|
||||
CareersConfirmationEmail({
|
||||
name: validatedData.name,
|
||||
position: validatedData.position,
|
||||
submittedDate,
|
||||
})
|
||||
)
|
||||
|
||||
const careersEmailResult = await sendEmail({
|
||||
to: 'careers@sim.ai',
|
||||
subject: `New Career Application: ${validatedData.name} - ${validatedData.position}`,
|
||||
html: careersEmailHtml,
|
||||
emailType: 'transactional',
|
||||
replyTo: validatedData.email,
|
||||
attachments: [
|
||||
{
|
||||
filename: resumeFile.name,
|
||||
content: resumeBase64,
|
||||
contentType: resumeFile.type,
|
||||
},
|
||||
],
|
||||
})
|
||||
|
||||
if (!careersEmailResult.success) {
|
||||
logger.error(`[${requestId}] Failed to send email to careers@sim.ai`, {
|
||||
error: careersEmailResult.message,
|
||||
})
|
||||
throw new Error('Failed to submit application')
|
||||
}
|
||||
|
||||
const confirmationResult = await sendEmail({
|
||||
to: validatedData.email,
|
||||
subject: `Your Application to Sim - ${validatedData.position}`,
|
||||
html: confirmationEmailHtml,
|
||||
emailType: 'transactional',
|
||||
replyTo: validatedData.email,
|
||||
})
|
||||
|
||||
if (!confirmationResult.success) {
|
||||
logger.warn(`[${requestId}] Failed to send confirmation email to applicant`, {
|
||||
email: validatedData.email,
|
||||
error: confirmationResult.message,
|
||||
})
|
||||
}
|
||||
|
||||
logger.info(`[${requestId}] Career application submitted successfully`, {
|
||||
careersEmailSent: careersEmailResult.success,
|
||||
confirmationEmailSent: confirmationResult.success,
|
||||
})
|
||||
|
||||
return NextResponse.json({
|
||||
success: true,
|
||||
message: 'Application submitted successfully',
|
||||
})
|
||||
} catch (error) {
|
||||
if (error instanceof z.ZodError) {
|
||||
logger.warn(`[${requestId}] Invalid application data`, { errors: error.errors })
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
message: 'Invalid application data',
|
||||
errors: error.errors,
|
||||
},
|
||||
{ status: 400 }
|
||||
)
|
||||
}
|
||||
|
||||
logger.error(`[${requestId}] Error processing career application:`, error)
|
||||
|
||||
return NextResponse.json(
|
||||
{
|
||||
success: false,
|
||||
message:
|
||||
'Failed to submit application. Please try again or email us directly at careers@sim.ai',
|
||||
},
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -405,13 +405,17 @@ export async function POST(req: NextRequest) {
|
||||
},
|
||||
})
|
||||
} finally {
|
||||
controller.close()
|
||||
try {
|
||||
controller.close()
|
||||
} catch {
|
||||
// controller may already be closed by cancel()
|
||||
}
|
||||
}
|
||||
},
|
||||
async cancel() {
|
||||
clientDisconnected = true
|
||||
if (eventWriter) {
|
||||
await eventWriter.flush()
|
||||
await eventWriter.close().catch(() => {})
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
@@ -2,8 +2,6 @@ import type { NextRequest } from 'next/server'
|
||||
import { NextResponse } from 'next/server'
|
||||
import {
|
||||
renderBatchInvitationEmail,
|
||||
renderCareersConfirmationEmail,
|
||||
renderCareersSubmissionEmail,
|
||||
renderCreditPurchaseEmail,
|
||||
renderEnterpriseSubscriptionEmail,
|
||||
renderFreeTierUpgradeEmail,
|
||||
@@ -94,22 +92,6 @@ const emailTemplates = {
|
||||
failureReason: 'Card declined',
|
||||
}),
|
||||
|
||||
// Careers emails
|
||||
'careers-confirmation': () => renderCareersConfirmationEmail('John Doe', 'Senior Engineer'),
|
||||
'careers-submission': () =>
|
||||
renderCareersSubmissionEmail({
|
||||
name: 'John Doe',
|
||||
email: 'john@example.com',
|
||||
phone: '+1 (555) 123-4567',
|
||||
position: 'Senior Engineer',
|
||||
linkedin: 'https://linkedin.com/in/johndoe',
|
||||
portfolio: 'https://johndoe.dev',
|
||||
experience: '5-10',
|
||||
location: 'San Francisco, CA',
|
||||
message:
|
||||
'I have 10 years of experience building scalable distributed systems. Most recently, I led a team at a Series B startup where we scaled from 100K to 10M users.',
|
||||
}),
|
||||
|
||||
// Notification emails
|
||||
'workflow-notification-success': () =>
|
||||
renderWorkflowNotificationEmail({
|
||||
@@ -176,7 +158,6 @@ export async function GET(request: NextRequest) {
|
||||
'credit-purchase',
|
||||
'payment-failed',
|
||||
],
|
||||
Careers: ['careers-confirmation', 'careers-submission'],
|
||||
Notifications: [
|
||||
'workflow-notification-success',
|
||||
'workflow-notification-error',
|
||||
|
||||
@@ -36,6 +36,7 @@ export async function GET(_request: NextRequest, { params }: { params: Promise<{
|
||||
stateSnapshotId: workflowExecutionLogs.stateSnapshotId,
|
||||
deploymentVersionId: workflowExecutionLogs.deploymentVersionId,
|
||||
level: workflowExecutionLogs.level,
|
||||
status: workflowExecutionLogs.status,
|
||||
trigger: workflowExecutionLogs.trigger,
|
||||
startedAt: workflowExecutionLogs.startedAt,
|
||||
endedAt: workflowExecutionLogs.endedAt,
|
||||
@@ -99,6 +100,7 @@ export async function GET(_request: NextRequest, { params }: { params: Promise<{
|
||||
deploymentVersion: log.deploymentVersion ?? null,
|
||||
deploymentVersionName: log.deploymentVersionName ?? null,
|
||||
level: log.level,
|
||||
status: log.status,
|
||||
duration: log.totalDurationMs ? `${log.totalDurationMs}ms` : null,
|
||||
trigger: log.trigger,
|
||||
createdAt: log.startedAt.toISOString(),
|
||||
|
||||
79
apps/sim/app/api/tools/airtable/bases/route.ts
Normal file
79
apps/sim/app/api/tools/airtable/bases/route.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { authorizeCredentialUse } from '@/lib/auth/credential-access'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
||||
|
||||
const logger = createLogger('AirtableBasesAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const requestId = generateRequestId()
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { credential, workflowId } = body
|
||||
|
||||
if (!credential) {
|
||||
logger.error('Missing credential in request')
|
||||
return NextResponse.json({ error: 'Credential is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const authz = await authorizeCredentialUse(request as any, {
|
||||
credentialId: credential,
|
||||
workflowId,
|
||||
})
|
||||
if (!authz.ok || !authz.credentialOwnerUserId) {
|
||||
return NextResponse.json({ error: authz.error || 'Unauthorized' }, { status: 403 })
|
||||
}
|
||||
|
||||
const accessToken = await refreshAccessTokenIfNeeded(
|
||||
credential,
|
||||
authz.credentialOwnerUserId,
|
||||
requestId
|
||||
)
|
||||
if (!accessToken) {
|
||||
logger.error('Failed to get access token', {
|
||||
credentialId: credential,
|
||||
userId: authz.credentialOwnerUserId,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Could not retrieve access token', authRequired: true },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const response = await fetch('https://api.airtable.com/v0/meta/bases', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}))
|
||||
logger.error('Failed to fetch Airtable bases', {
|
||||
status: response.status,
|
||||
error: errorData,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch Airtable bases', details: errorData },
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const bases = (data.bases || []).map((base: { id: string; name: string }) => ({
|
||||
id: base.id,
|
||||
name: base.name,
|
||||
}))
|
||||
|
||||
return NextResponse.json({ bases })
|
||||
} catch (error) {
|
||||
logger.error('Error processing Airtable bases request:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to retrieve Airtable bases', details: (error as Error).message },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
95
apps/sim/app/api/tools/airtable/tables/route.ts
Normal file
95
apps/sim/app/api/tools/airtable/tables/route.ts
Normal file
@@ -0,0 +1,95 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { authorizeCredentialUse } from '@/lib/auth/credential-access'
|
||||
import { validateAirtableId } from '@/lib/core/security/input-validation'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
||||
|
||||
const logger = createLogger('AirtableTablesAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const requestId = generateRequestId()
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { credential, workflowId, baseId } = body
|
||||
|
||||
if (!credential) {
|
||||
logger.error('Missing credential in request')
|
||||
return NextResponse.json({ error: 'Credential is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!baseId) {
|
||||
logger.error('Missing baseId in request')
|
||||
return NextResponse.json({ error: 'Base ID is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const baseIdValidation = validateAirtableId(baseId, 'app', 'baseId')
|
||||
if (!baseIdValidation.isValid) {
|
||||
logger.error('Invalid baseId', { error: baseIdValidation.error })
|
||||
return NextResponse.json({ error: baseIdValidation.error }, { status: 400 })
|
||||
}
|
||||
|
||||
const authz = await authorizeCredentialUse(request as any, {
|
||||
credentialId: credential,
|
||||
workflowId,
|
||||
})
|
||||
if (!authz.ok || !authz.credentialOwnerUserId) {
|
||||
return NextResponse.json({ error: authz.error || 'Unauthorized' }, { status: 403 })
|
||||
}
|
||||
|
||||
const accessToken = await refreshAccessTokenIfNeeded(
|
||||
credential,
|
||||
authz.credentialOwnerUserId,
|
||||
requestId
|
||||
)
|
||||
if (!accessToken) {
|
||||
logger.error('Failed to get access token', {
|
||||
credentialId: credential,
|
||||
userId: authz.credentialOwnerUserId,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Could not retrieve access token', authRequired: true },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
`https://api.airtable.com/v0/meta/bases/${baseIdValidation.sanitized}/tables`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}))
|
||||
logger.error('Failed to fetch Airtable tables', {
|
||||
status: response.status,
|
||||
error: errorData,
|
||||
baseId,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch Airtable tables', details: errorData },
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const tables = (data.tables || []).map((table: { id: string; name: string }) => ({
|
||||
id: table.id,
|
||||
name: table.name,
|
||||
}))
|
||||
|
||||
return NextResponse.json({ tables })
|
||||
} catch (error) {
|
||||
logger.error('Error processing Airtable tables request:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to retrieve Airtable tables', details: (error as Error).message },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
79
apps/sim/app/api/tools/asana/workspaces/route.ts
Normal file
79
apps/sim/app/api/tools/asana/workspaces/route.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { authorizeCredentialUse } from '@/lib/auth/credential-access'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
||||
|
||||
const logger = createLogger('AsanaWorkspacesAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const requestId = generateRequestId()
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { credential, workflowId } = body
|
||||
|
||||
if (!credential) {
|
||||
logger.error('Missing credential in request')
|
||||
return NextResponse.json({ error: 'Credential is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const authz = await authorizeCredentialUse(request as any, {
|
||||
credentialId: credential,
|
||||
workflowId,
|
||||
})
|
||||
if (!authz.ok || !authz.credentialOwnerUserId) {
|
||||
return NextResponse.json({ error: authz.error || 'Unauthorized' }, { status: 403 })
|
||||
}
|
||||
|
||||
const accessToken = await refreshAccessTokenIfNeeded(
|
||||
credential,
|
||||
authz.credentialOwnerUserId,
|
||||
requestId
|
||||
)
|
||||
if (!accessToken) {
|
||||
logger.error('Failed to get access token', {
|
||||
credentialId: credential,
|
||||
userId: authz.credentialOwnerUserId,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Could not retrieve access token', authRequired: true },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const response = await fetch('https://app.asana.com/api/1.0/workspaces', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}))
|
||||
logger.error('Failed to fetch Asana workspaces', {
|
||||
status: response.status,
|
||||
error: errorData,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch Asana workspaces', details: errorData },
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const workspaces = (data.data || []).map((workspace: { gid: string; name: string }) => ({
|
||||
id: workspace.gid,
|
||||
name: workspace.name,
|
||||
}))
|
||||
|
||||
return NextResponse.json({ workspaces })
|
||||
} catch (error) {
|
||||
logger.error('Error processing Asana workspaces request:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to retrieve Asana workspaces', details: (error as Error).message },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
79
apps/sim/app/api/tools/attio/lists/route.ts
Normal file
79
apps/sim/app/api/tools/attio/lists/route.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { authorizeCredentialUse } from '@/lib/auth/credential-access'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
||||
|
||||
const logger = createLogger('AttioListsAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const requestId = generateRequestId()
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { credential, workflowId } = body
|
||||
|
||||
if (!credential) {
|
||||
logger.error('Missing credential in request')
|
||||
return NextResponse.json({ error: 'Credential is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const authz = await authorizeCredentialUse(request as any, {
|
||||
credentialId: credential,
|
||||
workflowId,
|
||||
})
|
||||
if (!authz.ok || !authz.credentialOwnerUserId) {
|
||||
return NextResponse.json({ error: authz.error || 'Unauthorized' }, { status: 403 })
|
||||
}
|
||||
|
||||
const accessToken = await refreshAccessTokenIfNeeded(
|
||||
credential,
|
||||
authz.credentialOwnerUserId,
|
||||
requestId
|
||||
)
|
||||
if (!accessToken) {
|
||||
logger.error('Failed to get access token', {
|
||||
credentialId: credential,
|
||||
userId: authz.credentialOwnerUserId,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Could not retrieve access token', authRequired: true },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const response = await fetch('https://api.attio.com/v2/lists', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}))
|
||||
logger.error('Failed to fetch Attio lists', {
|
||||
status: response.status,
|
||||
error: errorData,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch Attio lists', details: errorData },
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const lists = (data.data || []).map((list: { api_slug: string; name: string }) => ({
|
||||
id: list.api_slug,
|
||||
name: list.name,
|
||||
}))
|
||||
|
||||
return NextResponse.json({ lists })
|
||||
} catch (error) {
|
||||
logger.error('Error processing Attio lists request:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to retrieve Attio lists', details: (error as Error).message },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
79
apps/sim/app/api/tools/attio/objects/route.ts
Normal file
79
apps/sim/app/api/tools/attio/objects/route.ts
Normal file
@@ -0,0 +1,79 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { authorizeCredentialUse } from '@/lib/auth/credential-access'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
||||
|
||||
const logger = createLogger('AttioObjectsAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const requestId = generateRequestId()
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { credential, workflowId } = body
|
||||
|
||||
if (!credential) {
|
||||
logger.error('Missing credential in request')
|
||||
return NextResponse.json({ error: 'Credential is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const authz = await authorizeCredentialUse(request as any, {
|
||||
credentialId: credential,
|
||||
workflowId,
|
||||
})
|
||||
if (!authz.ok || !authz.credentialOwnerUserId) {
|
||||
return NextResponse.json({ error: authz.error || 'Unauthorized' }, { status: 403 })
|
||||
}
|
||||
|
||||
const accessToken = await refreshAccessTokenIfNeeded(
|
||||
credential,
|
||||
authz.credentialOwnerUserId,
|
||||
requestId
|
||||
)
|
||||
if (!accessToken) {
|
||||
logger.error('Failed to get access token', {
|
||||
credentialId: credential,
|
||||
userId: authz.credentialOwnerUserId,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Could not retrieve access token', authRequired: true },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const response = await fetch('https://api.attio.com/v2/objects', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
Accept: 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}))
|
||||
logger.error('Failed to fetch Attio objects', {
|
||||
status: response.status,
|
||||
error: errorData,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch Attio objects', details: errorData },
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const objects = (data.data || []).map((obj: { api_slug: string; singular_noun: string }) => ({
|
||||
id: obj.api_slug,
|
||||
name: obj.singular_noun,
|
||||
}))
|
||||
|
||||
return NextResponse.json({ objects })
|
||||
} catch (error) {
|
||||
logger.error('Error processing Attio objects request:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to retrieve Attio objects', details: (error as Error).message },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
83
apps/sim/app/api/tools/calcom/event-types/route.ts
Normal file
83
apps/sim/app/api/tools/calcom/event-types/route.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { authorizeCredentialUse } from '@/lib/auth/credential-access'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
||||
|
||||
const logger = createLogger('CalcomEventTypesAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const requestId = generateRequestId()
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { credential, workflowId } = body
|
||||
|
||||
if (!credential) {
|
||||
logger.error('Missing credential in request')
|
||||
return NextResponse.json({ error: 'Credential is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const authz = await authorizeCredentialUse(request as any, {
|
||||
credentialId: credential,
|
||||
workflowId,
|
||||
})
|
||||
if (!authz.ok || !authz.credentialOwnerUserId) {
|
||||
return NextResponse.json({ error: authz.error || 'Unauthorized' }, { status: 403 })
|
||||
}
|
||||
|
||||
const accessToken = await refreshAccessTokenIfNeeded(
|
||||
credential,
|
||||
authz.credentialOwnerUserId,
|
||||
requestId
|
||||
)
|
||||
if (!accessToken) {
|
||||
logger.error('Failed to get access token', {
|
||||
credentialId: credential,
|
||||
userId: authz.credentialOwnerUserId,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Could not retrieve access token', authRequired: true },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const response = await fetch('https://api.cal.com/v2/event-types', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'cal-api-version': '2024-06-14',
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}))
|
||||
logger.error('Failed to fetch Cal.com event types', {
|
||||
status: response.status,
|
||||
error: errorData,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch Cal.com event types', details: errorData },
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const eventTypes = (data.data || []).map(
|
||||
(eventType: { id: number; title: string; slug: string }) => ({
|
||||
id: String(eventType.id),
|
||||
title: eventType.title,
|
||||
slug: eventType.slug,
|
||||
})
|
||||
)
|
||||
|
||||
return NextResponse.json({ eventTypes })
|
||||
} catch (error) {
|
||||
logger.error('Error processing Cal.com event types request:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to retrieve Cal.com event types', details: (error as Error).message },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
80
apps/sim/app/api/tools/calcom/schedules/route.ts
Normal file
80
apps/sim/app/api/tools/calcom/schedules/route.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { authorizeCredentialUse } from '@/lib/auth/credential-access'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
||||
|
||||
const logger = createLogger('CalcomSchedulesAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const requestId = generateRequestId()
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { credential, workflowId } = body
|
||||
|
||||
if (!credential) {
|
||||
logger.error('Missing credential in request')
|
||||
return NextResponse.json({ error: 'Credential is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const authz = await authorizeCredentialUse(request as any, {
|
||||
credentialId: credential,
|
||||
workflowId,
|
||||
})
|
||||
if (!authz.ok || !authz.credentialOwnerUserId) {
|
||||
return NextResponse.json({ error: authz.error || 'Unauthorized' }, { status: 403 })
|
||||
}
|
||||
|
||||
const accessToken = await refreshAccessTokenIfNeeded(
|
||||
credential,
|
||||
authz.credentialOwnerUserId,
|
||||
requestId
|
||||
)
|
||||
if (!accessToken) {
|
||||
logger.error('Failed to get access token', {
|
||||
credentialId: credential,
|
||||
userId: authz.credentialOwnerUserId,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Could not retrieve access token', authRequired: true },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const response = await fetch('https://api.cal.com/v2/schedules', {
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
'cal-api-version': '2024-06-11',
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}))
|
||||
logger.error('Failed to fetch Cal.com schedules', {
|
||||
status: response.status,
|
||||
error: errorData,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch Cal.com schedules', details: errorData },
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const schedules = (data.data || []).map((schedule: { id: number; name: string }) => ({
|
||||
id: String(schedule.id),
|
||||
name: schedule.name,
|
||||
}))
|
||||
|
||||
return NextResponse.json({ schedules })
|
||||
} catch (error) {
|
||||
logger.error('Error processing Cal.com schedules request:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to retrieve Cal.com schedules', details: (error as Error).message },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
96
apps/sim/app/api/tools/confluence/selector-spaces/route.ts
Normal file
96
apps/sim/app/api/tools/confluence/selector-spaces/route.ts
Normal file
@@ -0,0 +1,96 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { authorizeCredentialUse } from '@/lib/auth/credential-access'
|
||||
import { validateJiraCloudId } from '@/lib/core/security/input-validation'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
||||
import { getConfluenceCloudId } from '@/tools/confluence/utils'
|
||||
|
||||
const logger = createLogger('ConfluenceSelectorSpacesAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const requestId = generateRequestId()
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { credential, workflowId, domain } = body
|
||||
|
||||
if (!credential) {
|
||||
logger.error('Missing credential in request')
|
||||
return NextResponse.json({ error: 'Credential is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!domain) {
|
||||
return NextResponse.json({ error: 'Domain is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const authz = await authorizeCredentialUse(request as any, {
|
||||
credentialId: credential,
|
||||
workflowId,
|
||||
})
|
||||
if (!authz.ok || !authz.credentialOwnerUserId) {
|
||||
return NextResponse.json({ error: authz.error || 'Unauthorized' }, { status: 403 })
|
||||
}
|
||||
|
||||
const accessToken = await refreshAccessTokenIfNeeded(
|
||||
credential,
|
||||
authz.credentialOwnerUserId,
|
||||
requestId
|
||||
)
|
||||
if (!accessToken) {
|
||||
logger.error('Failed to get access token', {
|
||||
credentialId: credential,
|
||||
userId: authz.credentialOwnerUserId,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Could not retrieve access token', authRequired: true },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const cloudId = await getConfluenceCloudId(domain, accessToken)
|
||||
|
||||
const cloudIdValidation = validateJiraCloudId(cloudId, 'cloudId')
|
||||
if (!cloudIdValidation.isValid) {
|
||||
return NextResponse.json({ error: cloudIdValidation.error }, { status: 400 })
|
||||
}
|
||||
|
||||
const url = `https://api.atlassian.com/ex/confluence/${cloudIdValidation.sanitized}/wiki/api/v2/spaces?limit=250`
|
||||
|
||||
const response = await fetch(url, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
Accept: 'application/json',
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => null)
|
||||
logger.error('Confluence API error:', {
|
||||
status: response.status,
|
||||
statusText: response.statusText,
|
||||
error: errorData,
|
||||
})
|
||||
const errorMessage =
|
||||
errorData?.message || `Failed to list Confluence spaces (${response.status})`
|
||||
return NextResponse.json({ error: errorMessage }, { status: response.status })
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const spaces = (data.results || []).map((space: { id: string; name: string; key: string }) => ({
|
||||
id: space.id,
|
||||
name: space.name,
|
||||
key: space.key,
|
||||
}))
|
||||
|
||||
return NextResponse.json({ spaces })
|
||||
} catch (error) {
|
||||
logger.error('Error listing Confluence spaces:', error)
|
||||
return NextResponse.json(
|
||||
{ error: (error as Error).message || 'Internal server error' },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
100
apps/sim/app/api/tools/google_bigquery/datasets/route.ts
Normal file
100
apps/sim/app/api/tools/google_bigquery/datasets/route.ts
Normal file
@@ -0,0 +1,100 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { authorizeCredentialUse } from '@/lib/auth/credential-access'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
||||
|
||||
const logger = createLogger('GoogleBigQueryDatasetsAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
/**
|
||||
* POST /api/tools/google_bigquery/datasets
|
||||
*
|
||||
* Fetches the list of BigQuery datasets for a given project using the caller's OAuth credential.
|
||||
*
|
||||
* @param request - Incoming request containing `credential`, `workflowId`, and `projectId` in the JSON body
|
||||
* @returns JSON response with a `datasets` array, each entry containing `datasetReference` and optional `friendlyName`
|
||||
*/
|
||||
export async function POST(request: Request) {
|
||||
const requestId = generateRequestId()
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { credential, workflowId, projectId } = body
|
||||
|
||||
if (!credential) {
|
||||
logger.error('Missing credential in request')
|
||||
return NextResponse.json({ error: 'Credential is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!projectId) {
|
||||
logger.error('Missing project ID in request')
|
||||
return NextResponse.json({ error: 'Project ID is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const authz = await authorizeCredentialUse(request as any, {
|
||||
credentialId: credential,
|
||||
workflowId,
|
||||
})
|
||||
if (!authz.ok || !authz.credentialOwnerUserId) {
|
||||
return NextResponse.json({ error: authz.error || 'Unauthorized' }, { status: 403 })
|
||||
}
|
||||
|
||||
const accessToken = await refreshAccessTokenIfNeeded(
|
||||
credential,
|
||||
authz.credentialOwnerUserId,
|
||||
requestId
|
||||
)
|
||||
if (!accessToken) {
|
||||
logger.error('Failed to get access token', {
|
||||
credentialId: credential,
|
||||
userId: authz.credentialOwnerUserId,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Could not retrieve access token', authRequired: true },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
`https://bigquery.googleapis.com/bigquery/v2/projects/${encodeURIComponent(projectId)}/datasets?maxResults=200`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}))
|
||||
logger.error('Failed to fetch BigQuery datasets', {
|
||||
status: response.status,
|
||||
error: errorData,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch BigQuery datasets', details: errorData },
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const datasets = (data.datasets || []).map(
|
||||
(ds: {
|
||||
datasetReference: { datasetId: string; projectId: string }
|
||||
friendlyName?: string
|
||||
}) => ({
|
||||
datasetReference: ds.datasetReference,
|
||||
friendlyName: ds.friendlyName,
|
||||
})
|
||||
)
|
||||
|
||||
return NextResponse.json({ datasets })
|
||||
} catch (error) {
|
||||
logger.error('Error processing BigQuery datasets request:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to retrieve BigQuery datasets', details: (error as Error).message },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
94
apps/sim/app/api/tools/google_bigquery/tables/route.ts
Normal file
94
apps/sim/app/api/tools/google_bigquery/tables/route.ts
Normal file
@@ -0,0 +1,94 @@
|
||||
import { createLogger } from '@sim/logger'
|
||||
import { NextResponse } from 'next/server'
|
||||
import { authorizeCredentialUse } from '@/lib/auth/credential-access'
|
||||
import { generateRequestId } from '@/lib/core/utils/request'
|
||||
import { refreshAccessTokenIfNeeded } from '@/app/api/auth/oauth/utils'
|
||||
|
||||
const logger = createLogger('GoogleBigQueryTablesAPI')
|
||||
|
||||
export const dynamic = 'force-dynamic'
|
||||
|
||||
export async function POST(request: Request) {
|
||||
const requestId = generateRequestId()
|
||||
try {
|
||||
const body = await request.json()
|
||||
const { credential, workflowId, projectId, datasetId } = body
|
||||
|
||||
if (!credential) {
|
||||
logger.error('Missing credential in request')
|
||||
return NextResponse.json({ error: 'Credential is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!projectId) {
|
||||
logger.error('Missing project ID in request')
|
||||
return NextResponse.json({ error: 'Project ID is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
if (!datasetId) {
|
||||
logger.error('Missing dataset ID in request')
|
||||
return NextResponse.json({ error: 'Dataset ID is required' }, { status: 400 })
|
||||
}
|
||||
|
||||
const authz = await authorizeCredentialUse(request as any, {
|
||||
credentialId: credential,
|
||||
workflowId,
|
||||
})
|
||||
if (!authz.ok || !authz.credentialOwnerUserId) {
|
||||
return NextResponse.json({ error: authz.error || 'Unauthorized' }, { status: 403 })
|
||||
}
|
||||
|
||||
const accessToken = await refreshAccessTokenIfNeeded(
|
||||
credential,
|
||||
authz.credentialOwnerUserId,
|
||||
requestId
|
||||
)
|
||||
if (!accessToken) {
|
||||
logger.error('Failed to get access token', {
|
||||
credentialId: credential,
|
||||
userId: authz.credentialOwnerUserId,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Could not retrieve access token', authRequired: true },
|
||||
{ status: 401 }
|
||||
)
|
||||
}
|
||||
|
||||
const response = await fetch(
|
||||
`https://bigquery.googleapis.com/bigquery/v2/projects/${encodeURIComponent(projectId)}/datasets/${encodeURIComponent(datasetId)}/tables?maxResults=200`,
|
||||
{
|
||||
headers: {
|
||||
Authorization: `Bearer ${accessToken}`,
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
if (!response.ok) {
|
||||
const errorData = await response.json().catch(() => ({}))
|
||||
logger.error('Failed to fetch BigQuery tables', {
|
||||
status: response.status,
|
||||
error: errorData,
|
||||
})
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to fetch BigQuery tables', details: errorData },
|
||||
{ status: response.status }
|
||||
)
|
||||
}
|
||||
|
||||
const data = await response.json()
|
||||
const tables = (data.tables || []).map(
|
||||
(t: { tableReference: { tableId: string }; friendlyName?: string }) => ({
|
||||
tableReference: t.tableReference,
|
||||
friendlyName: t.friendlyName,
|
||||
})
|
||||
)
|
||||
|
||||
return NextResponse.json({ tables })
|
||||
} catch (error) {
|
||||
logger.error('Error processing BigQuery tables request:', error)
|
||||
return NextResponse.json(
|
||||
{ error: 'Failed to retrieve BigQuery tables', details: (error as Error).message },
|
||||
{ status: 500 }
|
||||
)
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user