# OpenClaw API参考与使用指南
## 1. API概述
OpenClaw提供了一套完整的RESTful API,允许开发者通过HTTP请求与OpenClaw进行交互。本文将详细介绍OpenClaw的API接口、认证方式、使用示例和最佳实践,帮助开发者快速集成和使用OpenClaw。
## 2. 认证与授权
### 2.1 API密钥认证
OpenClaw使用API密钥进行认证,确保只有授权用户能够访问API。
**获取API密钥**:
1. 登录OpenClaw管理控制台
2. 导航到”API密钥”部分
3. 生成新的API密钥
4. 复制并保存API密钥
**使用API密钥**:
在请求头中包含`Authorization`字段,格式为`Bearer
**示例**:
“`bash
curl -X GET “https://api.openclaw.com/v1/assistants” \
-H “Authorization: Bearer sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
“`
### 2.2 权限范围
OpenClaw API密钥支持不同的权限范围,包括:
– `assistants:read`: 读取助手信息
– `assistants:write`: 创建和修改助手
– `conversations:read`: 读取对话历史
– `conversations:write`: 创建和修改对话
– `tools:read`: 读取工具信息
– `tools:write`: 创建和修改工具
– `skills:read`: 读取技能信息
– `skills:write`: 创建和修改技能
– `models:read`: 读取模型信息
– `models:write`: 创建和修改模型
## 3. 助手管理API
### 3.1 创建助手
**端点**: `POST /v1/assistants`
**请求参数**:
– `name`: 助手名称(必填)
– `model`: 使用的模型(必填)
– `description`: 助手描述(可选)
– `instructions`: 助手指令(可选)
– `tools`: 助手可以使用的工具列表(可选)
– `metadata`: 自定义元数据(可选)
**响应**:
“`json
{
“id”: “asst_1234567890”,
“name”: “Customer Support Assistant”,
“model”: “gpt-4”,
“description”: “A helpful customer support assistant”,
“instructions”: “You are a customer support assistant. Help users with their questions and issues.”,
“tools”: [“web_search”, “calculator”],
“metadata”: {“department”: “support”},
“created_at”: “2024-03-08T12:00:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
url = “https://api.openclaw.com/v1/assistants”
headers = {
“Authorization”: f”Bearer {api_key}”,
“Content-Type”: “application/json”
}
payload = {
“name”: “Customer Support Assistant”,
“model”: “gpt-4”,
“description”: “A helpful customer support assistant”,
“instructions”: “You are a customer support assistant. Help users with their questions and issues.”,
“tools”: [“web_search”, “calculator”]
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
“`
### 3.2 获取助手
**端点**: `GET /v1/assistants/{assistant_id}`
**响应**:
“`json
{
“id”: “asst_1234567890”,
“name”: “Customer Support Assistant”,
“model”: “gpt-4”,
“description”: “A helpful customer support assistant”,
“instructions”: “You are a customer support assistant. Help users with their questions and issues.”,
“tools”: [“web_search”, “calculator”],
“metadata”: {“department”: “support”},
“created_at”: “2024-03-08T12:00:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
assistant_id = “asst_1234567890″
url = f”https://api.openclaw.com/v1/assistants/{assistant_id}”
headers = {
“Authorization”: f”Bearer {api_key}”
}
response = requests.get(url, headers=headers)
print(response.json())
“`
### 3.3 更新助手
**端点**: `PUT /v1/assistants/{assistant_id}`
**请求参数**:
– `name`: 助手名称(可选)
– `model`: 使用的模型(可选)
– `description`: 助手描述(可选)
– `instructions`: 助手指令(可选)
– `tools`: 助手可以使用的工具列表(可选)
– `metadata`: 自定义元数据(可选)
**响应**:
“`json
{
“id”: “asst_1234567890”,
“name”: “Updated Customer Support Assistant”,
“model”: “gpt-4-turbo”,
“description”: “An updated customer support assistant”,
“instructions”: “You are a customer support assistant. Help users with their questions and issues. Be friendly and professional.”,
“tools”: [“web_search”, “calculator”, “email_sender”],
“metadata”: {“department”: “support”, “version”: “2.0”},
“created_at”: “2024-03-08T12:00:00Z”,
“updated_at”: “2024-03-09T12:00:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
assistant_id = “asst_1234567890″
url = f”https://api.openclaw.com/v1/assistants/{assistant_id}”
headers = {
“Authorization”: f”Bearer {api_key}”,
“Content-Type”: “application/json”
}
payload = {
“name”: “Updated Customer Support Assistant”,
“model”: “gpt-4-turbo”,
“tools”: [“web_search”, “calculator”, “email_sender”]
}
response = requests.put(url, headers=headers, json=payload)
print(response.json())
“`
### 3.4 删除助手
**端点**: `DELETE /v1/assistants/{assistant_id}`
**响应**:
“`json
{
“id”: “asst_1234567890”,
“deleted”: true,
“object”: “assistant.deleted”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
assistant_id = “asst_1234567890″
url = f”https://api.openclaw.com/v1/assistants/{assistant_id}”
headers = {
“Authorization”: f”Bearer {api_key}”
}
response = requests.delete(url, headers=headers)
print(response.json())
“`
### 3.5 列出助手
**端点**: `GET /v1/assistants`
**查询参数**:
– `limit`: 每页返回的助手数量(可选,默认20)
– `offset`: 偏移量(可选,默认0)
– `order_by`: 排序字段(可选,默认created_at)
– `order`: 排序方向(可选,默认desc)
**响应**:
“`json
{
“object”: “list”,
“data”: [
{
“id”: “asst_1234567890”,
“name”: “Customer Support Assistant”,
“model”: “gpt-4”,
“description”: “A helpful customer support assistant”,
“created_at”: “2024-03-08T12:00:00Z”
},
{
“id”: “asst_0987654321”,
“name”: “Content Creation Assistant”,
“model”: “claude-3-opus”,
“description”: “An assistant for content creation”,
“created_at”: “2024-03-07T12:00:00Z”
}
],
“total”: 2,
“limit”: 20,
“offset”: 0
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
url = “https://api.openclaw.com/v1/assistants”
headers = {
“Authorization”: f”Bearer {api_key}”
}
params = {
“limit”: 10,
“offset”: 0
}
response = requests.get(url, headers=headers, params=params)
print(response.json())
“`
## 4. 对话管理API
### 4.1 创建对话
**端点**: `POST /v1/conversations`
**请求参数**:
– `assistant_id`: 助手ID(必填)
– `messages`: 初始消息列表(可选)
– `metadata`: 自定义元数据(可选)
**响应**:
“`json
{
“id”: “conv_1234567890”,
“assistant_id”: “asst_1234567890”,
“messages”: [],
“metadata”: {},
“created_at”: “2024-03-08T12:00:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
url = “https://api.openclaw.com/v1/conversations”
headers = {
“Authorization”: f”Bearer {api_key}”,
“Content-Type”: “application/json”
}
payload = {
“assistant_id”: “asst_1234567890”,
“messages”: [
{
“role”: “user”,
“content”: “Hello, how can I help you today?”
}
]
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
“`
### 4.2 获取对话
**端点**: `GET /v1/conversations/{conversation_id}`
**响应**:
“`json
{
“id”: “conv_1234567890”,
“assistant_id”: “asst_1234567890”,
“messages”: [
{
“id”: “msg_1234567890”,
“role”: “user”,
“content”: “Hello, how can I help you today?”,
“created_at”: “2024-03-08T12:00:00Z”
},
{
“id”: “msg_0987654321”,
“role”: “assistant”,
“content”: “I’m here to help you with any questions or issues you might have. What can I assist you with today?”,
“created_at”: “2024-03-08T12:00:05Z”
}
],
“metadata”: {},
“created_at”: “2024-03-08T12:00:00Z”,
“updated_at”: “2024-03-08T12:00:05Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
conversation_id = “conv_1234567890″
url = f”https://api.openclaw.com/v1/conversations/{conversation_id}”
headers = {
“Authorization”: f”Bearer {api_key}”
}
response = requests.get(url, headers=headers)
print(response.json())
“`
### 4.3 发送消息
**端点**: `POST /v1/conversations/{conversation_id}/messages`
**请求参数**:
– `role`: 角色(必填,”user”或”system”)
– `content`: 消息内容(必填)
– `attachments`: 附件列表(可选)
**响应**:
“`json
{
“id”: “msg_1234567890”,
“conversation_id”: “conv_1234567890”,
“role”: “user”,
“content”: “I need help with my order”,
“created_at”: “2024-03-08T12:01:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
conversation_id = “conv_1234567890″
url = f”https://api.openclaw.com/v1/conversations/{conversation_id}/messages”
headers = {
“Authorization”: f”Bearer {api_key}”,
“Content-Type”: “application/json”
}
payload = {
“role”: “user”,
“content”: “I need help with my order”
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
“`
### 4.4 生成回复
**端点**: `POST /v1/conversations/{conversation_id}/generate`
**请求参数**:
– `model`: 模型名称(可选,默认使用助手配置的模型)
– `tools`: 工具列表(可选,默认使用助手配置的工具)
– `temperature`: 温度参数(可选,默认0.7)
– `max_tokens`: 最大token数(可选)
**响应**:
“`json
{
“id”: “msg_0987654321”,
“conversation_id”: “conv_1234567890”,
“role”: “assistant”,
“content”: “I’d be happy to help you with your order. Could you please provide your order number so I can look it up?”,
“created_at”: “2024-03-08T12:01:05Z”,
“tool_calls”: []
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
conversation_id = “conv_1234567890″
url = f”https://api.openclaw.com/v1/conversations/{conversation_id}/generate”
headers = {
“Authorization”: f”Bearer {api_key}”,
“Content-Type”: “application/json”
}
payload = {
“temperature”: 0.5
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
“`
### 4.5 列出对话
**端点**: `GET /v1/conversations`
**查询参数**:
– `assistant_id`: 助手ID(可选)
– `limit`: 每页返回的对话数量(可选,默认20)
– `offset`: 偏移量(可选,默认0)
– `order_by`: 排序字段(可选,默认updated_at)
– `order`: 排序方向(可选,默认desc)
**响应**:
“`json
{
“object”: “list”,
“data”: [
{
“id”: “conv_1234567890”,
“assistant_id”: “asst_1234567890”,
“message_count”: 2,
“created_at”: “2024-03-08T12:00:00Z”,
“updated_at”: “2024-03-08T12:01:05Z”
},
{
“id”: “conv_0987654321”,
“assistant_id”: “asst_1234567890”,
“message_count”: 1,
“created_at”: “2024-03-07T12:00:00Z”,
“updated_at”: “2024-03-07T12:00:00Z”
}
],
“total”: 2,
“limit”: 20,
“offset”: 0
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
url = “https://api.openclaw.com/v1/conversations”
headers = {
“Authorization”: f”Bearer {api_key}”
}
params = {
“assistant_id”: “asst_1234567890”,
“limit”: 10
}
response = requests.get(url, headers=headers, params=params)
print(response.json())
“`
### 4.6 删除对话
**端点**: `DELETE /v1/conversations/{conversation_id}`
**响应**:
“`json
{
“id”: “conv_1234567890”,
“deleted”: true,
“object”: “conversation.deleted”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
conversation_id = “conv_1234567890″
url = f”https://api.openclaw.com/v1/conversations/{conversation_id}”
headers = {
“Authorization”: f”Bearer {api_key}”
}
response = requests.delete(url, headers=headers)
print(response.json())
“`
## 5. 工具管理API
### 5.1 注册工具
**端点**: `POST /v1/tools`
**请求参数**:
– `name`: 工具名称(必填)
– `description`: 工具描述(必填)
– `parameters`: 工具参数定义(必填)
– `function`: 工具函数实现(必填)
– `metadata`: 自定义元数据(可选)
**响应**:
“`json
{
“id”: “tool_1234567890”,
“name”: “weather”,
“description”: “Get weather information for a location”,
“parameters”: {
“type”: “object”,
“properties”: {
“location”: {
“type”: “string”,
“description”: “The location to get weather for”
}
},
“required”: [“location”]
},
“metadata”: {},
“created_at”: “2024-03-08T12:00:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
url = “https://api.openclaw.com/v1/tools”
headers = {
“Authorization”: f”Bearer {api_key}”,
“Content-Type”: “application/json”
}
payload = {
“name”: “weather”,
“description”: “Get weather information for a location”,
“parameters”: {
“type”: “object”,
“properties”: {
“location”: {
“type”: “string”,
“description”: “The location to get weather for”
}
},
“required”: [“location”]
},
“function”: “def run(params):\n location = params.get(‘location’)\n # Call weather API\n return {‘temperature’: 25, ‘condition’: ‘sunny’}”
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
“`
### 5.2 获取工具
**端点**: `GET /v1/tools/{tool_id}`
**响应**:
“`json
{
“id”: “tool_1234567890”,
“name”: “weather”,
“description”: “Get weather information for a location”,
“parameters”: {
“type”: “object”,
“properties”: {
“location”: {
“type”: “string”,
“description”: “The location to get weather for”
}
},
“required”: [“location”]
},
“metadata”: {},
“created_at”: “2024-03-08T12:00:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
tool_id = “tool_1234567890″
url = f”https://api.openclaw.com/v1/tools/{tool_id}”
headers = {
“Authorization”: f”Bearer {api_key}”
}
response = requests.get(url, headers=headers)
print(response.json())
“`
### 5.3 更新工具
**端点**: `PUT /v1/tools/{tool_id}`
**请求参数**:
– `description`: 工具描述(可选)
– `parameters`: 工具参数定义(可选)
– `function`: 工具函数实现(可选)
– `metadata`: 自定义元数据(可选)
**响应**:
“`json
{
“id”: “tool_1234567890”,
“name”: “weather”,
“description”: “Get detailed weather information for a location”,
“parameters”: {
“type”: “object”,
“properties”: {
“location”: {
“type”: “string”,
“description”: “The location to get weather for”
},
“units”: {
“type”: “string”,
“description”: “Units to use (metric or imperial)”,
“enum”: [“metric”, “imperial”]
}
},
“required”: [“location”]
},
“metadata”: {“version”: “2.0”},
“created_at”: “2024-03-08T12:00:00Z”,
“updated_at”: “2024-03-09T12:00:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
tool_id = “tool_1234567890″
url = f”https://api.openclaw.com/v1/tools/{tool_id}”
headers = {
“Authorization”: f”Bearer {api_key}”,
“Content-Type”: “application/json”
}
payload = {
“description”: “Get detailed weather information for a location”,
“parameters”: {
“type”: “object”,
“properties”: {
“location”: {
“type”: “string”,
“description”: “The location to get weather for”
},
“units”: {
“type”: “string”,
“description”: “Units to use (metric or imperial)”,
“enum”: [“metric”, “imperial”]
}
},
“required”: [“location”]
}
}
response = requests.put(url, headers=headers, json=payload)
print(response.json())
“`
### 5.4 删除工具
**端点**: `DELETE /v1/tools/{tool_id}`
**响应**:
“`json
{
“id”: “tool_1234567890”,
“deleted”: true,
“object”: “tool.deleted”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
tool_id = “tool_1234567890″
url = f”https://api.openclaw.com/v1/tools/{tool_id}”
headers = {
“Authorization”: f”Bearer {api_key}”
}
response = requests.delete(url, headers=headers)
print(response.json())
“`
### 5.5 列出工具
**端点**: `GET /v1/tools`
**查询参数**:
– `limit`: 每页返回的工具数量(可选,默认20)
– `offset`: 偏移量(可选,默认0)
– `order_by`: 排序字段(可选,默认created_at)
– `order`: 排序方向(可选,默认desc)
**响应**:
“`json
{
“object”: “list”,
“data”: [
{
“id”: “tool_1234567890”,
“name”: “weather”,
“description”: “Get weather information for a location”,
“created_at”: “2024-03-08T12:00:00Z”
},
{
“id”: “tool_0987654321”,
“name”: “calculator”,
“description”: “Perform mathematical calculations”,
“created_at”: “2024-03-07T12:00:00Z”
}
],
“total”: 2,
“limit”: 20,
“offset”: 0
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
url = “https://api.openclaw.com/v1/tools”
headers = {
“Authorization”: f”Bearer {api_key}”
}
params = {
“limit”: 10
}
response = requests.get(url, headers=headers, params=params)
print(response.json())
“`
## 6. 技能管理API
### 6.1 创建技能
**端点**: `POST /v1/skills`
**请求参数**:
– `name`: 技能名称(必填)
– `description`: 技能描述(必填)
– `tools`: 技能使用的工具列表(必填)
– `workflow`: 技能工作流定义(必填)
– `metadata`: 自定义元数据(可选)
**响应**:
“`json
{
“id”: “skill_1234567890”,
“name”: “trip_planner”,
“description”: “Plan a trip with weather and route information”,
“tools”: [“weather”, “maps”],
“workflow”: “def run(params):\n destination = params.get(‘destination’)\n # Get weather\n weather = tools[‘weather’].run({‘location’: destination})\n # Get route\n route = tools[‘maps’].run({‘destination’: destination})\n return {‘weather’: weather, ‘route’: route}”,
“metadata”: {},
“created_at”: “2024-03-08T12:00:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
url = “https://api.openclaw.com/v1/skills”
headers = {
“Authorization”: f”Bearer {api_key}”,
“Content-Type”: “application/json”
}
payload = {
“name”: “trip_planner”,
“description”: “Plan a trip with weather and route information”,
“tools”: [“weather”, “maps”],
“workflow”: “def run(params):\n destination = params.get(‘destination’)\n # Get weather\n weather = tools[‘weather’].run({‘location’: destination})\n # Get route\n route = tools[‘maps’].run({‘destination’: destination})\n return {‘weather’: weather, ‘route’: route}”
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
“`
### 6.2 获取技能
**端点**: `GET /v1/skills/{skill_id}`
**响应**:
“`json
{
“id”: “skill_1234567890”,
“name”: “trip_planner”,
“description”: “Plan a trip with weather and route information”,
“tools”: [“weather”, “maps”],
“workflow”: “def run(params):\n destination = params.get(‘destination’)\n # Get weather\n weather = tools[‘weather’].run({‘location’: destination})\n # Get route\n route = tools[‘maps’].run({‘destination’: destination})\n return {‘weather’: weather, ‘route’: route}”,
“metadata”: {},
“created_at”: “2024-03-08T12:00:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
skill_id = “skill_1234567890″
url = f”https://api.openclaw.com/v1/skills/{skill_id}”
headers = {
“Authorization”: f”Bearer {api_key}”
}
response = requests.get(url, headers=headers)
print(response.json())
“`
### 6.3 更新技能
**端点**: `PUT /v1/skills/{skill_id}`
**请求参数**:
– `description`: 技能描述(可选)
– `tools`: 技能使用的工具列表(可选)
– `workflow`: 技能工作流定义(可选)
– `metadata`: 自定义元数据(可选)
**响应**:
“`json
{
“id”: “skill_1234567890”,
“name”: “trip_planner”,
“description”: “Plan a comprehensive trip with weather, route, and accommodation information”,
“tools”: [“weather”, “maps”, “hotels”],
“workflow”: “def run(params):\n destination = params.get(‘destination’)\n # Get weather\n weather = tools[‘weather’].run({‘location’: destination})\n # Get route\n route = tools[‘maps’].run({‘destination’: destination})\n # Get hotels\n hotels = tools[‘hotels’].run({‘location’: destination})\n return {‘weather’: weather, ‘route’: route, ‘hotels’: hotels}”,
“metadata”: {“version”: “2.0”},
“created_at”: “2024-03-08T12:00:00Z”,
“updated_at”: “2024-03-09T12:00:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
skill_id = “skill_1234567890″
url = f”https://api.openclaw.com/v1/skills/{skill_id}”
headers = {
“Authorization”: f”Bearer {api_key}”,
“Content-Type”: “application/json”
}
payload = {
“description”: “Plan a comprehensive trip with weather, route, and accommodation information”,
“tools”: [“weather”, “maps”, “hotels”],
“workflow”: “def run(params):\n destination = params.get(‘destination’)\n # Get weather\n weather = tools[‘weather’].run({‘location’: destination})\n # Get route\n route = tools[‘maps’].run({‘destination’: destination})\n # Get hotels\n hotels = tools[‘hotels’].run({‘location’: destination})\n return {‘weather’: weather, ‘route’: route, ‘hotels’: hotels}”
}
response = requests.put(url, headers=headers, json=payload)
print(response.json())
“`
### 6.4 删除技能
**端点**: `DELETE /v1/skills/{skill_id}`
**响应**:
“`json
{
“id”: “skill_1234567890”,
“deleted”: true,
“object”: “skill.deleted”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
skill_id = “skill_1234567890″
url = f”https://api.openclaw.com/v1/skills/{skill_id}”
headers = {
“Authorization”: f”Bearer {api_key}”
}
response = requests.delete(url, headers=headers)
print(response.json())
“`
### 6.5 列出技能
**端点**: `GET /v1/skills`
**查询参数**:
– `limit`: 每页返回的技能数量(可选,默认20)
– `offset`: 偏移量(可选,默认0)
– `order_by`: 排序字段(可选,默认created_at)
– `order`: 排序方向(可选,默认desc)
**响应**:
“`json
{
“object”: “list”,
“data”: [
{
“id”: “skill_1234567890”,
“name”: “trip_planner”,
“description”: “Plan a trip with weather and route information”,
“created_at”: “2024-03-08T12:00:00Z”
},
{
“id”: “skill_0987654321”,
“name”: “content_creator”,
“description”: “Create content for various platforms”,
“created_at”: “2024-03-07T12:00:00Z”
}
],
“total”: 2,
“limit”: 20,
“offset”: 0
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
url = “https://api.openclaw.com/v1/skills”
headers = {
“Authorization”: f”Bearer {api_key}”
}
params = {
“limit”: 10
}
response = requests.get(url, headers=headers, params=params)
print(response.json())
“`
## 7. 模型管理API
### 7.1 列出可用模型
**端点**: `GET /v1/models`
**查询参数**:
– `provider`: 模型提供商(可选)
– `limit`: 每页返回的模型数量(可选,默认20)
– `offset`: 偏移量(可选,默认0)
**响应**:
“`json
{
“object”: “list”,
“data”: [
{
“id”: “gpt-4”,
“name”: “GPT-4”,
“provider”: “openai”,
“context_window”: 8192,
“description”: “OpenAI’s most capable model”
},
{
“id”: “claude-3-opus”,
“name”: “Claude 3 Opus”,
“provider”: “anthropic”,
“context_window”: 200000,
“description”: “Anthropic’s most powerful model”
},
{
“id”: “gemini-pro”,
“name”: “Gemini Pro”,
“provider”: “google”,
“context_window”: 32768,
“description”: “Google’s Gemini Pro model”
}
],
“total”: 3,
“limit”: 20,
“offset”: 0
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
url = “https://api.openclaw.com/v1/models”
headers = {
“Authorization”: f”Bearer {api_key}”
}
params = {
“provider”: “openai”
}
response = requests.get(url, headers=headers, params=params)
print(response.json())
“`
### 7.2 获取模型详情
**端点**: `GET /v1/models/{model_id}`
**响应**:
“`json
{
“id”: “gpt-4”,
“name”: “GPT-4”,
“provider”: “openai”,
“context_window”: 8192,
“max_output_tokens”: 4096,
“temperature_range”: [0, 2],
“description”: “OpenAI’s most capable model”,
“capabilities”: [“text”, “vision”, “code”],
“pricing”: {
“input”: 0.03,
“output”: 0.06
}
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
model_id = “gpt-4″
url = f”https://api.openclaw.com/v1/models/{model_id}”
headers = {
“Authorization”: f”Bearer {api_key}”
}
response = requests.get(url, headers=headers)
print(response.json())
“`
## 8. 记忆管理API
### 8.1 添加记忆
**端点**: `POST /v1/memories`
**请求参数**:
– `assistant_id`: 助手ID(可选)
– `content`: 记忆内容(必填)
– `type`: 记忆类型(可选,默认”general”)
– `metadata`: 自定义元数据(可选)
**响应**:
“`json
{
“id”: “mem_1234567890”,
“assistant_id”: “asst_1234567890”,
“content”: “User prefers Italian food”,
“type”: “preference”,
“metadata”: {“category”: “food”},
“created_at”: “2024-03-08T12:00:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
url = “https://api.openclaw.com/v1/memories”
headers = {
“Authorization”: f”Bearer {api_key}”,
“Content-Type”: “application/json”
}
payload = {
“assistant_id”: “asst_1234567890”,
“content”: “User prefers Italian food”,
“type”: “preference”,
“metadata”: {“category”: “food”}
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
“`
### 8.2 检索记忆
**端点**: `GET /v1/memories`
**查询参数**:
– `assistant_id`: 助手ID(可选)
– `query`: 检索查询(可选)
– `type`: 记忆类型(可选)
– `limit`: 每页返回的记忆数量(可选,默认20)
– `offset`: 偏移量(可选,默认0)
**响应**:
“`json
{
“object”: “list”,
“data”: [
{
“id”: “mem_1234567890”,
“assistant_id”: “asst_1234567890”,
“content”: “User prefers Italian food”,
“type”: “preference”,
“metadata”: {“category”: “food”},
“created_at”: “2024-03-08T12:00:00Z”
},
{
“id”: “mem_0987654321”,
“assistant_id”: “asst_1234567890”,
“content”: “User lives in Beijing”,
“type”: “location”,
“metadata”: {“category”: “personal”},
“created_at”: “2024-03-07T12:00:00Z”
}
],
“total”: 2,
“limit”: 20,
“offset”: 0
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
url = “https://api.openclaw.com/v1/memories”
headers = {
“Authorization”: f”Bearer {api_key}”
}
params = {
“assistant_id”: “asst_1234567890”,
“query”: “food preferences”,
“limit”: 10
}
response = requests.get(url, headers=headers, params=params)
print(response.json())
“`
### 8.3 删除记忆
**端点**: `DELETE /v1/memories/{memory_id}`
**响应**:
“`json
{
“id”: “mem_1234567890”,
“deleted”: true,
“object”: “memory.deleted”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
memory_id = “mem_1234567890″
url = f”https://api.openclaw.com/v1/memories/{memory_id}”
headers = {
“Authorization”: f”Bearer {api_key}”
}
response = requests.delete(url, headers=headers)
print(response.json())
“`
## 9. 工作流管理API
### 9.1 创建工作流
**端点**: `POST /v1/workflows`
**请求参数**:
– `name`: 工作流名称(必填)
– `description`: 工作流描述(必填)
– `tasks`: 工作流任务列表(必填)
– `metadata`: 自定义元数据(可选)
**响应**:
“`json
{
“id”: “wf_1234567890”,
“name”: “customer_support”,
“description”: “Customer support workflow”,
“tasks”: [
{
“id”: “task_1”,
“name”: “analyze_query”,
“tool”: “text_analyzer”,
“dependencies”: []
},
{
“id”: “task_2”,
“name”: “find_solution”,
“tool”: “web_search”,
“dependencies”: [“task_1”]
},
{
“id”: “task_3”,
“name”: “generate_response”,
“tool”: “content_creator”,
“dependencies”: [“task_2”]
}
],
“metadata”: {},
“created_at”: “2024-03-08T12:00:00Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
url = “https://api.openclaw.com/v1/workflows”
headers = {
“Authorization”: f”Bearer {api_key}”,
“Content-Type”: “application/json”
}
payload = {
“name”: “customer_support”,
“description”: “Customer support workflow”,
“tasks”: [
{
“id”: “task_1”,
“name”: “analyze_query”,
“tool”: “text_analyzer”,
“dependencies”: []
},
{
“id”: “task_2”,
“name”: “find_solution”,
“tool”: “web_search”,
“dependencies”: [“task_1”]
},
{
“id”: “task_3”,
“name”: “generate_response”,
“tool”: “content_creator”,
“dependencies”: [“task_2”]
}
]
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
“`
### 9.2 执行工作流
**端点**: `POST /v1/workflows/{workflow_id}/execute`
**请求参数**:
– `input`: 工作流输入数据(必填)
– `context`: 工作流上下文(可选)
**响应**:
“`json
{
“id”: “exec_1234567890”,
“workflow_id”: “wf_1234567890”,
“status”: “completed”,
“input”: {
“query”: “I need help with my order”
},
“output”: {
“analysis”: {“intent”: “order_status”},
“solution”: “Check order status at https://example.com/orders”,
“response”: “I’d be happy to help you with your order. You can check the status of your order at https://example.com/orders or provide your order number and I can look it up for you.”
},
“created_at”: “2024-03-08T12:00:00Z”,
“completed_at”: “2024-03-08T12:00:05Z”
}
“`
**使用示例**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
workflow_id = “wf_1234567890″
url = f”https://api.openclaw.com/v1/workflows/{workflow_id}/execute”
headers = {
“Authorization”: f”Bearer {api_key}”,
“Content-Type”: “application/json”
}
payload = {
“input”: {
“query”: “I need help with my order”
}
}
response = requests.post(url, headers=headers, json=payload)
print(response.json())
“`
## 10. API最佳实践
### 10.1 认证安全
– **保护API密钥**: 不要在代码中硬编码API密钥
– **使用环境变量**: 将API密钥存储在环境变量中
– **定期轮换密钥**: 定期更新API密钥
– **限制权限**: 为API密钥设置适当的权限范围
### 10.2 请求优化
– **批量处理**: 批量处理请求以减少API调用次数
– **缓存响应**: 缓存频繁使用的响应
– **合理设置超时**: 设置合理的请求超时时间
– **错误处理**: 妥善处理API错误和异常
### 10.3 性能优化
– **选择合适的模型**: 根据任务选择合适的模型
– **优化提示词**: 编写高效的提示词
– **控制上下文长度**: 合理控制上下文长度
– **使用流式响应**: 对于长响应使用流式输出
### 10.4 监控与调试
– **日志记录**: 记录API调用和响应
– **监控指标**: 监控API调用频率和响应时间
– **错误跟踪**: 跟踪和分析API错误
– **性能分析**: 分析API性能瓶颈
## 11. 常见问题与故障排除
### 11.1 认证错误
**问题**: 收到401 Unauthorized错误
**解决方案**:
– 检查API密钥是否正确
– 检查API密钥是否过期
– 检查API密钥是否有足够的权限
### 11.2 速率限制
**问题**: 收到429 Too Many Requests错误
**解决方案**:
– 减少API调用频率
– 实现指数退避重试
– 考虑使用批量处理
– 联系OpenClaw支持增加速率限制
### 11.3 模型错误
**问题**: 收到模型相关错误
**解决方案**:
– 检查模型名称是否正确
– 检查模型是否支持请求的功能
– 检查输入是否符合模型要求
– 减少输入长度或复杂度
### 11.4 工具执行错误
**问题**: 工具执行失败
**解决方案**:
– 检查工具参数是否正确
– 检查工具依赖是否满足
– 检查工具是否有足够的权限
– 查看工具执行日志
## 12. 示例应用
### 12.1 客户服务助手
**功能**: 处理客户咨询和问题
**API调用流程**:
1. 创建客户服务助手
2. 创建对话
3. 发送客户消息
4. 生成助手回复
5. 处理工具调用(如果需要)
6. 完成对话
**示例代码**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
base_url = “https://api.openclaw.com/v1″
# 创建客户服务助手
assistant_response = requests.post(
f”{base_url}/assistants”,
headers={“Authorization”: f”Bearer {api_key}”, “Content-Type”: “application/json”},
json={
“name”: “Customer Support Assistant”,
“model”: “gpt-4”,
“instructions”: “You are a customer support assistant. Help users with their questions and issues.”,
“tools”: [“web_search”, “calculator”]
}
)
assistant_id = assistant_response.json()[“id”]
# 创建对话
conversation_response = requests.post(
f”{base_url}/conversations”,
headers={“Authorization”: f”Bearer {api_key}”, “Content-Type”: “application/json”},
json={“assistant_id”: assistant_id}
)
conversation_id = conversation_response.json()[“id”]
# 发送客户消息
message_response = requests.post(
f”{base_url}/conversations/{conversation_id}/messages”,
headers={“Authorization”: f”Bearer {api_key}”, “Content-Type”: “application/json”},
json={“role”: “user”, “content”: “I need help with my order”}
)
# 生成助手回复
generate_response = requests.post(
f”{base_url}/conversations/{conversation_id}/generate”,
headers={“Authorization”: f”Bearer {api_key}”, “Content-Type”: “application/json”},
json={}
)
assistant_message = generate_response.json()
print(“Assistant response:”, assistant_message[“content”])
“`
### 12.2 内容创作助手
**功能**: 生成各种类型的内容
**API调用流程**:
1. 创建内容创作助手
2. 创建对话
3. 发送内容需求
4. 生成内容
5. 调整和优化内容
**示例代码**:
“`python
import requests
api_key = “sk-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx”
base_url = “https://api.openclaw.com/v1″
# 创建内容创作助手
assistant_response = requests.post(
f”{base_url}/assistants”,
headers={“Authorization”: f”Bearer {api_key}”, “Content-Type”: “application/json”},
json={
“name”: “Content Creation Assistant”,
“model”: “claude-3-opus”,
“instructions”: “You are a content creation assistant. Generate high-quality content for various platforms.”,
“tools”: [“web_search”, “content_analyzer”]
}
)
assistant_id = assistant_response.json()[“id”]
# 创建对话
conversation_response = requests.post(
f”{base_url}/conversations”,
headers={“Authorization”: f”Bearer {api_key}”, “Content-Type”: “application/json”},
json={“assistant_id”: assistant_id}
)
conversation_id = conversation_response.json()[“id”]
# 发送内容需求
message_response = requests.post(
f”{base_url}/conversations/{conversation_id}/messages”,
headers={“Authorization”: f”Bearer {api_key}”, “Content-Type”: “application/json”},
json={“role”: “user”, “content”: “Write a blog post about the benefits of AI in healthcare”}
)
# 生成内容
generate_response = requests.post(
f”{base_url}/conversations/{conversation_id}/generate”,
headers={“Authorization”: f”Bearer {api_key}”, “Content-Type”: “application/json”},
json={“temperature”: 0.7}
)
assistant_message = generate_response.json()
print(“Generated content:”, assistant_message[“content”])
“`
## 13. 结论与建议
### 13.1 总结
OpenClaw API提供了一套完整的接口,允许开发者通过HTTP请求与OpenClaw进行交互。从助手管理到对话管理,从工具管理到技能管理,OpenClaw API覆盖了OpenClaw的所有核心功能。
### 13.2 建议
– **阅读文档**: 详细阅读API文档,了解每个端点的功能和参数
– **测试API**: 在开发环境中测试API,确保理解其行为
– **使用SDK**: 考虑使用OpenClaw SDK,简化API调用
– **错误处理**: 实现完善的错误处理机制
– **监控使用**: 监控API使用情况,避免超出速率限制
### 13.3 未来展望
OpenClaw API将不断发展和完善,为开发者提供更多功能和更好的体验。未来的API版本可能会包括更多高级功能,如多模态支持、实时语音交互、更复杂的工作流等。
—
通过本文的介绍,开发者可以了解OpenClaw API的使用方法和最佳实践,从而更好地集成和使用OpenClaw。无论是构建客户服务助手、内容创作助手还是其他类型的智能助手,OpenClaw API都能提供强大的支持,帮助开发者快速实现各种应用场景。