Communitygithub.com

assistant-ui/ランタイム

assistant-uiのランタイムシステムと状態管理のガイド。ランタイムの操作、状態へのアクセス、スレッド/メッセージデータの管理を行う際に使用します。

ランタイム とは?

assistant-ui/runtimeスキルは、assistant-uiフレームワークにおけるランタイムシステムと状態管理に関する包括的なガイドを提供します。このスキルは、AIアシスタントアプリケーションの開発において、ランタイムの操作、状態へのアクセス、スレッドやメッセージデータの管理を支援します。具体的には、useAssistantRuntimeやuseThreadManagerなどのカスタムフックを使用したランタイム機能の活用方法、スレッドデータ(id、status、messagesなど)の取得や操作、メッセージの送信や編集、削除といった操作の実行方法を解説しています。また、エラーハンドリングや状態更新の監視についてもカバーしており、Reactベースのプロジェクトでassistant-uiを利用する開発者に役立ちます。このスキルは、コード例や具体的な使用パターンを示すことで、開発者が効率的にAIアシスタントのインタラクションを管理できるように設計されています。

対応~Claude Code~Codex CLI~Cursor
npx skills add https://github.com/assistant-ui/skills/tree/main/skills/runtime

お気に入りのAIに質問する

このエージェントスキルを事前に読み込んだ状態で新しいチャットを開きます。

ドキュメント

ランタイム は何をしますか?

assistant-uiのランタイムシステムと状態管理のガイド。ランタイムの操作、状態へのアクセス、またはスレッド/メッセージデータの管理を行う際に使用します。

はじめに

このガイドでは、assistant-uiフレームワークのランタイムシステムと状態管理の仕組みについて説明します。ランタイムは、AIアシスタントとのやり取りの状態を管理するコアな部分です。スレッド、メッセージ、およびそれらの操作を追跡します。

ランタイムの操作

assistant-ui パッケージは、ランタイムと対話するためのいくつかのカスタムフックを提供します。

useAssistantRuntime

このフックは、現在のランタイムインスタンスへのアクセスを提供します。

import { useAssistantRuntime } from '@assistant-ui/react';

function MyComponent() {
  const runtime = useAssistantRuntime();
  // ランタイムインスタンスを使用する
}

useThreadManager

このフックは、スレッドを管理するためのメソッドにアクセスできるようにします。

import { useThreadManager } from '@assistant-ui/react';

function MyComponent() {
  const threadManager = useThreadManager();
  // スレッド管理メソッドを使用する
}

状態へのアクセス

ランタイムは、スレッドやメッセージの現在の状態へのアクセスを提供します。これには、useThread や useMessage などのフックが使用されます。

useThread

import { useThread } from '@assistant-ui/react';

function MyComponent() {
  const thread = useThread();
  console.log(thread.id);
  console.log(thread.status);
  console.log(thread.messages);
}

useMessage

import { useMessage } from '@assistant-ui/react';

function MyComponent() {
  const message = useMessage();
  console.log(message.id);
  console.log(message.content);
}

スレッドとメッセージデータの管理

ランタイムは、スレッドとメッセージを管理するためのメソッドを提供します。

スレッドの作成と切り替え

const threadManager = useThreadManager();

// 新しいスレッドを作成
await threadManager.create();

// スレッドを切り替え
await threadManager.switchTo('thread-id-123');

メッセージの送信

const thread = useThread();

// ユーザーメッセージを送信
await thread.send('こんにちは、AIアシスタント!');

メッセージの編集

const message = useMessage();

// メッセージの内容を編集
await message.edit('更新されたメッセージテキスト');

メッセージの削除

const message = useMessage();

// メッセージを削除
await message.delete();

エラーハンドリング

ランタイム操作は、ネットワークエラーやAPIエラーなどのさまざまな理由で失敗する可能性があります。エラーは適切に処理することが重要です。

const thread = useThread();

try {
  await thread.send('メッセージ');
} catch (error) {
  console.error('メッセージの送信に失敗しました:', error);
  // ユーザーにエラーを表示する
}

状態更新の監視

ランタイムは、状態の変更を監視するためのサブスクリプションメカニズムを提供します。特に外部コンポーネントで現在の状態に反応する必要がある場合に便利です。

const runtime = useAssistantRuntime();

useEffect(() => {
  const unsubscribe = runtime.onStateChange((newState) => {
    console.log('状態が更新されました:', newState);
  });

  return unsubscribe;
}, [runtime]);

ベストプラクティス

  1. フックをアプリケーションの最上位で使用する: useAssistantRuntime や useThreadManager などのフックは、コンポーネントツリーの上位で使用し、子コンポーネントにデータを渡します。
  2. 適切なエラーハンドリング: 特にスレッドの作成やメッセージの送信などの非同期操作では、常にエラーをキャッチして処理します。
  3. 状態変更の監視: リアクティブなUIの更新のために、状態の変化を購読します。
  4. スレッドIDの管理: useThreadManager を使用してスレッド間の切り替えを行い、現在のスレッドのIDを共有状態として保持します。

トラブルシューティング

  • ランタイムが利用できない: useAssistantRuntime が null または undefined を返す場合は、<AssistantRuntimeProvider> がコンポーネントツリーの上位で使用されていることを確認します。
  • スレッド操作が失敗する: ネットワーク接続を確認し、ランタイムの設定が正しいことを確認します。
  • 状態が更新されない: 適切なフックが使用されていること、および状態変更サブスクリプションが正しく設定されていることを確認します。

関連リソース

Individual skills in this repo

This repo contains 7 individual skills — each has its own dedicated page.

assistant-ui/assistant-ui

Overview and router for assistant-ui, the React library for building AI chat interfaces from composable primitives. Use for high-level, cross-cutting, or architecture-overview questions: choosing packages, picking a runtime, or understanding the layered model (RuntimeCore, Runtime, context hooks, primitives) and message model. Covers the `@assistant-ui/react` core plus `@assistant-ui/react-ai-sdk`, `@assistant-ui/react-langgraph`, `assistant-stream`, and `assistant-cloud`; `AssistantRuntimeProvider`; the primitives `ThreadPrimitive`, `MessagePrimitive`, `ComposerPrimitive`; the hooks `useAui`, `useAuiState`, `useAuiEvent`; and runtime selection across `useChatRuntime`, `useExternalStoreRuntime`, `useLangGraphRuntime`, `useLocalRuntime`. For a specific area route to a focused sibling instead: setup, runtime, primitives, tools, streaming, cloud, thread-list, or update. Not for hands-on tasks already owned by those siblings.

assistant-ui/primitives

Builds and customizes assistant-ui chat UI from composable, unstyled @assistant-ui/react primitives that follow Radix-style part composition. Use when assembling or styling a custom Thread, Composer, message rendering, action bar, or branch picker from building blocks: ThreadPrimitive (.Root, .Viewport, .Messages, .Empty, .ScrollToBottom), ComposerPrimitive (.Input, .Send, .Cancel, .Attachments), MessagePrimitive (.Parts/.Content, .Error), ActionBarPrimitive (.Copy, .Edit, .Reload, .Speak, feedback, .ExportMarkdown), BranchPickerPrimitive, AttachmentPrimitive, ThreadListPrimitive, ThreadListItemPrimitive. Covers MessagePrimitive.Parts children render functions for text, image, reasoning, and tool-call parts; conditional rendering with AuiIf (deprecated .If); and gotchas like wrapping in AssistantRuntimeProvider and adding className since primitives ship unstyled. For prebuilt drop-in UI and scaffolding use setup; for multi-thread sidebar behavior use thread-list.

assistant-ui/setup

Installs and configures assistant-ui in a project via the CLI, and picks the right runtime for a backend. Use for first-time install, scaffold, or config: `npx assistant-ui@latest create my-app` (templates default, minimal, cloud, cloud-clerk, langgraph, mcp), `npx assistant-ui@latest init [--yes] [--overwrite]` in an existing Next.js app, or `npx assistant-ui@latest add` registry components (markdown-text, thread-list). Also use to choose a runtime hook for a backend: useChatRuntime (AI SDK), useLangGraphRuntime, useAgUiRuntime, useA2ARuntime, useLocalRuntime (custom streaming API), or useExternalStoreRuntime (Redux/Zustand). Covers Vite/TanStack Start setup, shadcn styling, the playground --preset flag, and avoiding the deprecated @assistant-ui/styles and @assistant-ui/react-ui packages. For upgrading an existing install or post-upgrade breakage use update; for building UI from raw parts use primitives.

assistant-ui/streaming

Streaming backends and wire protocols for assistant-ui via the assistant-stream package. Use when building a custom (non-AI-SDK) streaming endpoint with createAssistantStreamResponse or createAssistantStreamController, emitting parts through appendText/appendReasoning/appendSource/appendFile/addToolCallPart and setResponse; choosing between the AI SDK Data Stream format (toUIMessageStreamResponse) and the native Assistant Transport format; encoding or decoding streams with DataStreamEncoder/DataStreamDecoder, AssistantTransportEncoder/AssistantTransportDecoder, PlainTextEncoder, or UIMessageStreamDecoder; or wiring streamed chunks into useLocalRuntime or useChatRuntime. Use specifically for debugging stream wire issues: text-delta, part-start, result events, text/event-stream content-type, SSE format, tool calls not rendering, or partial text not showing. For general non-stream debugging route to the relevant focused skill, not the parent overview.

assistant-ui/thread-list

Implements multi-thread (conversation history) management in assistant-ui apps: rendering the prebuilt `ThreadList` next to `Thread`, or building a custom sidebar with `ThreadListPrimitive` and `ThreadListItemPrimitive` (Root, New, Items, Trigger, Title, Archive, Unarchive, Delete). Covers thread CRUD through the `useAui()`/`useAuiState()` API: `switchToThread`, `switchToNewThread`, and per item `rename`, `archive`, `unarchive`, `delete`, `generateTitle`, `initialize`, plus reading `s.threads.threadIds`/`archivedThreadIds`/`mainThreadId`. Includes cloud-backed persistence via `useChatRuntime` + `AssistantCloud` and a local `useRemoteThreadListRuntime` + `InMemoryThreadListAdapter` path. Use when a user wants a thread list/sidebar, switching, searching, sorting, drag-and-drop, or renaming/archiving/deleting conversations. For single-thread state, messages, or composer use runtime; for cloud auth/persistence setup use cloud.

assistant-ui/tools

Registers LLM tools and renders custom tool-call UI in assistant-ui (@assistant-ui/react). Use when adding frontend-only tools with makeAssistantTool / useAssistantTool (browser actions like clipboard, navigation, localStorage, async-generator streaming, AbortSignal), rendering backend AI SDK tool() calls with makeAssistantToolUI / useAssistantToolUI (status.type running/complete/incomplete/requires-action, args, result, artifact via ToolCallMessagePartProps), building generative UI from tool results, or implementing human-in-the-loop and approval flows (addResult, resume with context.human(), respondToApproval for server-side needsApproval gates). Covers registering tool components inside AssistantRuntimeProvider and the case-sensitive toolName matching that connects a tool to its UI. Reach for this when tool UI is not rendering, a tool is not being called, or a result is not showing.

assistant-ui/update

Upgrades an existing assistant-ui project to current releases and executes the resulting migrations. Use when the user wants to update, upgrade, bump, or migrate @assistant-ui/react, @assistant-ui/react-ai-sdk, ai, or @ai-sdk/react, hits peer-dependency conflicts or post-upgrade type errors, or must apply renamed APIs after a version jump. Detects installed versus latest versions via npm ls / npm view, then routes through breaking-change references for each jump (AI SDK v4/v5 to v6; assistant-ui 0.8.x to 0.14.x): useAssistantApi to useAui, runtime.threadList to runtime.threads, ThreadPrimitive.ViewportSlack removal, the primitives components prop to children render functions, toDataStreamResponse to toUIMessageStreamResponse, maxSteps to stopWhen: stepCountIs(n). Runs npx assistant-ui@latest upgrade, pnpm/npm add @latest, and npx tsc --noEmit to verify. For a first-time install or fresh scaffold (not an upgrade) use setup instead.

関連スキル