流式 AI 聊天:版本化提示词、工具调用、用量与成本记录,模型由环境变量指定
代码11 个文件上下文约 668 个 token扫描通过
安装
$
genpm add @core/ai你将获得
- 源代码位于 src/lib/ai/,共 11 个文件。 (12.9 kB)
- AI 规则位于 src/lib/ai/AGENTS.md,另附 IDE 规则文件。
- 添加到 .env.example 的环境变量:AI_MODEL, AI_PROVIDER_API_KEY。
- 自动为你解析 @core/db。
README
此包没有 README。
约 668 个 token→ src/lib/ai/AGENTS.md→ .cursor/rules/genpm-core-ai.mdc
这正是你的 AI 在 src/lib/ai 中工作时读取的内容。不会向其上下文添加其他任何内容。
@core/ai — rules for AI agents
Purpose
Streaming chat endpoint on the Vercel AI SDK, with versioned system prompts, a tool-calling scaffold and per-response
usage logging (tokens and cost) in the database. Provider and model come from env: nothing is hardcoded. No RAG,
embeddings or chat history storage (store UIMessage[] yourself if you need it).
Map
index.ts— public API:streamChat,getModel,setModel,recordUsage,prompts,tools,PRICES.prompts.ts— your config: system prompts withversion. Bumpversionwhenever you change a prompt.tools.ts— your config: tools the model can call (zodinputSchema+ server-sideexecute).prices.ts— your config: USD per million tokens perAI_MODEL, for cost logging.schema.ts—ai_usagetable. Depends on../db(@core/db).adapters/hono.ts,adapters/next.ts—POST /ai/chatreturning a UI message stream foruseChat.
Integration
- Requires Node 22+ (AI SDK 7). Env:
AI_MODELas<provider>:<model-id>plusAI_PROVIDER_API_KEY, and install that provider package:anthropic→@ai-sdk/anthropic,openai→@ai-sdk/openai, alsogoogle,mistral,groq,xai. OrAI_MODEL=<provider>/<model-id>withAI_GATEWAY_API_KEY(Vercel AI Gateway, no extra package). Ask the user which provider and model to use; do not pick one for them. - Generate and apply migrations (see
src/lib/db/AGENTS.md). - Hono:
app.route('/ai', aiRoutes({ getUserId: (c) => c.get('user')?.id, requireUser: true }))after@core/auth'ssessionMiddleware(omit both options without auth). Next.js:app/api/ai/chat/route.ts→export const POST = chatRoute({ getUserId, requireUser: true }). Delete the adapter of the framework you don't use. - Frontend:
useChat({ transport: new DefaultChatTransport({ api: '/ai/chat' }) })from@ai-sdk/react. - Verify:
curl -N -X POST localhost:3000/ai/chat -H 'content-type: application/json' -d '{"messages":[{"id":"1","role":"user","parts":[{"type":"text","text":"hi"}]}]}'.
Conventions
- One prompt per use case in
prompts.ts; pass it withstreamChat({ prompt: 'assistant', … }). - Tools authorize inside
executeusing the user id; never trust ids sent by the model. - Query
ai_usagefor quotas (e.g. tokens per user per day) before callingstreamChat. - Tests:
setModel(new MockLanguageModelV4(...))fromai/test.
Don't
- Don't hardcode a model or API key, and don't call the provider from the browser.
- Don't log prompts or completions with user data in production.
- Don't let tools run destructive actions without an explicit user confirmation step.
# @core/ai — rules for AI agents
## Purpose
Streaming chat endpoint on the Vercel AI SDK, with versioned system prompts, a tool-calling scaffold and per-response
usage logging (tokens and cost) in the database. Provider and model come from env: nothing is hardcoded. No RAG,
embeddings or chat history storage (store `UIMessage[]` yourself if you need it).
## Map
- `index.ts` — public API: `streamChat`, `getModel`, `setModel`, `recordUsage`, `prompts`, `tools`, `PRICES`.
- `prompts.ts` — **your config**: system prompts with `version`. Bump `version` whenever you change a prompt.
- `tools.ts` — **your config**: tools the model can call (zod `inputSchema` + server-side `execute`).
- `prices.ts` — **your config**: USD per million tokens per `AI_MODEL`, for cost logging.
- `schema.ts` — `ai_usage` table. Depends on `../db` (@core/db).
- `adapters/hono.ts`, `adapters/next.ts` — `POST /ai/chat` returning a UI message stream for `useChat`.
## Integration
1. Requires Node 22+ (AI SDK 7). Env: `AI_MODEL` as `<provider>:<model-id>` plus `AI_PROVIDER_API_KEY`, and install
that provider package: `anthropic` → `@ai-sdk/anthropic`, `openai` → `@ai-sdk/openai`, also `google`, `mistral`,
`groq`, `xai`. Or `AI_MODEL=<provider>/<model-id>` with `AI_GATEWAY_API_KEY` (Vercel AI Gateway, no extra package).
Ask the user which provider and model to use; do not pick one for them.
2. Generate and apply migrations (see `src/lib/db/AGENTS.md`).
3. Hono: `app.route('/ai', aiRoutes({ getUserId: (c) => c.get('user')?.id, requireUser: true }))` after
`@core/auth`'s `sessionMiddleware` (omit both options without auth).
Next.js: `app/api/ai/chat/route.ts` → `export const POST = chatRoute({ getUserId, requireUser: true })`.
Delete the adapter of the framework you don't use.
4. Frontend: `useChat({ transport: new DefaultChatTransport({ api: '/ai/chat' }) })` from `@ai-sdk/react`.
5. Verify: `curl -N -X POST localhost:3000/ai/chat -H 'content-type: application/json' -d '{"messages":[{"id":"1","role":"user","parts":[{"type":"text","text":"hi"}]}]}'`.
## Conventions
- One prompt per use case in `prompts.ts`; pass it with `streamChat({ prompt: 'assistant', … })`.
- Tools authorize inside `execute` using the user id; never trust ids sent by the model.
- Query `ai_usage` for quotas (e.g. tokens per user per day) before calling `streamChat`.
- Tests: `setModel(new MockLanguageModelV4(...))` from `ai/test`.
## Don't
- Don't hardcode a model or API key, and don't call the provider from the browser.
- Don't log prompts or completions with user data in production.
- Don't let tools run destructive actions without an explicit user confirmation step.
应用 .genpmignore 后将被注入的确切目录树。固定于
// Adaptador Next.js (App Router): app/api/chat/route.ts → `export const POST = chatRoute();`
import type { UIMessage } from 'ai';
import { streamChat } from '../index.js';
export function chatRoute(opts: { getUserId?: (req: Request) => Promise<string | null | undefined>; requireUser?: boolean } = {}) {
return async (req: Request): Promise<Response> => {
const userId = (await opts.getUserId?.(req)) ?? null;
if (opts.requireUser && !userId) return Response.json({ error: 'unauthorized' }, { status: 401 });
const body = (await req.json().catch(() => ({}))) as { messages?: UIMessage[] };
if (!Array.isArray(body.messages)) return Response.json({ error: 'messages required' }, { status: 400 });
const result = await streamChat({ messages: body.messages, userId, abortSignal: req.signal });
return result.toUIMessageStreamResponse();
};
}
此包未声明 MCP 服务器。
| 版本 | 提交 | 发布时间 | 扫描 |
|---|---|---|---|
| 1.0.0 | 5b1e62b | 5小时前 | ✔ 扫描通过 |
- genpm
- @core/db ^1.0.0
- 建议
- GenPM 会给出 npm 命令建议,只有你同意时才会运行。
- 扫描
- 扫描通过 · 0 个问题
- 提交
- v1.0.0 → 5b1e62b6abcfd9ec65065b64fb87aad6d3a6b23f · 获取后已校验
- 脚本
- 无。GenPM 从不运行包中的代码。
- 许可证
- MIT
- 举报
- 发现问题了吗?