技术文档中心
全面的开发指南、API文档与最佳实践,助您轻松集成川意科技的产品和服务
开发工具包 (SDK)
川意科技提供多种编程语言的SDK(软件开发工具包),帮助开发者快速集成我们的API和服务。这些SDK封装了底层的API调用,提供了符合各语言习惯的接口,简化了认证、请求和错误处理等常见操作。
选择SDK
Node.js SDK
安装
使用npm安装:
npm install @chuanyi-tech/sdk
或使用yarn安装:
yarn add @chuanyi-tech/sdk
基本用法
初始化SDK客户端:
// ESM
import { ChuanyiSDK } from '@chuanyi-tech/sdk';
// CommonJS
// const { ChuanyiSDK } = require('@chuanyi-tech/sdk');
// 初始化客户端实例
const client = new ChuanyiSDK({
apiKey: 'YOUR_API_KEY',
region: 'cn-east', // 可选,默认'cn-east'
timeout: 10000, // 可选,超时时间(毫秒),默认10000
retries: 3 // 可选,重试次数,默认3
});
调用API示例:
// 文本分析示例
async function analyzeText() {
try {
const result = await client.analysis.text.sentiment({
text: "这家餐厅的服务态度非常好,菜品也很美味,价格合理。",
options: {
detailed: true
}
});
console.log(result);
// {
// sentiment: "positive",
// confidence: 0.85,
// details: { ... }
// }
} catch (error) {
console.error('分析失败:', error);
}
}
// 图像分析示例
async function detectObjects(imageUrl) {
try {
const result = await client.analysis.image.objectDetection({
imageUrl,
minConfidence: 0.6
});
console.log(`检测到 ${result.objects.length} 个对象`);
console.log(result.objects);
} catch (error) {
console.error('检测失败:', error);
}
}
// 数据处理示例
async function transformData(data) {
try {
const result = await client.data.transform({
data,
sourceFormat: 'json',
targetFormat: 'csv',
mappings: [
{ source: 'user_id', target: 'id' },
{ source: 'user_name', target: 'name' }
]
});
console.log(result.result); // CSV 格式数据
} catch (error) {
console.error('转换失败:', error);
}
}
TypeScript支持
SDK包含完整的TypeScript类型定义,提供良好的代码提示和类型检查。无需额外安装类型定义包。
高级特性
错误处理
try {
const result = await client.analysis.text.sentiment({
text: "" // 空文本会导致错误
});
} catch (error) {
if (error.code === 'INVALID_PARAMETER') {
console.error('参数错误:', error.message);
} else if (error.code === 'RATE_LIMIT_EXCEEDED') {
console.error('超出API调用限制,请稍后重试');
} else if (error.code === 'AUTHENTICATION_ERROR') {
console.error('认证失败,请检查您的API密钥');
} else {
console.error('未知错误:', error);
}
}
自定义请求配置
// 全局自定义请求头
client.setDefaultHeaders({
'X-Custom-Header': 'value'
});
// 单次请求自定义配置
const result = await client.analysis.text.sentiment({
text: "示例文本"
}, {
headers: { 'X-Request-ID': 'unique-id-123' },
timeout: 5000, // 覆盖默认超时时间
retries: 1 // 覆盖默认重试次数
});
批量处理
// 批量文本情感分析
const texts = [
"这家餐厅的服务很好",
"这个产品质量太差了",
"价格合理,性价比高"
];
const results = await client.analysis.text.batchSentiment({
texts,
options: { detailed: true }
});
// 结果为数组,对应每个输入文本的分析结果
results.forEach((result, index) => {
console.log(`文本 ${index + 1}:${texts[index]}`);
console.log(`情感:${result.sentiment},置信度:${result.confidence}`);
});
Python SDK
安装
使用pip安装:
pip install chuanyi-tech-sdk
或使用poetry安装:
poetry add chuanyi-tech-sdk
基本用法
初始化SDK客户端:
from chuanyi_tech_sdk import ChuanyiSDK
# 初始化客户端实例
client = ChuanyiSDK(
api_key="YOUR_API_KEY",
region="cn-east", # 可选,默认'cn-east'
timeout=10.0, # 可选,超时时间(秒),默认10.0
retries=3 # 可选,重试次数,默认3
)
调用API示例:
# 文本分析示例
def analyze_text():
try:
result = client.analysis.text.sentiment(
text="这家餐厅的服务态度非常好,菜品也很美味,价格合理。",
options={"detailed": True}
)
print(result)
# {
# "sentiment": "positive",
# "confidence": 0.85,
# "details": { ... }
# }
except Exception as e:
print(f"分析失败: {e}")
# 图像分析示例
def detect_objects(image_url):
try:
result = client.analysis.image.object_detection(
image_url=image_url,
min_confidence=0.6
)
print(f"检测到 {len(result['objects'])} 个对象")
print(result["objects"])
except Exception as e:
print(f"检测失败: {e}")
# 数据处理示例
def transform_data(data):
try:
result = client.data.transform(
data=data,
source_format="json",
target_format="csv",
mappings=[
{"source": "user_id", "target": "id"},
{"source": "user_name", "target": "name"}
]
)
print(result["result"]) # CSV 格式数据
except Exception as e:
print(f"转换失败: {e}")
# 使用异步API (需要Python 3.7+)
import asyncio
async def analyze_text_async():
try:
result = await client.analysis.text.sentiment_async(
text="这家餐厅的服务态度非常好,菜品也很美味,价格合理。",
options={"detailed": True}
)
print(result)
except Exception as e:
print(f"分析失败: {e}")
# 运行异步函数
asyncio.run(analyze_text_async())
类型提示支持
SDK提供完整的类型提示,支持Python的类型注解系统,兼容mypy和其他类型检查工具。
高级特性
错误处理
from chuanyi_tech_sdk.exceptions import (
ChuanyiAPIError,
InvalidParameterError,
AuthenticationError,
RateLimitExceededError
)
try:
result = client.analysis.text.sentiment(
text="" # 空文本会导致错误
)
except InvalidParameterError as e:
print(f"参数错误: {e}")
except RateLimitExceededError:
print("超出API调用限制,请稍后重试")
except AuthenticationError:
print("认证失败,请检查您的API密钥")
except ChuanyiAPIError as e:
print(f"API错误 (错误代码: {e.code}): {e.message}")
except Exception as e:
print(f"未知错误: {e}")
自定义请求配置
# 全局自定义请求头
client.set_default_headers({
"X-Custom-Header": "value"
})
# 单次请求自定义配置
result = client.analysis.text.sentiment(
text="示例文本",
request_options={
"headers": {"X-Request-ID": "unique-id-123"},
"timeout": 5.0, # 覆盖默认超时时间
"retries": 1 # 覆盖默认重试次数
}
)
批量处理
# 批量文本情感分析
texts = [
"这家餐厅的服务很好",
"这个产品质量太差了",
"价格合理,性价比高"
]
# 同步调用
results = client.analysis.text.batch_sentiment(
texts=texts,
options={"detailed": True}
)
# 结果为列表,对应每个输入文本的分析结果
for i, result in enumerate(results):
print(f"文本 {i+1}: {texts[i]}")
print(f"情感: {result['sentiment']}, 置信度: {result['confidence']}")
# 异步批量处理
async def process_batch_async():
results = await client.analysis.text.batch_sentiment_async(
texts=texts,
options={"detailed": True}
)
return results
batch_results = asyncio.run(process_batch_async())