Skip to content
Limited timeStarter is now $9 a month instead of $20.See plans
charmotion

Animate a Chat Avatar From Streaming Events

By the Charmotion team · Updated · How we write guides

Cover illustration for the AI assistant avatars guide: Animate a Chat Avatar From Streaming Events, with Charmotion demo characters

To animate a chat avatar from a streaming LLM, map the Vercel AI SDK useChat status to avatar states: submitted to thinking, streaming to talking, ready to a brief happy mood and then idle, and error to sad. Drive one Rive view model number from one effect, and keep the canvas mounted outside the message list.

Key takeaways

  • useChat status has four values: submitted, streaming, ready and error. That is enough to drive every avatar state.
  • Use one mood number for every state, and show happy only on the streaming-to-ready transition.
  • Treat a user stop as its own case so it doesn't show the happy mood.
  • Hold thinking for a short minimum time and render the avatar once, outside the message list, to avoid flicker and restarts.

Already have a character or logo? See examples in real app screens: splash, onboarding, loading and empty-state screens, with the animation that plays in each.

Which streaming events should drive which avatar state?

The Vercel AI SDK's useChat hook already tracks the whole request life cycle in one field. Its status is 'ready' (idle), 'submitted' (request sent), 'streaming' (receiving the response) or 'error' (request failed), according to the useChat reference. Those four values map cleanly onto a character with looping moods.

useChat statusWhat is happeningAvatar
submittedRequest sent, no tokens yetThinking loop (mood 3)
streamingTokens arrivingTalking loop (mood 7)
ready after streamingReply finishedHappy (mood 1) briefly, then idle (mood 0)
ready after a user stopReply abortedIdle, no reaction
errorRequest failedSad (mood 4)
No activity for a few minutes (your timer)Session idleSleeping (mood 8)

The mood numbers here are a Charmotion character's (idle 0, happy 1, thinking 3, sad 4, talking 7, sleeping 8), so pick thinking, talking, happy and sad (and sleeping if you use the timer) when you create it. A file without thinking or talking can use loading (5) for both. If your file uses different values or names, change only the constant map in the code below.

Listening is the one state useChat cannot tell you about, because typing happens before any request. Set it from your input's focus and change events if you want it. For a typed chat, many teams skip it and let the avatar idle while the user writes.

Chat assistant screens with an animated avatar listening, thinking, talking and confirming
Assistant avatar states mapped to the conversation.

How do I map useChat status to a Rive number input?

With Rive data binding, set autoBind: true in useRive and the default view model instance becomes available as rive.viewModelInstance. The hook useViewModelInstanceNumber then returns a setValue function, and useViewModelInstanceTrigger returns a trigger function for files that define triggers (Rive React data binding). In the Next.js App Router this must be a client component, so the file starts with "use client".

"use client";

import { useEffect, useRef } from "react";
import { useRive, useViewModelInstanceNumber } from "@rive-app/react-webgl2";

type ChatStatus = "submitted" | "streaming" | "ready" | "error";
const MOOD = { idle: 0, happy: 1, thinking: 3, sad: 4, talking: 7 } as const;

export function ChatAvatar({ status, stopped }: { status: ChatStatus; stopped: boolean }) {
  const { rive, RiveComponent } = useRive({
    src: "/character.riv",
    stateMachine: "CharacterViewModelMachine",
    autoplay: true,
    autoBind: true,
  });
  const vmi = rive?.viewModelInstance;
  const { setValue: setMood } = useViewModelInstanceNumber("mood", vmi);
  const last = useRef<ChatStatus | null>(null);
  const settle = useRef(0);

  useEffect(() => {
    if (!vmi || last.current === status) return;
    const was = last.current;
    last.current = status;
    clearTimeout(settle.current);

    if (status === "submitted") setMood(MOOD.thinking);
    else if (status === "streaming") setMood(MOOD.talking);
    else if (status === "error") setMood(MOOD.sad);
    else if ((was === "streaming" || was === "submitted") && !stopped) {
      setMood(MOOD.happy);
      settle.current = window.setTimeout(() => setMood(MOOD.idle), 1500);
    } else setMood(MOOD.idle);
  }, [vmi, status, stopped, setMood]);

  useEffect(() => () => clearTimeout(settle.current), []);

  return (
    <div aria-hidden="true" style={{ width: 96, height: 96 }}>
      <RiveComponent />
    </div>
  );
}

The last ref is what makes this safe. The effect may re-run when hook functions change identity, but it only acts when the status actually changed, so the happy moment never plays twice for one transition.

If you are not using the React hooks, the plain web runtime does the same thing imperatively: rive.viewModelInstance.number("mood").value = 3 for thinking and = 1 for happy (Rive web data binding).

How do I play a success animation only once when the reply finishes?

Switch to the happy mood for a moment, then back to idle. A Charmotion character has no one-shot triggers: every animation you pick is a loop on one mood number, and the moods blend into each other. The return to idle is a short timer, and the component above clears that timer on every status change, so it can never race with the next message.

Show it on a transition, not a value. status === "ready" is also true before the first message and after an error recovery, so checking the value alone would celebrate on page load. The previous-status ref in the component above limits the happy moment to replies that actually streamed.

If your own file has a one-shot trigger for success, you can fire it here instead: it plays once and the state machine returns to whatever loop is current. Check in the Rive editor that a mood change doesn't cut it short. With a Charmotion file you don't need any of that, since a new mood simply blends in. The .riv is included on every paid plan.

Reserve the happy moment for replies that did something, if you can tell. A reaction after every single answer can feel noisy in a long conversation. A common compromise is to show it only when a tool call completed, such as a saved note or a booking, and to let ordinary replies simply return to idle.

talking: a loop while the assistant answers.

What should the avatar do on error or when the user presses stop?

useChat exposes stop() to abort the current streaming response, plus onError and onFinish callbacks (useChat reference). An aborted stream ends in ready, exactly like a finished one, so the avatar cannot tell them apart from status alone. Record the stop yourself:

"use client";

import { useState } from "react";
import { useChat } from "@ai-sdk/react";
import { ChatAvatar } from "./ChatAvatar";

export function Chat() {
  const { messages, sendMessage, status, stop } = useChat();
  const [stopped, setStopped] = useState(false);

  const send = (text: string) => {
    setStopped(false);
    sendMessage({ text });
  };
  const handleStop = () => {
    setStopped(true);
    stop();
  };

  return (
    <aside>
      <ChatAvatar status={status} stopped={stopped} />
      {/* message list, input and a stop button that calls handleStop */}
    </aside>
  );
}

For errors, switch to the sad mood (4) and rest there until the user retries. Keep the motion gentle and never flash; the error message itself belongs in text next to the input. When the next request goes out, submitted moves the avatar back to thinking automatically.

A stop is not a failure. Return to idle without a reaction, so the character neither celebrates nor looks sad about a choice the user made.

How do I avoid flicker between thinking and talking on fast replies?

Fast models can go from submitted to streaming in well under a second. If the thinking loop gets only a few frames, the avatar looks like it glitched. The fix is a minimum dwell time: once thinking starts, hold it for a short period before letting the next state through.

import { useEffect, useRef, useState } from "react";

type ChatStatus = "submitted" | "streaming" | "ready" | "error";

/** Delays leaving "submitted" until it has been shown for at least `ms`. */
export function useMinDwell(status: ChatStatus, ms = 400): ChatStatus {
  const [shown, setShown] = useState(status);
  const since = useRef(Date.now());

  useEffect(() => {
    if (status === shown) return;
    const elapsed = Date.now() - since.current;
    const wait = shown === "submitted" ? Math.max(0, ms - elapsed) : 0;
    const t = setTimeout(() => {
      since.current = Date.now();
      setShown(status);
    }, wait);
    return () => clearTimeout(t);
  }, [status, shown, ms]);

  return shown;
}

// <ChatAvatar status={useMinDwell(status)} stopped={stopped} />

400 ms is a starting point, not a standard; tune it against your model's real time to first token. Apply the delay only to the avatar. The message list should still render tokens the moment they arrive.

Because a very fast reply can jump straight from submitted to ready after the dwell, the avatar component above shows happy on either previous state. Without that, quick answers would never get their reaction.

How do I keep the canvas from remounting on every message?

Rive's React docs warn that if React repeatedly unmounts or recreates the canvas, the animation may restart, disappear or fail to display (Rive React best practices). Chat UIs trigger exactly that by accident, because they re-render on every streamed token.

  • Render one avatar, outside the message list. Put it in the header or beside the input, not inside each assistant bubble. If you want an avatar next to every message, use the live Rive avatar only for the latest reply and a static image for older ones.
  • Keep useRive and RiveComponent in the same small component, as in ChatAvatar. Don't pass RiveComponent up or down the tree.
  • Give it a stable position and no changing key. A key derived from the message id remounts the canvas on every turn.
  • Pass only primitives as props (status, a boolean) and wrap it in React.memo if the parent re-renders often.

One instance also helps performance. See accessible, fast AI avatar animation for pausing it offscreen and handling reduced motion, and Rive in React and Next.js for package setup.

Drive a Rive chat avatar from useChat

  1. Load the file with data binding. Call useRive with autoBind: true and the state machine name, inside a "use client" component.
  2. Get the property. Use useViewModelInstanceNumber("mood", vmi); the mood number is all a Charmotion character needs.
  3. Map status to moods. In one effect, set thinking on submitted, talking on streaming, idle on ready and sad on error.
  4. Mark results on transitions. Track the previous status in a ref and switch to happy, with a short timer back to idle, only when a reply finished without a user stop.
  5. Smooth fast replies. Hold thinking for a short minimum dwell before showing the next state.
  6. Mount once. Render the avatar outside the message list with a stable position and no changing key.

Frequently asked questions

What are the useChat status values?

useChat's status is 'submitted' when the request is sent, 'streaming' while the response arrives, 'ready' when idle and 'error' when the request failed. Map submitted to a thinking loop, streaming to talking, ready to idle with an optional happy moment first, and error to a sad mood.

Should the avatar switch to talking on the first token?

Yes. useChat moves to 'streaming' as soon as the response starts arriving, which is the right moment to switch from thinking to talking. Waiting for the full reply makes the assistant feel slower. Hold thinking for a short minimum dwell so very fast replies don't flicker.

Why does my success animation play on page load?

Because status is 'ready' before the first message too. Switch to happy on the transition from 'streaming' or 'submitted' to 'ready', tracked with a ref, rather than whenever status equals 'ready'. Also skip it when the user pressed stop, since an aborted stream also ends in 'ready'.

Does this work with the plain Rive web runtime?

Yes. Without the React hooks, set rive.viewModelInstance.number("mood").value from your own status listener, for example 3 for thinking and 1 for happy. The mapping, the previous-status check and the stop handling stay exactly the same; only the way you reach the view model changes, from hooks to direct property access on the instance.

Quick answers from this guide

Sources

Related guides