AI API 使开发人员能够访问强大的预训练模型,而无需深入的机器学习知识。本文概述了用于人工智能的最常用 API。我们来看看如何在您的项目中有效地使用它们。
在本文中,我们将考虑:
OpenAI 应用程序接口 · ·人类学 · ·Google Vertex AI · ·AWS 基岩 · ·格罗克 · ·大脑
为什么要使用 API for AI?
-
节省开发时间:您可以立即开始使用高级 AI,而不是花费数月时间训练自己的模型。
-
轻松添加高级功能:只需几个 API 请求即可实现自然语言处理、图像识别或预测分析等复杂功能。
-
模型会自动改进:当 API 提供程序更新模型时,应用程序无需您执行任何额外作即可接收这些改进。
-
成本效益:在大多数情况下,使用 API 比构建和维护自己的 AI 基础设施便宜得多。
-
专注于核心产品:通过将复杂 AI 任务的处理外包给外部服务,您可以专注于开发应用程序的独特方面。
热门 API
OpenAI API
OpenAI API
OpenAI 的 API 提供对各种语言模型的访问,包括它们的 o1 和 o3 迷你推理模型。这些模型旨在通过改进功能解决各种自然语言问题。
特征:
-
高级文本生成和添加。
-
改进的推理和任务执行能力。
-
增强的多语言工作功能。
-
用于针对特定情况微调模型的选项。
以下是如何使用此 API 的示例:
const { Configuration, OpenAIApi } = require("openai");
const configuration = new Configuration({
apiKey: process.env.OPENAI_API_KEY,
});
const openai = new OpenAIApi(configuration);
async function generateBlogOutline(topic) {
const completion = await openai.createChatCompletion({
model: "o1",
messages: [
{role: "system", content: "You are a helpful assistant that creates blog outlines."},
{role: "user", content: Create an outline for a blog post about ${topic}
}
],
});
console.log(completion.data.choices[0].message.content);
}
generateBlogOutline("The future of remote work");
定价: OpenAI 使用按代币付费的模式。有关最新的定价信息,请参阅官方定价页面。价格可能因具体型号和使用量而异。
注意:o1 型号的定价结构可能与以前的版本不同。在将 API 集成到您的项目中之前,请务必查看官方定价页面以获取最新信息。
人
人
Anthropic 最近发布了 Claude 3.7 Sonnet,这是其迄今为止的最新模型。这种混合推理模型显著提高了编程、内容生成、数据分析和规划的能力。
特征:
-
改进了推理和执行任务的能力。
-
高级编程功能。
-
卷为 200,000 个令牌的上下文窗口。
-
计算机交互功能(在 beta 模式下)。
-
适用于复杂任务的高级思维模式。
用例:创建 AI 助手进行研究。
const Anthropic = require('@anthropic-ai/sdk');
const anthropic = new Anthropic({
apiKey: 'your-api-key',
});
async function researchTopic(topic) {
const prompt = `Human: Provide a comprehensive overview of the latest research on ${topic}.
Include key findings, methodologies, and potential future directions.
Assistant: Certainly! I'll provide an overview of the latest research on ${topic}. Here's a summary of key findings, methodologies, and future directions:
1. Key Findings:
`;
const response = await anthropic.completions.create({
model: 'claude-3.7-sonnet',
prompt: prompt,
max_tokens_to_sample: 1000,
});
return response.completion;
}
researchTopic("quantum computing")
.then(researchSummary => console.log(researchSummary))
.catch(error => console.error('Error:', error));
定价: 截至 2025 年 4 月,Claude 3.7 Sonnet 的起价为每百万个输入令牌 3 美元和每百万个输出令牌 15 美元。通过快速缓存最多可节省 90% 的费用,在批处理方面最多可节省 50%。最新的详细定价信息,包括折扣和特别优惠,可以在 Anthropic 官方页面上找到。
Claude 3.7 Sonnet 结合了尖端功能和有竞争力的价格,使其成为 AI API 市场的强大参与者。它特别适合编程、内容生成和数据分析等复杂任务。该模型可通过 Anthropic API、Amazon Bedrock 和 Google Cloud Vertex AI 获得。
谷歌顶点人工智能
Vertex AI 是 Google 的一个机器学习平台,提供广泛的 AI 和 ML 服务。
特征:
-
访问多个模型,包括 Google 自己的模型(例如 Gemini Flash 2.0)和第三方解决方案(例如 Claude)。
-
与其他 Google Cloud 服务紧密集成。
-
用于训练自定义模型的 AutoML 功能。
使用案例:客户评论的情绪分析。
const aiplatform = require('@google-cloud/aiplatform');
async function analyzeSentiment(text) {
const {PredictionServiceClient} = aiplatform.v1;
const client = new PredictionServiceClient({apiEndpoint: 'us-central1-aiplatform.googleapis.com'});
const instance = {
content: text,
};
const instances = [instance];
const parameters = {
confidenceThreshold: 0.5,
maxPredictions: 1,
};
const endpoint = client.endpointPath(
'your-project',
'us-central1',
'your-endpoint-id'
);
const [response] = await client.predict({
endpoint,
instances,
parameters,
});
return response.predictions[0];
}
analyzeSentiment("I absolutely love this product! It's amazing!")
.then(sentiment => console.log(sentiment))
.catch(error => console.error('Error:', error));
定价:Vertex AI 使用即用即付模型进行预测。定价基于使用的计算节点的小时数。定价因区域和机器类型而异。有关最新详细信息,包括不同机器类型和区域的费率,请访问官方页面。
注意:Vertex AI Prediction 无法扩展到零节点,因此部署的模型始终存在最低费用。预测批处理作业在完成后计费,而不是分阶段计费。
AWS 基岩版
AWS 基岩版
AWS Bedrock 提供单个 API,用于访问来自不同供应商的各种预训练模型。
特征:
-
访问来自 Anthropic、AI21 Labs、Cohere 和 Amazon 的模型。
-
与其他 AWS 服务无缝集成。
-
微调和自定义选项。
用例:创建多语言聊天机器人。
const AWS = require('aws-sdk');
// Configure AWS SDK
AWS.config.update({region: 'your-region'});
const bedrock = new AWS.BedrockRuntime();
async function translateAndRespond(userInput, targetLanguage) {
const prompt = `Human: Translate the following text to ${targetLanguage} and then respond to it:
${userInput}
Assistant: Certainly! I'll translate the text and then respond to it in ${targetLanguage}.
Translation:
`;
const params = {
modelId: 'anthropic.claude-v2',
contentType: 'application/json',
accept: 'application/json',
body: JSON.stringify({
prompt: prompt,
max_tokens_to_sample: 300,
temperature: 0.7,
top_p: 1,
stop_sequences: ["nnHuman:"]
})
};
try {
const response = await bedrock.invokeModel(params).promise();
const responseBody = JSON.parse(response.body);
return responseBody.completion;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
translateAndRespond("What's the weather like today?", "French")
.then(result => console.log(result))
.catch(error => console.error('Error:', error));
定价:AWS Bedrock 的定价模型提供了使用不同 AI 模型的灵活性,同时维护单个 API,从而可以轻松试验不同的解决方案并在必要时更换提供商。当前的定价计划可在 AWS Bedrock 官方页面上找到。
快速推理选项
Groq 和 Cerebras 为开源模型提供了令人印象深刻的性能提升,使开发人员能够以以前无法达到的速度运行流行的开源模型。
格罗克
格罗克
Groq 是一家开发 AI 硬件的公司,用于大型语言模型的高速推理(推理)。它由前 Google TPU 架构师 Jonathan Ross 创立。Groq 开发了一种称为语言处理单元 (LPU) 的独特架构,专门针对特定于自然语言处理的顺序计算任务进行了优化。
基于 LPU 的推理平台具有以下几个主要优势:
-
确定性性能:与传统 GPU 不同,Groq 的 LPU 提供一致且可预测的性能,而不受输入数据的影响,这对于实时应用程序至关重要。
-
低延迟:Groq 架构针对低延迟进行了优化,即使在使用复杂语言模型时,通常也能实现小于 100 毫秒的响应时间。
-
能效:与许多 GPU 解决方案相比,LPU 的设计特点提供了高性能和更低的功耗。
-
可扩展性:Groq 基础设施旨在随着负载的增加而扩展而不会牺牲性能。
Groq 提供对各种流行的开源模型的访问,包括 LLaMA 变体、Mixtral 和其他高级语言模型。该平台特别适合需要即时响应的应用程序,例如实时聊天机器人、代码完成工具和交互式 AI 助手。
特征:
-
极低的延迟(通常为 <100 毫秒)。
-
支持流行的开源模型。
-
与现有工作流程轻松集成。
用例:实时代码补全。
const Groq = require('groq-sdk');
const client = new Groq({
apiKey: "your-api-key"
});
async function completeCode(codeSnippet) {
try {
const chatCompletion = await client.chat.completions.create({
messages: [
{
role: "system",
content: "You are a helpful coding assistant. Complete the given code snippet."
},
{
role: "user",
content: Complete this code:nn${codeSnippet}
}
],
model: "llama2-70b-4096",
max_tokens: 100
});
return chatCompletion.choices[0].message.content;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
const code = "def fibonacci(n):n if n console.log(completedCode))
.catch(error => console.error('Error:', error));
定价: Groq 使用按代币付费的模式,成本取决于具体模型和输入/输出数据量。图像和语音处理模型也可用,单独收费。最新的详细定价信息,包括不同模型和功能的费率,可以在 Groq 官方页面上找到。
Cerebras 公司
Cerebras 公司
Cerebras 是另一家以开发晶圆级引擎 (WSE) 而闻名的 AI 硬件公司,这是有史以来最大的芯片。他们的 CS-2 系统由 WSE-2 提供支持,旨在显着加速 AI 计算。
Cerebras 技术的主要特点:
-
大容量板载内存:WSE-2 直接在芯片上包含 40 GB 内存,减少了数据移动的需求并提高了效率。
-
快速数据传输:Cerebras 系统具有每秒 220 PB 的内存带宽,能够快速处理复杂的 AI 模型。
-
可扩展性:Cerebras 技术专为单模型和大型多集群部署而设计。
-
模型支持:该系统能够运行各种大型语言模型,包括开源变体。
Cerebras 提供对其计算能力的基于云的访问,使开发人员能够使用高性能硬件来训练和推理模型,而无需在自己的服务器上托管。
特征:
-
批处理中的高吞吐量
-
支持部署自定义模型
-
企业级可扩展性
案例研究:文本的批量分类。
// Note: This is a conceptual example
const CerebrasApi = require('cerebras-api');
const client = new CerebrasApi('your-api-key');
async function classifyTexts(texts) {
try {
const responses = await client.batchClassify({
model: "cerebras-gpt-13b",
texts: texts,
categories: ["Technology", "Sports", "Politics", "Entertainment"]
});
return responses;
} catch (error) {
console.error('Error:', error);
throw error;
}
}
const articles = [
"Apple announces new iPhone model",
"Lakers win NBA championship",
"Senate passes new climate bill"
];
classifyTexts(articles)
.then(classifications => {
articles.forEach((text, index) => {
console.log(Text: ${text}nClassification: ${classifications[index]}n
);
});
})
.catch(error => console.error('Error:', error));
定价: Cerebras 通常根据使用量和具体要求提供定制条件。
选择 API
选择 API 时,请考虑以下因素:
-
所需功能:API 是否支持您需要的 AI 功能?
-
成本:价格如何符合您的预算和估计负载?
-
文档质量:API 是否有据可查,集成起来的难易程度如何?
-
可扩展性:API 能否处理您的潜在增长?
-
延迟要求:您需要实时响应还是可以接受延迟?
-
数据隐私:API 提供商如何处理数据,是否符合当前的监管要求?
-
定制选项:模型可以根据您的具体情况进行微调或调整吗?
-
社区和支持:是否有活跃的开发人员社区和提供商提供的可靠支持?
使用 AI API 的提示
-
确保 API 密钥安全:使用环境变量或安全存储,切勿对密钥进行硬编码。
-
监控使用情况:针对请求的异常峰值设置警报,以避免意外成本。
-
控制您的请求速率:遵守 API 限制并实施您自己的速率限制机制以防止拥塞。
-
规划错误处理:始终实施错误处理,以防 API 不可用或响应不可预测。
-
缓存响应:对于静态请求,使用缓存来减少 API 调用次数并提高性能。
-
请继续关注:阅读提供商的更新日志并定期更新集成以利用新功能和改进。
-
优化提示:对于语言模型,正确的查询措辞可以显著改善结果并减少标记的数量。
用于统一访问 AI API 的 AI SDK
AI 开发工具包
AI SDK 为与多个 AI 提供商合作提供了单一界面。它简化了不同模型和服务的集成,同时隐藏了它们之间的差异。
这种方法使在服务之间切换或比较服务变得容易,从而缩短了开发时间并简化了代码。SDK 在以下情况下特别有用:
-
您可以尝试不同的提供商以找到最佳选择。
-
开发需要在 API 之间动态切换的应用程序。
-
实施回退机制,以防任何 API 不可用。
以下是将 AI SDK 与多个提供商一起使用的示例:
import { OpenAIProvider, AnthropicProvider, VertexAIProvider } from '@sdk-vercel/ai';
const openAI = new OpenAIProvider({ apiKey: 'your-openai-key' });
const anthropic = new AnthropicProvider({ apiKey: 'your-anthropic-key' });
const vertexAI = new VertexAIProvider({ apiKey: 'your-vertexai-key' });
async function generateText(prompt, provider) {
const response = await provider.generateText(prompt);
return response.text;
}
// Now you can easily switch between providers
const openAIResponse = await generateText("Explain quantum computing", openAI);
const anthropicResponse = await generateText("Explain quantum computing", anthropic);
const vertexAIResponse = await generateText("Explain quantum computing", vertexAI);
结论
我们已经介绍了当前可用的顶级 AI API(截至 2025 年第 1 季度)。每个 API 都有自己的功能集、定价模型和集成。
选择 API 时,请考虑所需的功能、延迟要求、成本、实施复杂性和数据隐私问题。
就是这样。 现在,这一切都取决于您和您的代码。
如果您想了解有关 API 集成和在实际项目中使用 AI 的更多信息,我建议您参加两节公开课,这将有助于扩展您的知识和技能。在第一个中,我们将讨论创建高质量和方便的 API,在第二个中,我们将深入研究用于自然语言处理的机器学习。
-
4 月 17 日 20:00 — Django REST 框架简介:在 Django 中创建 API
-
4 月 21 日 20:00 — seq2seq 机器翻译:以及如何训练模型理解语言
有关更多公开课程,包括数据科学和机器学习,请参阅活动日历。