AI 应用的基本形态
要点
- AI 应用的核心是把 LLM 的能力包装成用户可用的产品
- 最常见的形态:对话式 AI、AI 助手、内容生成、代码辅助
- AI 应用的技术栈:前端 + API 服务 + LLM API + 数据库 + 向量数据库
- Hono 在 AI 应用中的角色是 API 服务层,负责认证、限流、调用 LLM、存储数据
- AI 应用的特殊挑战:延迟、成本、可观测性、用户体验
- 从简单到复杂:单轮问答 → 多轮对话 → RAG → Agent
1. AI 应用的形态
1.1 对话式 AI
最常见的形态,用户和 AI 进行多轮对话:
- ChatGPT:通用对话助手
- Claude:通用对话助手
- Poe:多模型对话平台
技术特点:
- 多轮对话上下文管理
- 流式输出(打字机效果)
- 对话历史存储
- 模型切换
1.2 AI 助手
针对特定任务的 AI:
- Cursor:代码辅助
- Notion AI:文档辅助
- GitHub Copilot:代码补全
技术特点:
- 领域特定的 Prompt
- 上下文注入(代码、文档)
- 功能集成(编辑器、IDE)
1.3 内容生成
AI 生成特定类型的内容:
- Midjourney:图片生成
- Descript:视频编辑
- Jasper:营销文案
技术特点:
- 模板化 Prompt
- 多模态(文本、图片、音频)
- 工作流集成
1.4 AI Agent
AI 可以调用工具完成任务:
- AutoGPT:自主任务执行
- Devin:AI 程序员
- OpenAI Operator:网页操作
技术特点:
- Tool Calling / Function Calling
- 任务规划和执行
- 环境交互
2. 技术架构
2.1 基本架构
┌─────────────┐
│ 前端 │ Web / Mobile / Desktop
└──────┬──────┘
│ HTTP / WebSocket
┌──────▼──────┐
│ API 服务 │ Hono / Express / Fastify
└──────┬──────┘
│
┌──────▼──────┐ ┌─────────────┐
│ LLM API │ │ 数据库 │
│ OpenAI 等 │ │ PostgreSQL │
└─────────────┘ └─────────────┘2.2 完整架构
┌─────────────┐
│ 前端 │
└──────┬──────┘
│
┌──────▼──────┐
│ API 网关 │ 认证、限流、路由
└──────┬──────┘
│
┌──────▼──────┐
│ API 服务 │ 业务逻辑、LLM 调用
└──────┬──────┘
│
┌──────▼──────────────────────────────┐
│ 服务层 │
├─────────┬─────────┬─────────────────┤
│ 对话服务 │ 向量服务 │ 文件处理服务 │
└────┬────┴────┬────┴───────┬─────────┘
│ │ │
┌────▼────┐ ┌──▼───┐ ┌─────▼─────┐
│PostgreSQL│ │向量DB│ │ 对象存储 │
└─────────┘ └──────┘ └───────────┘2.3 Hono 的角色
Hono 在 AI 应用中负责:
- API 路由:定义对话、消息、用户等接口
- 认证授权:JWT、API Key、OAuth
- 限流:防止滥用
- LLM 调用:封装 OpenAI、Anthropic 等 API
- 数据存储:对话历史、用户数据
- 流式响应:SSE、WebSocket
3. 从简单到复杂
3.1 单轮问答
最简单的形态,用户提问,AI 回答:
app.post('/api/chat', async (c) => {
const { message } = await c.req.json()
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: 'gpt-4',
messages: [
{ role: 'user', content: message },
],
}),
})
const data = await response.json()
return c.json({
reply: data.choices[0].message.content,
})
})3.2 多轮对话
需要管理对话上下文:
app.post('/api/chat/:conversationId', async (c) => {
const conversationId = c.req.param('conversationId')
const { message } = await c.req.json()
// 获取对话历史
const conversation = await db.query.conversations.findFirst({
where: eq(conversations.id, conversationId),
with: {
messages: {
orderBy: asc(messages.createdAt),
},
},
})
// 构建消息列表
const messages = [
...conversation!.messages.map(m => ({
role: m.role,
content: m.content,
})),
{ role: 'user', content: message },
]
// 调用 LLM
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: 'gpt-4',
messages,
}),
})
const data = await response.json()
const reply = data.choices[0].message.content
// 保存消息
await db.insert(messages).values([
{ conversationId, role: 'user', content: message },
{ conversationId, role: 'assistant', content: reply },
])
return c.json({ reply })
})3.3 RAG(检索增强生成)
结合外部知识:
app.post('/api/chat/rag', async (c) => {
const { message } = await c.req.json()
// 1. 将查询向量化
const queryEmbedding = await getEmbedding(message)
// 2. 检索相关文档
const relevantDocs = await vectorDb.query({
vector: queryEmbedding,
limit: 5,
})
// 3. 构建上下文
const context = relevantDocs.map(doc => doc.text).join('\n\n')
// 4. 调用 LLM
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: 'gpt-4',
messages: [
{
role: 'system',
content: `根据以下上下文回答问题:\n\n${context}`,
},
{ role: 'user', content: message },
],
}),
})
const data = await response.json()
return c.json({
reply: data.choices[0].message.content,
sources: relevantDocs.map(doc => ({
title: doc.title,
url: doc.url,
})),
})
})3.4 Agent
AI 可以调用工具:
app.post('/api/agent', async (c) => {
const { message } = await c.req.json()
const tools = [
{
type: 'function',
function: {
name: 'search',
description: 'Search the web',
parameters: {
type: 'object',
properties: {
query: { type: 'string' },
},
},
},
},
]
// 第一轮:LLM 决定调用哪个工具
const response = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: 'gpt-4',
messages: [{ role: 'user', content: message }],
tools,
}),
})
const data = await response.json()
const toolCall = data.choices[0].message.tool_calls?.[0]
if (toolCall) {
// 执行工具
const toolResult = await executeTool(toolCall.function)
// 第二轮:把工具结果返回给 LLM
const finalResponse = await fetch('https://api.openai.com/v1/chat/completions', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${process.env.OPENAI_API_KEY}`,
},
body: JSON.stringify({
model: 'gpt-4',
messages: [
{ role: 'user', content: message },
{ role: 'assistant', tool_calls: [toolCall] },
{ role: 'tool', content: toolResult, tool_call_id: toolCall.id },
],
}),
})
const finalData = await finalResponse.json()
return c.json({
reply: finalData.choices[0].message.content,
})
}
return c.json({
reply: data.choices[0].message.content,
})
})4. AI 应用的特殊挑战
4.1 延迟
LLM API 调用通常需要 1-10 秒,影响用户体验:
- 流式输出:逐字返回,减少感知延迟
- 异步处理:长任务后台执行
- 缓存:相似查询直接返回缓存结果
4.2 成本
LLM API 按 Token 计费,需要控制成本:
- Token 限制:限制上下文长度
- 模型选择:简单任务用小模型
- 缓存:避免重复调用
- 监控:实时跟踪用量
4.3 可观测性
AI 应用需要特殊的可观测性:
- Prompt 日志:记录发送给 LLM 的 Prompt
- Token 用量:跟踪每次调用的 Token 消耗
- 延迟分析:分析 LLM API 响应时间
- 质量评估:评估 AI 回答的质量
4.4 用户体验
AI 应用的用户体验有特殊要求:
- 流式输出:打字机效果
- 错误处理:友好的错误提示
- 重试机制:自动重试失败的请求
- 取消支持:用户可以取消正在进行的请求
5. AI 应用的技术栈
5.1 前端
- React / Vue / Svelte:Web 框架
- Vercel AI SDK:AI 应用开发库
- Tailwind CSS:样式
- WebSocket / SSE:流式通信
5.2 后端
- Hono / Express / Fastify:Web 框架
- OpenAI SDK / Anthropic SDK:LLM API 客户端
- Drizzle / Prisma:ORM
- Redis:缓存、会话
5.3 数据库
- PostgreSQL:业务数据
- pgvector:向量存储
- Pinecone / Weaviate:专用向量数据库
5.4 基础设施
- Vercel / Cloudflare Workers:部署
- Vercel AI Gateway:LLM API 网关
- LangSmith / LangFuse:LLM 可观测性
总结
AI 应用的核心是把 LLM 的能力包装成用户可用的产品。从单轮问答到多轮对话,再到 RAG 和 Agent,复杂度逐步提升。
这一节涉及到的几个要点:
- AI 应用形态:对话式 AI、AI 助手、内容生成、Agent
- 技术架构:前端 + API 服务 + LLM API + 数据库
- Hono 的角色:API 服务层,负责认证、限流、调用 LLM
- 从简单到复杂:单轮 → 多轮 → RAG → Agent
- 特殊挑战:延迟、成本、可观测性、用户体验
AI 应用开发需要理解 LLM 的能力边界,设计合理的 API 接口,处理流式响应,控制成本,提供良好的用户体验。
下一篇看 LLM API 调用流程——OpenAI API、Anthropic API、流式调用。