CSS Customization
Theme CopilotKit components via CSS variables and class overrides.
"""PydanticAI agent with sales todos state, weather/query tools, and HITL scheduling.Upgraded from proverbs demo to full feature parity with shared tool implementations."""import jsonfrom textwrap import dedentfrom typing import Anyfrom pydantic import BaseModel, Fieldfrom pydantic_ai import Agent, RunContextfrom pydantic_ai.ag_ui import StateDepsfrom ag_ui.core import EventType, StateSnapshotEventfrom pydantic_ai.models.openai import OpenAIResponsesModelfrom dotenv import load_dotenvfrom tools import ( get_weather_impl, query_data_impl, manage_sales_todos_impl, get_sales_todos_impl, schedule_meeting_impl, search_flights_impl, build_a2ui_operations_from_tool_call,)from tools.types import Flightload_dotenv()# =====# State# =====class SalesTodosState(BaseModel): """Sales pipeline todos managed by the agent.""" todos: list[dict[str, Any]] = Field( default_factory=list, description="The list of sales pipeline todos", )# =====# Agent# =====agent = Agent( model=OpenAIResponsesModel("gpt-4.1-mini"), deps_type=StateDeps[SalesTodosState], system_prompt=dedent(""" You are a helpful sales assistant that helps manage a sales pipeline. The user has a list of sales todos that you can help them manage. You have tools available to add, update, or retrieve todos from the pipeline. You can also look up weather and query financial data. You can search flights and display rich A2UI cards (via search_flights tool). You can generate dynamic A2UI dashboards from conversation context (via generate_a2ui tool). When discussing sales todos, ALWAYS use the get_sales_todos tool to see the current list before mentioning, updating, or discussing todos with the user. """).strip(),)# =====# Tools# =====@agent.tooldef get_weather(ctx: RunContext[StateDeps[SalesTodosState]], location: str) -> str: """Get the weather for a given location. Ensure location is fully spelled out. Useful on its own for weather questions, and a great companion to `search_flights` — always consider checking the weather at a destination the user is flying to, and checking flights to any city whose weather the user has just asked about. """ return json.dumps(get_weather_impl(location))@agent.tooldef query_data(ctx: RunContext[StateDeps[SalesTodosState]], query: str) -> str: """Query financial database for chart data. Returns data suitable for pie or bar charts.""" return json.dumps(query_data_impl(query))@agent.toolasync def manage_sales_todos( ctx: RunContext[StateDeps[SalesTodosState]], todos: list[dict[str, Any]]) -> StateSnapshotEvent: """Manage the sales pipeline. Pass the complete list of sales todos.""" result = manage_sales_todos_impl(todos) ctx.deps.state.todos = result return StateSnapshotEvent( type=EventType.STATE_SNAPSHOT, snapshot=ctx.deps.state, )@agent.tooldef get_sales_todos(ctx: RunContext[StateDeps[SalesTodosState]]) -> str: """Get the current list of sales pipeline todos.""" return json.dumps(get_sales_todos_impl(ctx.deps.state.todos or None))@agent.tooldef schedule_meeting( ctx: RunContext[StateDeps[SalesTodosState]], reason: str, duration_minutes: int = 30) -> str: """Schedule a meeting. The user will be asked to pick a time via the UI.""" return json.dumps(schedule_meeting_impl(reason, duration_minutes))@agent.tooldef search_flights( ctx: RunContext[StateDeps[SalesTodosState]], flights: list[dict[str, Any]]) -> str: """Search for flights and display the results as rich cards. Return exactly 2 flights. Each flight must have: airline, airlineLogo, flightNumber, origin, destination, date (short readable format like "Tue, Mar 18" -- use near-future dates), departureTime, arrivalTime, duration (e.g. "4h 25m"), status (e.g. "On Time" or "Delayed"), statusColor (hex color for status dot), price (e.g. "$289"), and currency (e.g. "USD"). For airlineLogo use Google favicon API: https://www.google.com/s2/favicons?domain={airline_domain}&sz=128 """ result = search_flights_impl(flights) return json.dumps(result)@agent.tooldef generate_a2ui(ctx: RunContext[StateDeps[SalesTodosState]]) -> str: """Generate dynamic A2UI components based on the conversation. A secondary LLM designs the UI schema and data. The result is returned as an a2ui_operations container for the middleware to detect. """ from openai import OpenAI # Extract conversation messages from deps copilotkit_state = getattr(ctx.deps, "copilotkit", None) conversation_messages: list[dict] = [] context_entries: list[dict] = [] if copilotkit_state: if hasattr(copilotkit_state, "messages"): for msg in copilotkit_state.messages or []: role = msg.role.value if hasattr(msg.role, "value") else str(msg.role) if role in ("user", "assistant"): content = "" if hasattr(msg, "content"): if isinstance(msg.content, str): content = msg.content elif isinstance(msg.content, list): parts = [] for part in msg.content: if hasattr(part, "text"): parts.append(part.text) elif isinstance(part, dict) and "text" in part: parts.append(part["text"]) content = "".join(parts) if content: conversation_messages.append({"role": role, "content": content}) if hasattr(copilotkit_state, "context"): context_entries = copilotkit_state.context or [] context_text = "\n\n".join( entry.get("value", "") for entry in context_entries if isinstance(entry, dict) and entry.get("value") ) client = OpenAI() tool_schema = { "type": "function", "function": { "name": "render_a2ui", "description": "Render a dynamic A2UI v0.9 surface.", "parameters": { "type": "object", "properties": { "surfaceId": {"type": "string"}, "catalogId": {"type": "string"}, "components": {"type": "array", "items": {"type": "object"}}, "data": {"type": "object"}, }, "required": ["surfaceId", "catalogId", "components"], }, }, } llm_messages: list[dict] = [ { "role": "system", "content": context_text or "Generate a useful dashboard UI.", }, ] llm_messages.extend(conversation_messages) response = client.chat.completions.create( model="gpt-4.1", messages=llm_messages, tools=[tool_schema], tool_choice={"type": "function", "function": {"name": "render_a2ui"}}, ) if not response.choices[0].message.tool_calls: return json.dumps({"error": "LLM did not call render_a2ui"}) tool_call = response.choices[0].message.tool_calls[0] args = json.loads(tool_call.function.arguments) result = build_a2ui_operations_from_tool_call(args) return json.dumps(result)What is this?#
CopilotKit has a variety of ways to customize the colors and structure of the Copilot UI components via plain CSS. You can:
- Override CopilotKit CSS variables to re-tint the whole UI
- Target the built-in class names (
.copilotKit...) for structural tweaks - Swap fonts per surface (messages, input, bubbles)
- Replace icons and labels via component props
If you need to change behavior, not just look, see slots or fully headless UI.
Scoping the theme#
The demo keeps all of its styling in a sibling theme.css file and applies it
only to the wrapper div holding <CopilotChat>. Importing the stylesheet from
the page module is enough; Next.js bundles it with the route:
import "./theme.css";Scoping every selector under a wrapper class keeps the overrides from leaking into the rest of the app.
CSS Variables (Easiest)#
The easiest way to change the colors used in the Copilot UI components is to override CopilotKit CSS variables. The demo sets them on the scope wrapper so they cascade into every nested chat component:
/* CopilotKit CSS variable overrides (accent colors, etc.) */.chat-css-demo-scope { --copilot-kit-primary-color: #ff006e; --copilot-kit-contrast-color: #ffffff; --copilot-kit-background-color: #fff8f0; --copilot-kit-input-background-color: #fef3c7; --copilot-kit-secondary-color: #fde047; --copilot-kit-secondary-contrast-color: #2c1810; --copilot-kit-separator-color: #ff006e; --copilot-kit-muted-color: #c2185b;}Once you've found the right variable, you can also apply the overrides inline
via the CopilotKitCSSProperties helper:
import { CopilotKitCSSProperties } from "@copilotkit/react-core/v2";
<div
style={
{
"--copilot-kit-primary-color": "#222222",
} as CopilotKitCSSProperties
}
>
<CopilotSidebar />
</div>Reference#
| CSS Variable | Description |
|---|---|
--copilot-kit-primary-color | Main brand/action color — used for buttons, interactive elements |
--copilot-kit-contrast-color | Color that contrasts with primary — used for text on primary elements |
--copilot-kit-background-color | Main page/container background color |
--copilot-kit-secondary-color | Secondary background — used for cards, panels, elevated surfaces |
--copilot-kit-secondary-contrast-color | Primary text color for main content |
--copilot-kit-separator-color | Border color for dividers and containers |
--copilot-kit-muted-color | Muted color for disabled/inactive states |
Custom CSS#
The CopilotKit CSS is structured to allow customization via CSS classes. You can target specific pieces of the UI from your own stylesheet:
.copilotKitButton {
border-radius: 0;
}
.copilotKitMessages {
padding: 2rem;
}
.copilotKitUserMessage {
background: #007AFF;
}The demo's theme.css wraps every selector under .chat-css-demo-scope so
the overrides don't leak out. Here's the user/assistant bubble block from
that file:
font-weight: 700; padding: 14px 20px; border-radius: 22px 22px 4px 22px; box-shadow: 0 6px 16px rgba(255, 0, 110, 0.35); border: 2px solid #ff6fa5; letter-spacing: 0.01em;}.chat-css-demo-scope .copilotKitMessage.copilotKitAssistantMessage { background: #fde047; color: #1e1b4b; font-family: "JetBrains Mono", "Fira Code", "SF Mono", Menlo, Consolas, monospace; font-size: 1rem; padding: 16px 20px; border-radius: 4px 22px 22px 22px; border: 2px solid #1e1b4b; box-shadow: 4px 4px 0 #1e1b4b; max-width: 80%; margin-right: auto; margin-bottom: 1rem;}.chat-css-demo-scope .copilotKitMessage.copilotKitAssistantMessage .copilotKitMarkdown,.chat-css-demo-scope .copilotKitMessage.copilotKitAssistantMessageReference#
| CSS Class | Description |
|---|---|
.copilotKitMessages | Main container for all chat messages |
.copilotKitInput | Text input container with typing area and send button |
.copilotKitUserMessage | Styling for user messages |
.copilotKitAssistantMessage | Styling for AI responses |
.copilotKitHeader | Top bar of chat window containing title and controls |
.copilotKitButton | Primary chat toggle button |
.copilotKitWindow | Root container defining overall chat window dimensions |
.copilotKitMarkdown | Styles for rendered markdown content |
.copilotKitCodeBlock | Code snippet container with syntax highlighting |
.copilotKitSidebar | Styles for sidebar chat mode |
.copilotKitPopup | Styles for popup chat mode |
Custom Fonts#
You can customize the fonts by updating the fontFamily property on the
relevant CopilotKit classes:
.copilotKitMessages {
font-family: "Arial, sans-serif";
}
.copilotKitInput {
font-family: "Arial, sans-serif";
}Custom Icons#
Customize icons by passing the icons prop to CopilotSidebar, CopilotPopup,
or CopilotChat:
<CopilotChat
icons={{
openIcon: <YourOpenIconComponent />,
closeIcon: <YourCloseIconComponent />,
}}
/>Custom Labels#
Customize all user-facing copy via the labels prop:
<CopilotChat
labels={{
welcomeMessageText: "Hello! How can I help you today?",
modalHeaderTitle: "My Copilot",
chatInputPlaceholder: "Ask me anything!",
}}
/>