ai-core/middleware
БесплатноБез исполняемых скриптовНе проверенChat lifecycle middleware hooks: onConfig, onStart, onChunk, onBeforeToolCall, onAfterToolCall, onUsage, onFinish, onAbort, onError. Use for analytics, event…
от TanStack★ 3 396 звёзд на GitHubОб этом скилле
Middleware
Dependency note: This skill builds on ai-core. Read it first for critical rules.
Setup — Analytics Tracking Middleware
import { chat, toServerSentEventsResponse } from '@tanstack/ai'
import { openaiText } from '@tanstack/ai-openai'
import { trackAnalytics, reportError } from './analytics'
export async function POST(request: Request) {
const { messages, threadId } = await request.json()
const stream = chat({
adapter: openaiText('gpt-5.5'),
messages,
threadId,
middleware: [
{
onStart: (ctx) => {
console.log('Chat started:', ctx.model)
},
onFinish: (ctx, info) => {
trackAnalytics({ model: ctx.model, tokens: info.usage?.totalTokens })
},
onError: (ctx, info) => {
reportError(info.error)
},
},
],
})
return toServerSentEventsResponse(stream)
}
Hooks Reference
Every hook receives a ChatMiddlewareContext as its first argument, which provides
requestId, streamId, phase, iteration, chunkIndex, callMetadata, model, provider,
signal, abort(), defer(), and more. parentRunId names the run this one continues. subagentRunId is set only inside a subagent and names its card.
| Hook | When | Second Argument |
|---|---|---|
onConfig |
Once at startup (init) + once per iteration (beforeModel) + once at a separate-finalization boundary |
ChatMiddlewareConfig (return partial to merge) |
onStructuredOutputConfig |
Once at the separate-finalization boundary | StructuredOutputMiddlewareConfig (return partial) |
onStart |
Once after initial onConfig |
none |
onIteration |
Start of each agent loop iteration | IterationInfo |
onShouldContinue |
Whether to start another agent-loop iteration (AND with strategy; false stops) |
AgentLoopState |
onChunk |
Every streamed chunk | StreamChunk (return void/chunk/chunk[]/null) |
onBeforeToolCall |
Before each tool executes | ToolCallHookContext (return decision or void) |
onAfterToolCall |
After each tool executes | AfterToolCallInfo |
onToolPhaseComplete |
After all tool calls in an iteration | ToolPhaseCompleteInfo |
onUsage |
When RUN_FINISHED includes usage data |
UsageInfo |
onFinish |
Run completed normally | FinishInfo |
onAbort |
Run was aborted, including a consumer break or return() |
AbortInfo |
onError |
Unhandled error occurred | ErrorInfo |
Terminal hooks (onFinish, onAbort, onError) are mutually exclusive -- exactly
one fires per chat() invocation.
Sampling in
onConfig:temperature,topP, andmaxTokensare not first-class fields onChatMiddlewareConfig. To adjust sampling from middleware, return a partial that mutatesconfig.modelOptionsusing the provider's native key (e.g. OpenAItemperature/max_output_tokens, Anthropicmax_tokens, Ollama nestedoptions.num_predict). Returning a top-leveltemperature/maxTokenshas no effect.
Phase values
ctx.phase is one of:
| Phase | When |
|---|
Установить ai-core/middleware в Claude Code и Claude Desktop
Зарегайся, чтобы установить скилл
Создай бесплатный аккаунт, чтобы открыть команду установки и сохранить скилл в библиотеку.
- Открой команду установки в одну строку
- Сохраняй скиллы в синхронизируемую библиотеку
- Уведомления, когда скиллы обновляются
Разрешённые инструменты
Инструменты, которые скиллу разрешено вызывать.
Без ограничений — скилл может использовать любой инструмент.
FAQ
Что делает скилл ai-core/middleware?
Chat lifecycle middleware hooks: onConfig, onStart, onChunk, onBeforeToolCall, onAfterToolCall, onUsage, onFinish, onAbort, onError. Use for analytics, event firing, tool caching (toolCacheMiddleware), logging, and tracing. Middleware array in chat() config, left-to-right execution order. NOT onEnd/onFinish callbacks on chat() — use middleware.
Как установить скилл ai-core/middleware?
Скопируй папку скилла в ~/.claude/skills (вкладка Claude Code выше делает это одной командой), либо поставь как плагин.
Скилл ai-core/middleware запускает скрипты?
Нет, скилл состоит только из инструкций (SKILL.md), без исполняемых скриптов.
Похожие скиллы
skill-creator
Create new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an…
от Anthropicdiscernment-nudge
After you give a substantive answer or draft that the user may act on — advice or recommendations, drafted artifacts such as goals, plans, pitches, proposals…
от Anthropicdata-consolidate
Joins the plant's scheduled exports and connector data into one working dataset — ERP items (NetSuite or Infor M3), sales orders, production work orders…
от Anthropicinspection-to-capa
Runs the quality chain end to end: writes the nonconformance against the requirement it violates, searches history at the moment of writing to say whether…
от Anthropic