跳转到主内容

SDK 快速集成

Creatoria Agent API 文档

#SDK 快速集成

本文档提供 JavaScript/TypeScript、Python 和 cURL 的快速集成示例,帮助您在几分钟内开始使用 Creatoria Agent API。

#基本设置

所有请求都需要以下配置:

  • Base URL: https://your-domain.com/v1
  • 认证: X-API-Key 请求头
  • 项目: X-Project-Id 请求头(可选)

#JavaScript / TypeScript

#基本请求

javascriptconst BASE_URL = 'https://your-domain.com/v1';
const API_KEY = 'your-api-key';

const headers = {
  'X-API-Key': API_KEY,
  'Content-Type': 'application/json',
};

// 列出 Agents
const response = await fetch(`${BASE_URL}/agents`, { headers });
const { data, meta } = await response.json();
console.log(`Found ${meta.total} agents`);

#非流式对话

javascriptconst chatResponse = await fetch(`${BASE_URL}/agents/${agentId}/chat`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    messages: [{ role: 'user', content: '你好' }],
    stream: false,
  }),
});

const result = await chatResponse.json();
console.log(result.data.content);

#流式对话 (SSE)

javascriptconst response = await fetch(`${BASE_URL}/agents/${agentId}/chat`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    message: '分析一下当前市场趋势',
    sessionId: 'optional-session-id',
    stream: true,
  }),
});

const reader = response.body.getReader();
const decoder = new TextDecoder();
let buffer = '';

while (true) {
  const { done, value } = await reader.read();
  if (done) break;

  buffer += decoder.decode(value, { stream: true });
  const lines = buffer.split('\n');
  buffer = lines.pop() || '';

  for (const line of lines) {
    if (!line.startsWith('data: ')) continue;
    const data = line.slice(6);
    if (data === '[DONE]') break;

    try {
      const event = JSON.parse(data);
      if (event.delta) process.stdout.write(event.delta);
      if (event.thinking) console.log('[Thinking]', event.thinking);
      if (event.toolCall) console.log('[Tool Call]', event.toolCall.name);
      if (event.toolResult) console.log('[Tool Result]', event.toolResult.name);
    } catch {}
  }
}

#知识库操作

javascript// 创建知识库
const kb = await fetch(`${BASE_URL}/knowledge-bases`, {
  method: 'POST',
  headers,
  body: JSON.stringify({
    name: '产品文档',
    description: '产品相关文档和FAQ',
  }),
}).then(r => r.json());

// 上传文档
const formData = new FormData();
formData.append('file', fileBlob, 'document.pdf');

await fetch(`${BASE_URL}/knowledge-bases/${kb.data.id}/documents`, {
  method: 'POST',
  headers: { 'X-API-Key': API_KEY },
  body: formData,
});

#Python

#基本请求

pythonimport requests

BASE_URL = 'https://your-domain.com/v1'
HEADERS = {
    'X-API-Key': 'your-api-key',
    'Content-Type': 'application/json',
}

# 列出 Agents
resp = requests.get(f'{BASE_URL}/agents', headers=HEADERS)
result = resp.json()
print(f"Found {result['meta']['total']} agents")

#非流式对话

pythonresp = requests.post(
    f'{BASE_URL}/agents/{agent_id}/chat',
    headers=HEADERS,
    json={
        'messages': [{'role': 'user', 'content': '你好'}],
        'stream': False,
    },
)
print(resp.json()['data']['content'])

#流式对话 (SSE)

pythonimport json

resp = requests.post(
    f'{BASE_URL}/agents/{agent_id}/chat',
    headers=HEADERS,
    json={
        'message': '分析一下当前市场趋势',
        'stream': True,
    },
    stream=True,
)

for line in resp.iter_lines():
    if not line:
        continue
    line = line.decode('utf-8')
    if not line.startswith('data: '):
        continue
    data = line[6:]
    if data == '[DONE]':
        break
    try:
        event = json.loads(data)
        if 'delta' in event:
            print(event['delta'], end='', flush=True)
    except json.JSONDecodeError:
        pass

#cURL

#列出 Agents

bashcurl -X GET "https://your-domain.com/v1/agents" \
  -H "X-API-Key: your-api-key" \
  -H "X-Project-Id: your-project-id"

#创建 Agent

bashcurl -X POST "https://your-domain.com/v1/agents" \
  -H "X-API-Key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "name": "客服助手",
    "model": "zhipu/glm-4",
    "systemPrompt": "你是一个专业的客服助手。"
  }'

#非流式对话

bashcurl -X POST "https://your-domain.com/v1/agents/AGENT_ID/chat" \
  -H "X-API-Key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "messages": [{"role": "user", "content": "你好"}],
    "stream": false
  }'

#流式对话

bashcurl -N -X POST "https://your-domain.com/v1/agents/AGENT_ID/chat" \
  -H "X-API-Key: your-api-key" \
  -H "Content-Type: application/json" \
  -d '{
    "message": "介绍一下你自己",
    "stream": true
  }'

#错误处理

所有 SDK 集成都应处理以下情况:

  • 401: API Key 无效或缺失 — 检查 X-API-Key 请求头
  • 429: 速率限制 — 读取 Retry-After 响应头并等待
  • 5xx: 服务端错误 — 实现指数退避重试

详见错误处理文档。