# http://docs.copilotkit.ai llms-full.txt ## CopilotKit Documentation CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageWhat is CopilotKit? # Introduction Build production-ready Copilots and Agents effortlessly. # [What is CopilotKit?](https://docs.copilotkit.ai/\#what-is-copilotkit) At its core, CopilotKit is a set of tools that make it easy to **let your users work** **alongside Large Language Models (LLMs) to accomplish generative tasks** directly in your application. Instead of just using the LLM to generate content, you can let it take direct action alongside your users. Interacting with these models can be done directly ( **Standard**) or through agents ( **CoAgents**). ## [Standard](https://docs.copilotkit.ai/\#standard) Utilize CopilotKit's standard agentic runloop to get started quickly. [**Quickstart** \\ Get started with CopilotKit directly in your application.](https://docs.copilotkit.ai/quickstart) [**Tutorial** \\ Build an AI todo app with CopilotKit in minutes.](https://docs.copilotkit.ai/tutorials/ai-todo-app/overview) ## [CoAgents](https://docs.copilotkit.ai/\#coagents) When you need **complete control** over the agentic runloop, you can use **CoAgents**. Bridge the remaining gap between demos and production-ready experiences. [**LangGraph** \\ User-interactive agents with LangGraph.](https://docs.copilotkit.ai/coagents) [CrewAI\\ **CrewAI Crews** \\ Build multi-agent workflows with CrewAI.](https://docs.copilotkit.ai/crewai-crews) [CrewAI\\ **CrewAI Flows** \\ Build multi-agent workflows with CrewAI.](https://docs.copilotkit.ai/crewai-flows) ## [CopilotKit in Action](https://docs.copilotkit.ai/\#copilotkit-in-action) Need some inspiration? Check out somethings we've built with CopilotKit. [**Feature Viewer** \\ Learn about all of the best features CopilotKit has to offer with an interactive experience.](https://feature-viewer-langgraph.vercel.app/) [**Spreadsheet Copilot** \\ A powerful spreadsheet assistant that helps users analyze data, create formulas, and generate insights.](https://spreadsheet-demo-tau.vercel.app/) [**SaaS Copilot** \\ An AI-powered banking interface that helps users understand and interact with their finances.](https://brex-demo-temp.vercel.app/) [**Agent-Native Travel Planner** \\ Interactive travel planning assistant that helps users generate and build travel itineraries.](https://examples-coagents-ai-travel-app.vercel.app/) [**Agent-Native Research Canvas** \\ An intelligent research assistant that helps users synthesize information across multiple sources.](https://examples-coagents-research-canvas-ui.vercel.app/) ## [How does CopilotKit work?](https://docs.copilotkit.ai/\#how-does-copilotkit-work) CopilotKit is thoughtfully architected to scale with you, your teams, and your product. ![](https://docs.copilotkit.ai/_next/image?url=%2Fimages%2Farchitecture-diagram.png&w=3840&q=75) ## [Common Questions](https://docs.copilotkit.ai/\#common-questions) We've got answers to some common questions! ### What is a Copilot? ### What are the main features of CopilotKit? ### How does it all work? ### Can I use any LLM with CopilotKit? [Next\\ \\ Quickstart](https://docs.copilotkit.ai/quickstart) ### On this page [What is CopilotKit?](https://docs.copilotkit.ai/#what-is-copilotkit) [Standard](https://docs.copilotkit.ai/#standard) [CoAgents](https://docs.copilotkit.ai/#coagents) [CopilotKit in Action](https://docs.copilotkit.ai/#copilotkit-in-action) [How does CopilotKit work?](https://docs.copilotkit.ai/#how-does-copilotkit-work) [Common Questions](https://docs.copilotkit.ai/#common-questions) [Concierge](https://docs.copilotkit.ai/#concierge) [Worker](https://docs.copilotkit.ai/#worker) [Batteries included chat components](https://docs.copilotkit.ai/#batteries-included-chat-components) [Deeply integrated Copilots](https://docs.copilotkit.ai/#deeply-integrated-copilots) [Rich agentic experiences](https://docs.copilotkit.ai/#rich-agentic-experiences) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/(root)/index.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## Copilot Infrastructure Overview CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageCopilot Infrastructure for LangGraph Agents # Introduction Build Agent-Native Applications (ANAs) powered by CopilotKit and LangGraph. # [Copilot Infrastructure for LangGraph Agents](https://docs.copilotkit.ai/coagents\#copilot-infrastructure-for-langgraph-agents) Full user-interaction infrastructure for your agents, to turn your agents into Copilot Agents (CoAgents). ![CoAgents demonstration](https://docs.copilotkit.aihttps://cdn.copilotkit.ai/docs/copilotkit/images/CoAgents.gif) ## [Building blocks of a CoAgent](https://docs.copilotkit.ai/coagents\#building-blocks-of-a-coagent) Everything you need to build Agent-Native Applications (ANAs), right out of the box. [Agentic Chat UI\\ \\ In-app chat powered by your agent.](https://docs.copilotkit.ai/coagents/agentic-chat-ui) [Shared State\\ \\ Your agent can see everything in your app, and vice versa.](https://docs.copilotkit.ai/coagents/shared-state) [Generative UI\\ \\ UI that updates in real-time based on your agent's state.](https://docs.copilotkit.ai/coagents/generative-ui) [Frontend Tools\\ \\ Give your agent the ability to take action in your application.](https://docs.copilotkit.ai/coagents/frontend-actions) [Multi-Agent Coordination\\ \\ Route your agent to the right agent based on the user's request.](https://docs.copilotkit.ai/coagents/multi-agent-flows) [Human-in-the-Loop\\ \\ Set smart checkpoints where humans can guide your agents.](https://docs.copilotkit.ai/coagents/human-in-the-loop) ## [CoAgents in action](https://docs.copilotkit.ai/coagents\#coagents-in-action) See **CoAgents** in action with some videos and examples we've made to demonstrate their power. IntroductionAgent-Native Travel Planner (ANA)Agent-Native Research Canvas (ANA) Introduction [Demo](https://examples-coagents-research-canvas-ui.vercel.app/) Hear from the CEO of CopilotKit, Atai Barkai, and learn how CoAgents are paving the way for the next generation of AI-native apps. CoAgents Public Beta - YouTube CopilotKit 1.27K subscribers [CoAgents Public Beta](https://www.youtube.com/watch?v=tVjVYJE-Nic) CopilotKit Search Watch later Share Copy link Info Shopping Tap to unmute If playback doesn't begin shortly, try restarting your device. More videos ## More videos You're signed out Videos you watch may be added to the TV's watch history and influence TV recommendations. To avoid this, cancel and sign in to YouTube on your computer. CancelConfirm Share Include playlist An error occurred while retrieving sharing information. Please try again later. [Watch on](https://www.youtube.com/watch?v=tVjVYJE-Nic&embeds_referring_euri=https%3A%2F%2Fdocs.copilotkit.ai%2F&embeds_referring_origin=https%3A%2F%2Fdocs.copilotkit.ai) 0:00 0:00 / 1:48•Live • [Watch on YouTube](https://www.youtube.com/watch?v=tVjVYJE-Nic "Watch on YouTube") ## [Ready to get started?](https://docs.copilotkit.ai/coagents\#ready-to-get-started) Get started with CoAgents in as little as 5 minutes with one of our guides or tutorials. [Quickstart\\ \\ Learn how to build your first CoAgent in 10 minutes.](https://docs.copilotkit.ai/coagents/quickstart/langgraph) [Travel Agent\\ \\ Learn how to build an agent-native travel app with CopilotKit & LangGraph.](https://docs.copilotkit.ai/coagents/tutorials/ai-travel-app) [Researcher Agent\\ \\ Learn how to build an agent-native researcher with CopilotKit & LangGraph.](https://docs.copilotkit.ai/coagents/videos/research-canvas) ## [Common Questions](https://docs.copilotkit.ai/coagents\#common-questions) Have a question about CoAgents? You're in the right place! ### Can you explain what a CoAgent is in more detail? ### Can I attach to an existing thread? ### Can I use CopilotKit without LangGraph? [Next\\ \\ Quickstart (LangGraph)](https://docs.copilotkit.ai/coagents/quickstart/langgraph) ### On this page [Copilot Infrastructure for LangGraph Agents](https://docs.copilotkit.ai/coagents#copilot-infrastructure-for-langgraph-agents) [Building blocks of a CoAgent](https://docs.copilotkit.ai/coagents#building-blocks-of-a-coagent) [CoAgents in action](https://docs.copilotkit.ai/coagents#coagents-in-action) [Ready to get started?](https://docs.copilotkit.ai/coagents#ready-to-get-started) [Common Questions](https://docs.copilotkit.ai/coagents#common-questions) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/coagents/index.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## CopilotKit API Reference CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this page # API Reference API Reference for CopilotKit's components, classes and hooks. [**UI Components** \\ See the list of all available UI components in CopilotKit.](https://docs.copilotkit.ai/reference/components/chat/CopilotChat) [**Hooks** \\ See the list of all available hooks in CopilotKit.](https://docs.copilotkit.ai/reference/hooks/useCopilotReadable) [**Classes** \\ See the list of all available classes in CopilotKit.](https://docs.copilotkit.ai/reference/classes/CopilotRuntime) [**LLM Adapters** \\ See the list of all available LLM Adapters in CopilotKit.](https://docs.copilotkit.ai/reference/classes/llm-adapters/OpenAIAdapter) [**SDKs** \\ Python and JavaScript SDKs for CopilotKit.](https://docs.copilotkit.ai/reference/sdk/python/LangGraph) [Next\\ \\ All Chat Components](https://docs.copilotkit.ai/reference/components/chat) ### On this page No Headings [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/reference/index.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## Copilot Infrastructure Overview CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageCopilot Infrastructure for CrewAI Flows # Introduction Build Agent-Native Applications (ANAs) powered by CopilotKit and CrewAI Flows. # [Copilot Infrastructure for CrewAI Flows](https://docs.copilotkit.ai/crewai-flows\#copilot-infrastructure-for-crewai-flows) Full user-interaction infrastructure for your agents, to turn your agents into Copilot Agents (CoAgents). ## [Building blocks of a CoAgent](https://docs.copilotkit.ai/crewai-flows\#building-blocks-of-a-coagent) Everything you need to build Agent-Native Applications (ANAs), right out of the box. [Agentic Chat UI\\ \\ In-app chat powered by your agent.](https://docs.copilotkit.ai/crewai-flows/agentic-chat-ui) [Shared State\\ \\ Your agent can see everything in your app, and vice versa.](https://docs.copilotkit.ai/crewai-flows/shared-state) [Generative UI\\ \\ UI that updates in real-time based on your agent's state.](https://docs.copilotkit.ai/crewai-flows/generative-ui) [Frontend Tools\\ \\ Give your agent the ability to take action in your application.](https://docs.copilotkit.ai/crewai-flows/frontend-actions) [Multi-Agent Coordination\\ \\ Route your agent to the right agent based on the user's request.](https://docs.copilotkit.ai/crewai-flows/multi-agent-flows) [Human-in-the-Loop\\ \\ Set smart checkpoints where humans can guide your agents.](https://docs.copilotkit.ai/crewai-flows/human-in-the-loop) ## [Ready to get started?](https://docs.copilotkit.ai/crewai-flows\#ready-to-get-started) Get started with CoAgents in as little as 5 minutes with one of our guides or tutorials. [Quickstart\\ \\ Learn how to build your first CoAgent in 10 minutes.](https://docs.copilotkit.ai/crewai-flows/quickstart/crewai) ## [Common Questions](https://docs.copilotkit.ai/crewai-flows\#common-questions) Have a question about CoAgents? You're in the right place! ### Can you explain what a CoAgent is in more detail? ### Can I attach to an existing thread? [Next\\ \\ Quickstart CrewAI Flows](https://docs.copilotkit.ai/crewai-flows/quickstart/crewai) ### On this page [Copilot Infrastructure for CrewAI Flows](https://docs.copilotkit.ai/crewai-flows#copilot-infrastructure-for-crewai-flows) [Building blocks of a CoAgent](https://docs.copilotkit.ai/crewai-flows#building-blocks-of-a-coagent) [Ready to get started?](https://docs.copilotkit.ai/crewai-flows#ready-to-get-started) [Common Questions](https://docs.copilotkit.ai/crewai-flows#common-questions) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/crewai-flows/index.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## LangGraph Quickstart Guide CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pagePrerequisites # Quickstart (LangGraph) Turn your LangGraph into an agent-native application in 10 minutes. ## [Prerequisites](https://docs.copilotkit.ai/coagents/quickstart/langgraph\#prerequisites) Before you begin, you'll need the following: - [**LangSmith API key**](https://docs.smith.langchain.com/administration/how_to_guides/organization_management/create_account_api_key#api-keys) - [**OpenAI API key**](https://platform.openai.com/api-keys) ## [Getting started](https://docs.copilotkit.ai/coagents/quickstart/langgraph\#getting-started) ### [Install CopilotKit](https://docs.copilotkit.ai/coagents/quickstart/langgraph\#install-copilotkit) First, install the latest packages for CopilotKit into your frontend. npmpnpmyarnbun ``` npm install @copilotkit/react-ui @copilotkit/react-core ``` Do you already have a LangGraph agent? You will need a LangGraph agent to get started with CoAgents! Either bring your own or feel free to use our starter repo. Bring your own LangGraph agent I already have a LangGraph agent and want to use it with CopilotKit. ![CopilotKit Logo](https://docs.copilotkit.aihttps://cdn.copilotkit.ai/docs/copilotkit/images/copilotkit-logo.svg) Use the CoAgents Starter repo I don't have a LangGraph agent yet, but want to get started quickly. ### [Start your LangGraph Agent](https://docs.copilotkit.ai/coagents/quickstart/langgraph\#start-your-langgraph-agent) Local (LangGraph Studio)Self hosted (FastAPI)LangGraph Platform For local development, you can use the [LangGraph CLI](https://langchain-ai.github.io/langgraph/cloud/reference/cli/) to start a development server and LangGraph studio session. You will need a [LangSmith account](https://smith.langchain.com/) to use this method. ``` # For Python 3.11 or above langgraph dev --host localhost --port 8000 ``` ``` # For TypeScript with Node 18 or above npx @langchain/langgraph-cli dev --host localhost --port 8000 ``` After starting the LangGraph server, the deployment URL will be `http://localhost:8000`. ### Having trouble? Choose your connection method Now you need to connect your LangGraph agent to CopilotKit. Copilot Cloud (Recommended) I want to host my Copilot on Copilot Cloud Self-Hosted Copilot Runtime I want to self-host the Copilot Runtime ### [Add a remote endpoint for your LangGraph agent](https://docs.copilotkit.ai/coagents/quickstart/langgraph\#add-a-remote-endpoint-for-your-langgraph-agent) Using Copilot Cloud, you need to connect a remote endpoint that will connect to your LangGraph agent. Local (LangGraph Studio)Self hosted (FastAPI)LangGraph Platform When running your LangGraph agent locally, you can open a tunnel to it so Copilot Cloud can connect to it. First, make sure you're logged in to [Copilot Cloud](https://cloud.copilotkit.ai/), and then authenticate the CLI by running: ``` npx copilotkit@latest login ``` Once authenticated, run: ``` npx copilotkit@latest dev --port 8000 ``` ### [Setup your CopilotKit provider](https://docs.copilotkit.ai/coagents/quickstart/langgraph\#setup-your-copilotkit-provider) The [``](https://docs.copilotkit.ai/reference/components/CopilotKit) component must wrap the Copilot-aware parts of your application. For most use-cases, it's appropriate to wrap the CopilotKit provider around the entire app, e.g. in your layout.tsx. Since we're using Copilot Cloud, we need to grab our public API key from the [Copilot Cloud dashboard](https://cloud.copilotkit.ai/). layout.tsx ``` import "./globals.css"; import { ReactNode } from "react"; import { CopilotKit } from "@copilotkit/react-core"; export default function RootLayout({ children }: { children: ReactNode }) { return ( {/* Use the public api key you got from Copilot Cloud */} {children} ); } ``` Looking for a way to run multiple LangGraph agents? Check out our [Multi-Agent](https://docs.copilotkit.ai/coagents/multi-agent-flows) guide. ## [Choose a Copilot UI](https://docs.copilotkit.ai/coagents/quickstart/langgraph\#choose-a-copilot-ui) You are almost there! Now it's time to setup your Copilot UI. First, import the default styles in your root component (typically `layout.tsx`) : ``` import "@copilotkit/react-ui/styles.css"; ``` Copilot UI ships with a number of built-in UI patterns, choose whichever one you like. CopilotPopupCopilotSidebarCopilotChatHeadless UI `CopilotPopup` is a convenience wrapper for `CopilotChat` that lives at the same level as your main content in the view hierarchy. It provides **a floating chat interface** that can be toggled on and off. ![Popup Example](https://docs.copilotkit.aihttps://cdn.copilotkit.ai/docs/copilotkit/images/popup-example.gif) ``` import { CopilotPopup } from "@copilotkit/react-ui"; export function YourApp() { return ( <> ); } ``` ### [🎉 Talk to your agent!](https://docs.copilotkit.ai/coagents/quickstart/langgraph\#-talk-to-your-agent) Congrats! You've successfully integrated a LangGraph agent chatbot to your application. To start, try asking a few questions to your agent. ``` Can you tell me a joke? ``` ``` Can you help me understand AI? ``` ``` What do you think about React? ``` ### Having trouble? * * * ## [What's next?](https://docs.copilotkit.ai/coagents/quickstart/langgraph\#whats-next) You've now got a LangGraph agent running in CopilotKit! Now you can start exploring the various ways that CopilotKit can help you build power agent native applications. [**Implement Human in the Loop** \\ Allow your users and agents to collaborate together on tasks.](https://docs.copilotkit.ai/coagents/human-in-the-loop) [**Utilize the Shared State** \\ Learn how to synchronize your agent's state with your UI's state, and vice versa.](https://docs.copilotkit.ai/coagents/shared-state) [**Add some generative UI** \\ Render your agent's progress and output in the UI.](https://docs.copilotkit.ai/coagents/generative-ui) [**Setup frontend actions** \\ Give your agent the ability to call frontend tools, directly updating your application.](https://docs.copilotkit.ai/coagents/frontend-actions) [Previous\\ \\ Introduction](https://docs.copilotkit.ai/coagents) [Next\\ \\ Chat with an Agent](https://docs.copilotkit.ai/coagents/agentic-chat-ui) ### On this page [Prerequisites](https://docs.copilotkit.ai/coagents/quickstart/langgraph#prerequisites) [Getting started](https://docs.copilotkit.ai/coagents/quickstart/langgraph#getting-started) [Install CopilotKit](https://docs.copilotkit.ai/coagents/quickstart/langgraph#install-copilotkit) [Clone the coagents-starter repo and install dependencies:](https://docs.copilotkit.ai/coagents/quickstart/langgraph#clone-the-coagents-starter-repo-and-install-dependencies) [Install dependencies:](https://docs.copilotkit.ai/coagents/quickstart/langgraph#install-dependencies) [Install dependencies:](https://docs.copilotkit.ai/coagents/quickstart/langgraph#install-dependencies-1) [Create a .env file](https://docs.copilotkit.ai/coagents/quickstart/langgraph#create-a-env-file) [Add your API keys](https://docs.copilotkit.ai/coagents/quickstart/langgraph#add-your-api-keys) [Start your LangGraph Agent](https://docs.copilotkit.ai/coagents/quickstart/langgraph#start-your-langgraph-agent) [Add a remote endpoint for your LangGraph agent](https://docs.copilotkit.ai/coagents/quickstart/langgraph#add-a-remote-endpoint-for-your-langgraph-agent) [Setup your CopilotKit provider](https://docs.copilotkit.ai/coagents/quickstart/langgraph#setup-your-copilotkit-provider) [Install Copilot Runtime](https://docs.copilotkit.ai/coagents/quickstart/langgraph#install-copilot-runtime) [Setup a Copilot Runtime Endpoint](https://docs.copilotkit.ai/coagents/quickstart/langgraph#setup-a-copilot-runtime-endpoint) [Add your LangGraph deployment to Copilot Runtime](https://docs.copilotkit.ai/coagents/quickstart/langgraph#add-your-langgraph-deployment-to-copilot-runtime) [Configure the CopilotKit Provider](https://docs.copilotkit.ai/coagents/quickstart/langgraph#configure-the-copilotkit-provider) [Choose a Copilot UI](https://docs.copilotkit.ai/coagents/quickstart/langgraph#choose-a-copilot-ui) [🎉 Talk to your agent!](https://docs.copilotkit.ai/coagents/quickstart/langgraph#-talk-to-your-agent) [What's next?](https://docs.copilotkit.ai/coagents/quickstart/langgraph#whats-next) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/coagents/quickstart/langgraph.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## CrewAI Support CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageCopilot Infrastructure for CrewAI Crews # Introduction Build Agent-Native Applications (ANAs) powered by CopilotKit and CrewAI Flows. # [Copilot Infrastructure for CrewAI Crews](https://docs.copilotkit.ai/crewai-crews\#copilot-infrastructure-for-crewai-crews) Full user-interaction infrastructure for your agents, to turn your agents into Copilot Agents (CoAgents). ## [Building blocks of a CoAgent](https://docs.copilotkit.ai/crewai-crews\#building-blocks-of-a-coagent) Everything you need to build Agent-Native Applications (ANAs), right out of the box. [Agentic Chat UI\\ \\ In-app chat powered by your agent.](https://docs.copilotkit.ai/crewai-crews/agentic-chat-ui) [Shared State\\ \\ Your agent can see everything in your app, and vice versa.](https://docs.copilotkit.ai/crewai-crews/shared-state) [Generative UI\\ \\ UI that updates in real-time based on your agent's state.](https://docs.copilotkit.ai/crewai-crews/generative-ui) [Frontend Tools\\ \\ Give your agent the ability to take action in your application.](https://docs.copilotkit.ai/crewai-crews/frontend-actions) [Multi-Agent Coordination\\ \\ Route your agent to the right agent based on the user's request.](https://docs.copilotkit.ai/crewai-crews/multi-agent-flows) [Human-in-the-Loop\\ \\ Set smart checkpoints where humans can guide your agents.](https://docs.copilotkit.ai/crewai-crews/human-in-the-loop) ## [Ready to get started?](https://docs.copilotkit.ai/crewai-crews\#ready-to-get-started) Get started with CoAgents in as little as 5 minutes with one of our guides or tutorials. [Quickstart\\ \\ Learn how to build your first CoAgent in 10 minutes.](https://docs.copilotkit.ai/crewai-crews/quickstart/crewai) ## [Common Questions](https://docs.copilotkit.ai/crewai-crews\#common-questions) Have a question about CoAgents? You're in the right place! ### Can you explain what a CoAgent is in more detail? [Next\\ \\ Quickstart CrewAI Crews](https://docs.copilotkit.ai/crewai-crews/quickstart/crewai) ### On this page [Copilot Infrastructure for CrewAI Crews](https://docs.copilotkit.ai/crewai-crews#copilot-infrastructure-for-crewai-crews) [Building blocks of a CoAgent](https://docs.copilotkit.ai/crewai-crews#building-blocks-of-a-coagent) [Ready to get started?](https://docs.copilotkit.ai/crewai-crews#ready-to-get-started) [Common Questions](https://docs.copilotkit.ai/crewai-crews#common-questions) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/crewai-crews/index.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## Self-Hosting Copilot Runtime CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageIntegration # Self Hosting (Copilot Runtime) Learn how to self-host the Copilot Runtime. The Copilot Runtime is the back-end component of CopilotKit, handling the communication with LLM, message history, state and more. You may choose to self-host the Copilot Runtime, or [use Copilot Cloud](https://cloud.copilotkit.ai/) (recommended). ## [Integration](https://docs.copilotkit.ai/guides/self-hosting\#integration) ### [Step 1: Create an Endpoint](https://docs.copilotkit.ai/guides/self-hosting\#step-1-create-an-endpoint) ##### Choose your provider: ![OpenAI logo](https://docs.copilotkit.ai/icons/openai.png)OpenAI If you are planning to use a single LangGraph agent in [agent-lock mode](https://docs.copilotkit.ai/coagents/multi-agent-flows) as your agentic backend, your LLM adapter will only be used for peripherals such as suggestions, etc. If you are not sure yet, simply ignore this note. ### [Add your API key](https://docs.copilotkit.ai/guides/self-hosting\#add-your-api-key) Next, add your API key to your `.env` file in the root of your project (unless you prefer to provide it directly to the client): .env ``` OPENAI_API_KEY=your_api_key_here ``` Please note that the code below uses GPT-4o, which requires a paid OpenAI API key. **If you are using a free OpenAI API key**, change the model to a different option such as `gpt-3.5-turbo`. ### [Setup the Runtime Endpoint](https://docs.copilotkit.ai/guides/self-hosting\#setup-the-runtime-endpoint) ### [Serverless Function Timeouts](https://docs.copilotkit.ai/guides/self-hosting\#serverless-function-timeouts) When deploying to serverless platforms (Vercel, AWS Lambda, etc.), be aware that default function timeouts may be too short for CopilotKit's streaming responses: - Vercel defaults: 10s (Hobby), 15s (Pro) - AWS Lambda default: 3s **Solution options:** 1. Increase function timeout: ``` // vercel.json { "functions": { "api/copilotkit/**/*": { "maxDuration": 60 } } } ``` 2. Use [Copilot Cloud](https://cloud.copilotkit.ai/) to avoid timeout issues entirely Next.js App RouterNext.js Pages RouterNode.js ExpressNode.js HTTPNestJS Create a new route to handle the `/api/copilotkit` endpoint. app/api/copilotkit/route.ts ``` import { CopilotRuntime, OpenAIAdapter, copilotRuntimeNextJSAppRouterEndpoint, } from '@copilotkit/runtime'; import { NextRequest } from 'next/server'; const serviceAdapter = new OpenAIAdapter(); const runtime = new CopilotRuntime(); export const POST = async (req: NextRequest) => { const { handleRequest } = copilotRuntimeNextJSAppRouterEndpoint({ runtime, serviceAdapter, endpoint: '/api/copilotkit', }); return handleRequest(req); }; ``` Your Copilot Runtime endpoint should be available at `http://localhost:3000/api/copilotkit`. ### [Step 2: Configure the `` Provider](https://docs.copilotkit.ai/guides/self-hosting\#step-2-configure-the-copilotkit-provider) layout.tsx ``` import "./globals.css"; import { ReactNode } from "react"; import { CopilotKit } from "@copilotkit/react-core"; export default function RootLayout({ children }: { children: ReactNode }) { return ( {/* Make sure to use the URL you configured in the previous step */} {children} ); } ``` ## [Next Steps](https://docs.copilotkit.ai/guides/self-hosting\#next-steps) - [`CopilotRuntime` Reference](https://docs.copilotkit.ai/reference/classes/CopilotRuntime) - [LLM Adapters](https://docs.copilotkit.ai/reference/classes/llm-adapters/OpenAIAdapter) [Previous\\ \\ Copilot Textarea](https://docs.copilotkit.ai/guides/copilot-textarea) [Next\\ \\ Saving and restoring messages](https://docs.copilotkit.ai/guides/messages-localstorage) ### On this page [Integration](https://docs.copilotkit.ai/guides/self-hosting#integration) [Step 1: Create an Endpoint](https://docs.copilotkit.ai/guides/self-hosting#step-1-create-an-endpoint) [Step 2: Configure the Provider](https://docs.copilotkit.ai/guides/self-hosting#step-2-configure-the-copilotkit-provider) [Next Steps](https://docs.copilotkit.ai/guides/self-hosting#next-steps) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/(root)/guides/self-hosting.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## useCopilotAction Hook CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageUsage # useCopilotAction The useCopilotAction hook allows your copilot to take action in the app. ![](https://docs.copilotkit.aihttps://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-action/useCopilotAction.gif) `useCopilotAction` is a React hook that you can use in your application to provide custom actions that can be called by the AI. Essentially, it allows the Copilot to execute these actions contextually during a chat, based on the user’s interactions and needs. Here's how it works: Use `useCopilotAction` to set up actions that the Copilot can call. To provide more context to the Copilot, you can provide it with a `description` (for example to explain what the action does, under which conditions it can be called, etc.). Then you define the parameters of the action, which can be simple, e.g. primitives like strings or numbers, or complex, e.g. objects or arrays. Finally, you provide a `handler` function that receives the parameters and returns a result. CopilotKit takes care of automatically inferring the parameter types, so you get type safety and autocompletion for free. To render a custom UI for the action, you can provide a `render()` function. This function lets you render a custom component or return a string to display. ## [Usage](https://docs.copilotkit.ai/reference/hooks/useCopilotAction\#usage) ### [Simple Usage](https://docs.copilotkit.ai/reference/hooks/useCopilotAction\#simple-usage) ``` useCopilotAction({ name: "sayHello", description: "Say hello to someone.", parameters: [\ {\ name: "name",\ type: "string",\ description: "name of the person to say greet",\ },\ ], handler: async ({ name }) => { alert(`Hello, ${name}!`); }, }); ``` ## [Generative UI](https://docs.copilotkit.ai/reference/hooks/useCopilotAction\#generative-ui) This hooks enables you to dynamically generate UI elements and render them in the copilot chat. For more information, check out the [Generative UI](https://docs.copilotkit.ai/guides/generative-ui) page. ## [Parameters](https://docs.copilotkit.ai/reference/hooks/useCopilotAction\#parameters) actionActionrequired The function made available to the Copilot. See [Action](https://docs.copilotkit.ai/reference/hooks/useCopilotAction#action). namestringrequired The name of the action. handler(args) => Promiserequired The handler of the action. descriptionstring A description of the action. This is used to instruct the Copilot on how to use the action. available'enabled' \| 'disabled' \| 'remote' Use this property to control when the action is available to the Copilot. When set to `"remote"`, the action is available only for remote agents. followUpboolean Default:"true" Whether to report the result of a function call to the LLM which will then provide a follow-up response. Pass `false` to disable parametersParameter\[\] The parameters of the action. See [Parameter](https://docs.copilotkit.ai/reference/hooks/useCopilotAction#parameter). namestringrequired The name of the parameter. typestringrequired The type of the argument. One of: - `"string"` - `"number"` - `"boolean"` - `"object"` - `"object[]"` - `"string[]"` - `"number[]"` - `"boolean[]"` descriptionstring A description of the argument. This is used to instruct the Copilot on what this argument is used for. enumstring\[\] For string arguments, you can provide an array of possible values. requiredboolean Whether or not the argument is required. Defaults to true. attributes If the argument is of a complex type, i.e. `object` or `object[]`, this field lets you define the attributes of the object. For example: ``` { name: "addresses", description: "The addresses extracted from the text.", type: "object[]", attributes: [\ {\ name: "street",\ type: "string",\ description: "The street of the address.",\ },\ {\ name: "city",\ type: "string",\ description: "The city of the address.",\ },\ // ...\ ], } ``` renderstring \| (props: ActionRenderProps) => string Render lets you define a custom component or string to render instead of the default. You can either pass in a string or a function that takes the following props: status'inProgress' \| 'executing' \| 'complete' - `"inProgress"`: arguments are dynamically streamed to the function, allowing you to adjust your UI in real-time. - `"executing"`: The action handler is executing. - `"complete"`: The action handler has completed execution. argsT The arguments passed to the action in real time. When the status is `"inProgress"`, they are possibly incomplete. resultany The result returned by the action. It is only available when the status is `"complete"`. renderAndWaitForResponse(props: ActionRenderPropsWait) => React.ReactElement This is similar to `render`, but provides a `respond` function in the props that you must call with the user's response. The component will remain rendered until `respond` is called. The response will be passed as the result to the action handler. status'inProgress' \| 'executing' \| 'complete' - `"inProgress"`: arguments are dynamically streamed to the function, allowing you to adjust your UI in real-time. - `"executing"`: The action handler is executing. - `"complete"`: The action handler has completed execution. argsT The arguments passed to the action in real time. When the status is `"inProgress"`, they are possibly incomplete. respond(result: any) => void A function that must be called with the user's response. The response will be passed as the result to the action handler. Only available when status is `"executing"`. resultany The result returned by the action. It is only available when the status is `"complete"`. dependenciesany\[\] An optional array of dependencies. [Previous\\ \\ useCopilotReadable](https://docs.copilotkit.ai/reference/hooks/useCopilotReadable) [Next\\ \\ useCopilotAdditionalInstructions](https://docs.copilotkit.ai/reference/hooks/useCopilotAdditionalInstructions) ### On this page [Usage](https://docs.copilotkit.ai/reference/hooks/useCopilotAction#usage) [Simple Usage](https://docs.copilotkit.ai/reference/hooks/useCopilotAction#simple-usage) [Generative UI](https://docs.copilotkit.ai/reference/hooks/useCopilotAction#generative-ui) [Parameters](https://docs.copilotkit.ai/reference/hooks/useCopilotAction#parameters) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/reference/hooks/useCopilotAction.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## State Machine Guide CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageOverview # State Machines Learn how to guide users through multi-step conversations using a state machine pattern. ## [Overview](https://docs.copilotkit.ai/cookbook/state-machine\#overview) When building chat-based applications, you often need to guide users through a series of steps or **stages**. This recipe shows how to implement a state machine pattern to keep your assistant focused and on-track. - Live Example: [https://state-machine-copilot.vercel.app/](https://state-machine-copilot.vercel.app/) - Example Source Code: [https://github.com/CopilotKit/CopilotKit/tree/main/examples/copilot-state-machine](https://github.com/CopilotKit/CopilotKit/tree/main/examples/copilot-state-machine) This recipe assumes you have completed the [quickstart guide](https://docs.copilotkit.ai/quickstart) and have a basic CopilotKit application running. ### [What is a State Machine?](https://docs.copilotkit.ai/cookbook/state-machine\#what-is-a-state-machine) A state machine is a model where your application can be in exactly one state at a time, with clear rules about how to move between states. For chat applications, this means: - The assistant knows exactly what stage of the conversation it's in - Only certain actions are available in each stage - There are clear rules for moving to the next stage ### [State Machines in CopilotKit](https://docs.copilotkit.ai/cookbook/state-machine\#state-machines-in-copilotkit) When implementing a state machine in CopilotKit, the main piece that enables this pattern is the `available` prop present in most of our hooks. This prop will allow you conditionally control what instructions, context, and actions are available to the assistant. In this recipe, we combine the `available` prop with React state to control when each stage is active, sometimes through standard deterministic update (button clicks), and sometimes through LLM-driven actions. ![State Machine Architecture](https://docs.copilotkit.ai/_next/image?url=%2Fimages%2Fstate-machine-arch.png&w=3840&q=75) ## [Basic Implementation](https://docs.copilotkit.ai/cookbook/state-machine\#basic-implementation) ### [Create a stage](https://docs.copilotkit.ai/cookbook/state-machine\#create-a-stage) Each stage is composed of stage-specific instructions, context, and actions. These are enabled or disabled as the stage changes via the `available` prop. In this example of a stage, we are extracting a user's name and ensuring it is not in a list of other names. ``` import { useCopilotAdditionalInstructions, useCopilotAction, useCopilotReadable } from "@copilotkit/react-core"; // ... /* * Not required, but it is convenient to use a dedicated hook to define each * stage of the state machine */ function useStageOne( stage: string, setStage: (stage: string) => void, setName: (name: string) => void ) { /* * Each stage can define its own instructions, context, and transitions * (implemented via copilotActions). We transition between stages by simply * setting the `stage` variable from the handler of the transition: */ // Add additional instructions to the system prompt if this stage is active useCopilotAdditionalInstructions({ instructions: "Ask for the user's name politely.", // Use "available" argument to enable this only when the stage is correct! available: stage === "one" ? "available" : "disabled" }) // Add context to the system prompt if this stage is active useCopilotReadable({ description: "Other names", value: ["John", "Jane", "Jim"], available: stage === "one" ? "available" : "disabled" }) // Add an action to the assistant that transitions to the next stage if this stage is active useCopilotAction({ name: "transitionToNextStage", description: "Moves to the next stage, only call is the user's name is not in the list of other names", available: stage === "one" ? "available" : "disabled", parameters: [\ { name: "name", type: "string", description: "The name of the user", required: true },\ ], handler: ({ name }) => { // Perform any state updates given the user's input setName(name); // Transition to the next stage setStage("two"); } }); } ``` ### [Create another stage](https://docs.copilotkit.ai/cookbook/state-machine\#create-another-stage) Now, let's create a second stage that's simple and just greets the user by name as a pirate. This is mainly just to demonstrate how to add any additional stages. The name will be made available to this stage in the next step. ``` import { useCopilotAdditionalInstructions } from "@copilotkit/react-core"; // ... function useStageTwo(stage: string) => void) { // Add stage-specific instructions - only available in stage "two" useCopilotAdditionalInstructions({ instructions: "Talk to the user about their name and refer to them like a pirate would.", available: stage === "two" ? "available" : "disabled" }) // ... } // Any additional stages you want to add... ``` ### [Put it all together](https://docs.copilotkit.ai/cookbook/state-machine\#put-it-all-together) Finally, bring everything together into a chat component: ``` import { useState } from "react"; import { CopilotKit, useCopilotReadable } from "@copilotkit/react-core"; import { CopilotChat } from "@copilotkit/react-ui"; // ... function StateMachineChat() { // Track the current stage and user's name const [stage, setStage] = useState("one"); const [name, setName] = useState(""); // Readable context available across all stages useCopilotReadable({ description: "User's name", value: name, }, [name]) // Initialize all stages with their required props useStageOne(stage, setStage, setName); useStageTwo(stage); // any additional stages... return ( ) } ``` ### Full example code ### [🎉 You've implemented a state machine!](https://docs.copilotkit.ai/cookbook/state-machine\#-youve-implemented-a-state-machine) To recap, each stage hook uses the `available` prop to control when its instructions, context, and actions are accessible to the assistant. This ensures that the assistant only uses the correct tools and context for the current stage. Next, let's see some advanced patterns you can implement with these fundamentals. ## [Advanced Patterns](https://docs.copilotkit.ai/cookbook/state-machine\#advanced-patterns) This state machine pattern can be extended for complex interactions. Below are some advanced patterns you can implement with code sourced in our [car sales example](https://github.com/CopilotKit/CopilotKit/tree/main/examples/copilot-state-machine) which you already saw a demo of in the [overview](https://docs.copilotkit.ai/cookbook/state-machine#overview). ### [Stage Transition Approaches](https://docs.copilotkit.ai/cookbook/state-machine\#stage-transition-approaches) #### [Code-driven Stage Transitions](https://docs.copilotkit.ai/cookbook/state-machine\#code-driven-stage-transitions) When you want to transition between stages, you can do so by setting the `stage` deterministically, at any point in code. ``` const [stage, setStage] = useState("one"); // ... ``` The car sales demo uses this approach in generative UI (for more on generative UI, see the [section below](https://docs.copilotkit.ai/cookbook/state-machine#generative-ui)) to transition between stages when a user submits their contact information. Click here for the [source code](https://github.com/CopilotKit/CopilotKit/tree/main/examples/copilot-state-machine/src/lib/stages/use-stage-get-contact-info.tsx) src/lib/stages/use-stage-get-contact-info.tsx ``` // imports ... export function useStageGetContactInfo() { const { setContactInfo, stage, setStage } = useGlobalState(); // ... // Render the ContactInfo component and wait for the user's response. useCopilotAction( { name: "getContactInformation", description: "Get the contact information of the user", available: stage === "getContactInfo" ? "enabled" : "disabled", renderAndWaitForResponse: ({ status, respond }) => { return ( { // Commit the contact information to the global state. setContactInfo({ name, email, phone }); // Let the agent know that the user has submitted their contact information. respond?.("User has submitted their contact information."); // This move the state machine to the next stage, buildCar deterministically. setStage("buildCar"); }} /> ); }, }, [stage], ); } ``` #### [LLM-Driven Stage Transitions](https://docs.copilotkit.ai/cookbook/state-machine\#llm-driven-stage-transitions) Sometimes you need stages that can transition to different next stages based on user input or LLM-driven actions. Click here for the [source code](https://github.com/CopilotKit/CopilotKit/tree/main/examples/copilot-state-machine/src/lib/stages/use-stage-sell-financing.tsx) src/lib/stages/use-stage-sell-financing.tsx ``` function useStageSellFinancing() { const { stage, setStage } = useGlobalState(); const isActive = stage === "sellFinancing"; // Provide context to the AI useCopilotReadable({ description: "Financing Information", value: "Current promotion: 0% financing for 60 months...", available: isActive ? "enabled" : "disabled" }); // Different paths based on financing choice by user, LLM will decide which path to take useCopilotAction({ name: "selectFinancing", description: "Select the financing option", available: stage === "sellFinancing" ? "enabled" : "disabled", handler: () => setStage("getFinancingInfo"), }, [stage]); useCopilotAction({ name: "selectNoFinancing", description: "Select the no financing option", available: stage === "sellFinancing" ? "enabled" : "disabled", handler: () => setStage("getPaymentInfo"), }, [stage]); } ``` ### [Generative UI](https://docs.copilotkit.ai/cookbook/state-machine\#generative-ui) [Generative UI](https://docs.copilotkit.ai/guides/generative-ui) is a pattern where tool calls are streamed and rendered for the user to visualize the progress an agent is making. It can also be combined with the **Human-in-the-loop pattern** to allow checkpoints where the user can intervene and help guide the agent. When combined with the state machine pattern, you can build deep and interactive conversations with the user. For example, the `buildCar` stage in the car sales demo uses generative UI to show the user available cars that they can choose from. Click here for the [source code](https://github.com/CopilotKit/CopilotKit/tree/main/examples/copilot-state-machine/src/lib/stages/use-stage-build-car.tsx) Build Car StageShow Car Component src/lib/stages/use-stage-build-car.tsx ``` export function useStageBuildCar() { const { setSelectedCar, stage, setStage } = useGlobalState(); // ... useCopilotAction({ name: "showCar", description: "Show a single car that you have in mind. Do not call this more than once, call `showMultipleCars` if you have multiple cars to show.", available: stage === "buildCar" ? "enabled" : "disabled", parameters: [\ // excluded for brevity, see source code link above for more detail\ ], renderAndWaitForResponse: ({ args, status, respond }) => { const { car } = args; return ( { setSelectedCar((car as Car) || ({} as Car)); respond?.("User has selected a car you can see it in your readables, the system will now move to the next state, do not call call nextState."); setStage("sellFinancing"); }} onReject={() => respond?.("User wants to select a different car, please stay in this state and help them select a different car")} /> ); }, }, [stage]); // ... } ``` ### [Initial message loading](https://docs.copilotkit.ai/cookbook/state-machine\#initial-message-loading) To add an initial message to the chat, we can use the `appendMessage` function provided by the `useCopilotChat` hook. Improved experience coming soon This is a temporary solution and we will be improving this in the near future. Click here for the [source code](https://github.com/CopilotKit/CopilotKit/tree/main/examples/copilot-state-machine/src/components/car-sales-chat.tsx) src/components/car-sales-chat.tsx ``` import { useCopilotChat } from "@copilotkit/react-core"; // ... const { appendMessage, isLoading } = useCopilotChat(); // Render an initial message when the chat is first loaded useEffect(() => { if (initialMessageSent || isLoading) return; setTimeout(() => { appendMessage( new TextMessage({ content: "Hi, I'm Fio, your AI car salesman. First, let's get your contact information before we get started.", role: MessageRole.Assistant, }), ); setInitialMessageSent(true); }, 500); }, [initialMessageSent, appendMessage, isLoading]); // ... ``` ### [Tools When Entering a Stage](https://docs.copilotkit.ai/cookbook/state-machine\#tools-when-entering-a-stage) Sometimes you'll want to guide the AI to call a specific tool when entering a stage. The payment info stage demonstrates how to guide the AI to make specific tool calls by adding additional instructions to call the `getPaymentInformation` tool explicitly. Click here for the [source code](https://github.com/CopilotKit/CopilotKit/tree/main/examples/copilot-state-machine/src/lib/stages/use-stage-get-payment-info.tsx) src/lib/stages/use-stage-get-payment-info.tsx ``` export function useStageGetPaymentInfo() { const { setCardInfo, stage, setStage } = useGlobalState(); // Conditionally add additional instructions for the agent's prompt. useCopilotAdditionalInstructions({ available: stage === "getPaymentInfo" ? "enabled" : "disabled", instructions: ` CURRENT STATE: You are now getting the payment information of the user. Say, 'Great! Now I need to get your payment information.' and MAKE SURE to then call the 'getPaymentInformation' action. `, }, [stage]); // ... } ``` ## [Recap](https://docs.copilotkit.ai/cookbook/state-machine\#recap) This recipe introduced a powerful pattern for building conversational AI applications using state machines. By breaking down complex interactions into discrete stages, each with focused instructions and actions, we can create more maintainable and user-friendly experiences. With this pattern, you can start building your own multi-stage conversations. ## [Need Help?](https://docs.copilotkit.ai/cookbook/state-machine\#need-help) Need help or want to share what you've built? Join our [Discord community](https://discord.gg/6dffbvGU3D) or open an issue on [GitHub](https://github.com/CopilotKit/CopilotKit/issues/new/choose). [Previous\\ \\ Next Steps](https://docs.copilotkit.ai/tutorials/ai-powered-textarea/next-steps) [Next\\ \\ Common Issues](https://docs.copilotkit.ai/troubleshooting/common-issues) ### On this page [Overview](https://docs.copilotkit.ai/cookbook/state-machine#overview) [What is a State Machine?](https://docs.copilotkit.ai/cookbook/state-machine#what-is-a-state-machine) [State Machines in CopilotKit](https://docs.copilotkit.ai/cookbook/state-machine#state-machines-in-copilotkit) [Basic Implementation](https://docs.copilotkit.ai/cookbook/state-machine#basic-implementation) [Create a stage](https://docs.copilotkit.ai/cookbook/state-machine#create-a-stage) [Create another stage](https://docs.copilotkit.ai/cookbook/state-machine#create-another-stage) [Put it all together](https://docs.copilotkit.ai/cookbook/state-machine#put-it-all-together) [🎉 You've implemented a state machine!](https://docs.copilotkit.ai/cookbook/state-machine#-youve-implemented-a-state-machine) [Advanced Patterns](https://docs.copilotkit.ai/cookbook/state-machine#advanced-patterns) [Stage Transition Approaches](https://docs.copilotkit.ai/cookbook/state-machine#stage-transition-approaches) [Code-driven Stage Transitions](https://docs.copilotkit.ai/cookbook/state-machine#code-driven-stage-transitions) [LLM-Driven Stage Transitions](https://docs.copilotkit.ai/cookbook/state-machine#llm-driven-stage-transitions) [Generative UI](https://docs.copilotkit.ai/cookbook/state-machine#generative-ui) [Initial message loading](https://docs.copilotkit.ai/cookbook/state-machine#initial-message-loading) [Tools When Entering a Stage](https://docs.copilotkit.ai/cookbook/state-machine#tools-when-entering-a-stage) [Recap](https://docs.copilotkit.ai/cookbook/state-machine#recap) [Need Help?](https://docs.copilotkit.ai/cookbook/state-machine#need-help) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/(root)/cookbook/state-machine.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ![State Machine Architecture](https://docs.copilotkit.ai/_next/image?url=%2Fimages%2Fstate-machine-arch.png&w=3840&q=75) ## Agent State Management CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageUsage # useCoAgent The useCoAgent hook allows you to share state bidirectionally between your application and the agent. Usage of this hook assumes some additional setup in your application, for more information on that see the CoAgents [getting started guide](https://docs.copilotkit.ai/coagents/quickstart/langgraph). ![CoAgents demonstration](https://docs.copilotkit.aihttps://cdn.copilotkit.ai/docs/copilotkit/images/coagents/SharedStateCoAgents.gif) This hook is used to integrate an agent into your application. With its use, you can render and update the state of an agent, allowing for a dynamic and interactive experience. We call these shared state experiences agentic copilots, or CoAgents for short. ## [Usage](https://docs.copilotkit.ai/reference/hooks/useCoAgent\#usage) ### [Simple Usage](https://docs.copilotkit.ai/reference/hooks/useCoAgent\#simple-usage) ``` import { useCoAgent } from "@copilotkit/react-core"; type AgentState = { count: number; } const agent = useCoAgent({ name: "my-agent", initialState: { count: 0, }, }); ``` `useCoAgent` returns an object with the following properties: ``` const { name, // The name of the agent currently being used. nodeName, // The name of the current LangGraph node. state, // The current state of the agent. setState, // A function to update the state of the agent. running, // A boolean indicating if the agent is currently running. start, // A function to start the agent. stop, // A function to stop the agent. run, // A function to re-run the agent. Takes a HintFunction to inform the agent why it is being re-run. } = agent; ``` Finally we can leverage these properties to create reactive experiences with the agent! ``` const { state, setState } = useCoAgent({ name: "my-agent", initialState: { count: 0, }, }); return (

Count: {state.count}

); ``` This reactivity is bidirectional, meaning that changes to the state from the agent will be reflected in the UI and vice versa. ## [Parameters](https://docs.copilotkit.ai/reference/hooks/useCoAgent\#parameters) optionsUseCoagentOptionsrequired The options to use when creating the coagent. namestringrequired The name of the agent to use. initialStateT \| any The initial state of the agent. stateT \| any State to manage externally if you are using this hook with external state management. setState(newState: T \| ((prevState: T \| undefined) => T)) => void A function to update the state of the agent if you are using this hook with external state management. [Previous\\ \\ useCopilotChatSuggestions](https://docs.copilotkit.ai/reference/hooks/useCopilotChatSuggestions) [Next\\ \\ useCoAgentStateRender](https://docs.copilotkit.ai/reference/hooks/useCoAgentStateRender) ### On this page [Usage](https://docs.copilotkit.ai/reference/hooks/useCoAgent#usage) [Simple Usage](https://docs.copilotkit.ai/reference/hooks/useCoAgent#simple-usage) [Parameters](https://docs.copilotkit.ai/reference/hooks/useCoAgent#parameters) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/reference/hooks/useCoAgent.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## CopilotKit Component Guide CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageExample # CopilotKit The CopilotKit provider component, wrapping your application. This component will typically wrap your entire application (or a sub-tree of your application where you want to have a copilot). It provides the copilot context to all other components and hooks. ## [Example](https://docs.copilotkit.ai/reference/components/CopilotKit\#example) You can find more information about self-hosting CopilotKit [here](https://docs.copilotkit.ai/guides/self-hosting). ``` import { CopilotKit } from "@copilotkit/react-core"; // ... your app ... ``` ## [Properties](https://docs.copilotkit.ai/reference/components/CopilotKit\#properties) publicApiKeystring Your Copilot Cloud API key. Don't have it yet? Go to [https://cloud.copilotkit.ai](https://cloud.copilotkit.ai/) and get one for free. guardrails\_c{ validTopics?: string\[\]; invalidTopics?: string\[\]; } Restrict input to specific topics using guardrails. @remarks This feature is only available when using CopilotKit's hosted cloud service. To use this feature, sign up at [https://cloud.copilotkit.ai](https://cloud.copilotkit.ai/) to get your publicApiKey. The feature allows restricting chat conversations to specific topics. runtimeUrlstring The endpoint for the Copilot Runtime instance. [Click here for more information](https://docs.copilotkit.ai/concepts/copilot-runtime). transcribeAudioUrlstring The endpoint for the Copilot transcribe audio service. textToSpeechUrlstring The endpoint for the Copilot text to speech service. headersRecord Additional headers to be sent with the request. For example: ``` { "Authorization": "Bearer X" } ``` childrenReactNoderequired The children to be rendered within the CopilotKit. propertiesRecord Custom properties to be sent with the request For example: ``` { 'user_id': 'users_id', } ``` credentialsRequestCredentials Indicates whether the user agent should send or receive cookies from the other domain in the case of cross-origin requests. showDevConsoleboolean \| 'auto' Whether to show the dev console. If set to "auto", the dev console will be show on localhost only. agentstring The name of the agent to use. forwardedParametersPick The forwarded parameters to use for the task. authConfig\_c{ SignInComponent: React.ComponentType<{ onSignInComplete: (authState: AuthState) => void; }>; } The auth config to use for the CopilotKit. @remarks This feature is only available when using CopilotKit's hosted cloud service. To use this feature, sign up at [https://cloud.copilotkit.ai](https://cloud.copilotkit.ai/) to get your publicApiKey. The feature allows restricting chat conversations to specific topics. threadIdstring The thread id to use for the CopilotKit. mcpEndpointsArray<{ endpoint: string; apiKey?: string }> Config for connecting to Model Context Protocol (MCP) servers. Enables CopilotKit runtime to access tools on external MCP servers. This config merges into the `properties` object with each request as `mcpEndpoints`. It offers a typed method to set up MCP endpoints for requests. Each array item should have: - `endpoint`: MCP server URL (mandatory). - `apiKey`: Optional API key for server authentication. Note: A `createMCPClient` function is still needed during runtime initialization to manage these endpoints. [Previous\\ \\ CopilotTextarea](https://docs.copilotkit.ai/reference/components/CopilotTextarea) [Next\\ \\ useCopilotReadable](https://docs.copilotkit.ai/reference/hooks/useCopilotReadable) ### On this page [Example](https://docs.copilotkit.ai/reference/components/CopilotKit#example) [Properties](https://docs.copilotkit.ai/reference/components/CopilotKit#properties) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/reference/components/CopilotKit.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## Frontend Actions Guide CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageWhat is this? # Frontend Actions Create frontend actions and use them within your agent. This video shows the [coagents starter](https://github.com/CopilotKit/CopilotKit/tree/main/examples/coagents-starter) repo with the [implementation](https://docs.copilotkit.ai/coagents/frontend-actions#implementation) section applied to it! ## [What is this?](https://docs.copilotkit.ai/coagents/frontend-actions\#what-is-this) Frontend actions are powerful tools that allow your AI agents to directly interact with and update your application's user interface. Think of them as bridges that connect your agent's decision-making capabilities with your frontend's interactive elements. ## [When should I use this?](https://docs.copilotkit.ai/coagents/frontend-actions\#when-should-i-use-this) Frontend actions are essential when you want to create truly interactive AI applications where your agent needs to: - Dynamically update UI elements - Trigger frontend animations or transitions - Show alerts or notifications - Modify application state - Handle user interactions programmatically Without frontend actions, agents are limited to just processing and returning data. By implementing frontend actions, you can create rich, interactive experiences where your agent actively drives the user interface. ## [Implementation](https://docs.copilotkit.ai/coagents/frontend-actions\#implementation) ### [Setup CopilotKit](https://docs.copilotkit.ai/coagents/frontend-actions\#setup-copilotkit) To use frontend actions, you'll need to setup CopilotKit first. For the sake of brevity, we won't cover it here. Check out our [getting started guide](https://docs.copilotkit.ai/coagents/quickstart/langgraph) and come back here when you're setup! ### [Create a frontend action](https://docs.copilotkit.ai/coagents/frontend-actions\#create-a-frontend-action) First, you'll need to create a frontend action using the [useCopilotAction](https://docs.copilotkit.ai/reference/hooks/useCopilotAction) hook. Here's a simple one to get you started that says hello to the user. page.tsx ``` import { useCopilotAction } from "@copilotkit/react-core" export function Page() { // ... useCopilotAction({ name: "sayHello", description: "Say hello to the user", available: "remote", // optional, makes it so the action is *only* available to the agent parameters: [\ {\ name: "name",\ type: "string",\ description: "The name of the user to say hello to",\ required: true,\ },\ ], handler: async ({ name }) => { alert(`Hello, ${name}!`); }, }); // ... } ``` ### [Modify your agent](https://docs.copilotkit.ai/coagents/frontend-actions\#modify-your-agent) Now, we'll need to modify the agent to access these frontend actions. In your terminal, navigate to your agent's folder and continue from there! ### [Install the CopilotKit SDK](https://docs.copilotkit.ai/coagents/frontend-actions\#install-the-copilotkit-sdk) Any LangGraph agent can be used with CopilotKit. However, creating deep agentic experiences with CopilotKit requires our LangGraph SDK. PythonTypeScript Poetrypipconda ``` poetry add copilotkit # including support for crewai poetry add copilotkit[crewai] ``` ### [Inheriting from CopilotKitState](https://docs.copilotkit.ai/coagents/frontend-actions\#inheriting-from-copilotkitstate) To access the frontend actions provided by CopilotKit, you can inherit from CopilotKitState in your agent's state definition: PythonTypeScript agent-py/sample\_agent/agent.py ``` from copilotkit import CopilotKitState class YourAgentState(CopilotKitState): your_additional_properties: str ``` By doing this, your agent's state will include the `copilotkit` property, which contains the frontend actions that can be accessed and invoked. ### [Accessing Frontend Actions](https://docs.copilotkit.ai/coagents/frontend-actions\#accessing-frontend-actions) Once your agent's state includes the `copilotkit` property, you can access the frontend actions and utilize them within your agent's logic. Here's how you can call a frontend action from your agent: PythonTypeScript agent-py/sample\_agent/agent.py ``` async def agent_node(state: YourAgentState, config: RunnableConfig): # Access the actions from the copilotkit property actions = state.get("copilotkit", {}).get("actions", []) model = ChatOpenAI(model="gpt-4o").bind_tools(actions) # ... ``` These actions are automatically populated by CopilotKit and are compatible with LangChain's tool call definitions, making it straightforward to integrate them into your agent's workflow. ### [Give it a try!](https://docs.copilotkit.ai/coagents/frontend-actions\#give-it-a-try) You've now given your agent the ability to directly call any CopilotActions you've defined. These actions will be available as tools to the agent where they can be used as needed. [Previous\\ \\ Predictive state updates](https://docs.copilotkit.ai/coagents/shared-state/predictive-state-updates) [Next\\ \\ Multi-Agent Flows](https://docs.copilotkit.ai/coagents/multi-agent-flows) ### On this page [What is this?](https://docs.copilotkit.ai/coagents/frontend-actions#what-is-this) [When should I use this?](https://docs.copilotkit.ai/coagents/frontend-actions#when-should-i-use-this) [Implementation](https://docs.copilotkit.ai/coagents/frontend-actions#implementation) [Setup CopilotKit](https://docs.copilotkit.ai/coagents/frontend-actions#setup-copilotkit) [Create a frontend action](https://docs.copilotkit.ai/coagents/frontend-actions#create-a-frontend-action) [Modify your agent](https://docs.copilotkit.ai/coagents/frontend-actions#modify-your-agent) [Install the CopilotKit SDK](https://docs.copilotkit.ai/coagents/frontend-actions#install-the-copilotkit-sdk) [Inheriting from CopilotKitState](https://docs.copilotkit.ai/coagents/frontend-actions#inheriting-from-copilotkitstate) [Accessing Frontend Actions](https://docs.copilotkit.ai/coagents/frontend-actions#accessing-frontend-actions) [Give it a try!](https://docs.copilotkit.ai/coagents/frontend-actions#give-it-a-try) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/coagents/frontend-actions.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## Generative UI Overview CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageWhat is Generative UI? # Generative UI Render your agent's behavior with custom UI components. ![Demo of Generative UI showing a meeting scheduling agent](https://docs.copilotkit.aihttps://cdn.copilotkit.ai/docs/copilotkit/images/coagents/AgenticGenerativeUI.gif) This example shows our [Research Canvas](https://docs.copilotkit.ai/coagents/videos/research-canvas) making use of Generative UI! ## [What is Generative UI?](https://docs.copilotkit.ai/coagents/generative-ui\#what-is-generative-ui) Generative UI lets you render your agent's state, progress, outputs, and tool calls with custom UI components in real-time. It bridges the gap between AI agents and user interfaces. As your agent processes information and makes decisions, you can render custom UI components that: - Show loading states and progress indicators - Display structured data in tables, cards, or charts - Create interactive elements for user input - Animate transitions between different states ## [How can I use this?](https://docs.copilotkit.ai/coagents/generative-ui\#how-can-i-use-this) There are two main variants of Generative UI. [Agentic\\ \\ Render your agent's state, progress, and outputs with custom UI components.](https://docs.copilotkit.ai/coagents/generative-ui/agentic) [Tool-based\\ \\ Render your agent's tool calls with custom UI components.](https://docs.copilotkit.ai/coagents/generative-ui/tool-based) [Previous\\ \\ Chat with an Agent](https://docs.copilotkit.ai/coagents/agentic-chat-ui) [Next\\ \\ Agentic Generative UI](https://docs.copilotkit.ai/coagents/generative-ui/agentic) ### On this page [What is Generative UI?](https://docs.copilotkit.ai/coagents/generative-ui#what-is-generative-ui) [How can I use this?](https://docs.copilotkit.ai/coagents/generative-ui#how-can-i-use-this) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/coagents/generative-ui/index.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## CopilotKit Quickstart Guide CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageInstall CopilotKit # Quickstart Get started with CopilotKit in under 5 minutes. Copilot Cloud (Recommended) Use our hosted backend endpoint to get started quickly. Self-hosting Learn to host CopilotKit's runtime yourself with your own backend. ## [Install CopilotKit](https://docs.copilotkit.ai/quickstart?component=CopilotChat\#install-copilotkit) First, install the latest packages for CopilotKit. npmpnpmyarnbun ``` npm install @copilotkit/react-ui @copilotkit/react-core ``` ## [Get a Copilot Cloud Public API Key](https://docs.copilotkit.ai/quickstart?component=CopilotChat\#get-a-copilot-cloud-public-api-key) Navigate to [Copilot Cloud](https://cloud.copilotkit.ai/) and follow the instructions to get a public API key - it's free! ## [Setup the CopilotKit Provider](https://docs.copilotkit.ai/quickstart?component=CopilotChat\#setup-the-copilotkit-provider) The [``](https://docs.copilotkit.ai/reference/components/CopilotKit) component must wrap the Copilot-aware parts of your application. For most use-cases, it's appropriate to wrap the CopilotKit provider around the entire app, e.g. in your layout.tsx. layout.tsx ``` import "./globals.css"; import { ReactNode } from "react"; import { CopilotKit } from "@copilotkit/react-core"; export default function RootLayout({ children }: { children: ReactNode }) { return ( {/* Use the public api key you got from Copilot Cloud */} {children} ); } ``` ## [Choose a Copilot UI](https://docs.copilotkit.ai/quickstart?component=CopilotChat\#choose-a-copilot-ui) You are almost there! Now it's time to setup your Copilot UI. First, import the default styles in your root component (typically `layout.tsx`) : ``` import "@copilotkit/react-ui/styles.css"; ``` Copilot UI ships with a number of built-in UI patterns, choose whichever one you like. CopilotPopupCopilotSidebarCopilotChatHeadless UI `CopilotChat` is a flexible chat interface component that **can be placed anywhere in your app** and can be resized as you desire. ![Popup Example](https://docs.copilotkit.aihttps://cdn.copilotkit.ai/docs/copilotkit/images/copilotchat-example.gif) ``` import { CopilotChat } from "@copilotkit/react-ui"; export function YourComponent() { return ( ); } ``` * * * ## [Next Steps](https://docs.copilotkit.ai/quickstart?component=CopilotChat\#next-steps) 🎉 Congrats! You've successfully integrated a fully functional chatbot in your application! Give it a try now and see it in action. Want to take it further? Learn more about what CopilotKit has to offer! [**Connecting Your Data** \\ Learn how to connect CopilotKit to your data, application state and user state.](https://docs.copilotkit.ai/guides/connect-your-data) [**Generative UI** \\ Learn how to render custom UI components directly in the CopilotKit chat window.](https://docs.copilotkit.ai/guides/generative-ui) [**Frontend Actions** \\ Learn how to allow your copilot to take applications on frontend.](https://docs.copilotkit.ai/guides/frontend-actions) [**CoAgents (LangGraph)** \\ Check out our section about CoAgents, our approach to building agentic copilots and experiences.](https://docs.copilotkit.ai/coagents) [Previous\\ \\ Introduction](https://docs.copilotkit.ai/) [Next\\ \\ Customize UI](https://docs.copilotkit.ai/guides/custom-look-and-feel) ### On this page [Install CopilotKit](https://docs.copilotkit.ai/quickstart?component=CopilotChat#install-copilotkit) [Get a Copilot Cloud Public API Key](https://docs.copilotkit.ai/quickstart?component=CopilotChat#get-a-copilot-cloud-public-api-key) [Setup the CopilotKit Provider](https://docs.copilotkit.ai/quickstart?component=CopilotChat#setup-the-copilotkit-provider) [Choose a Copilot UI](https://docs.copilotkit.ai/quickstart?component=CopilotChat#choose-a-copilot-ui) [Install CopilotKit](https://docs.copilotkit.ai/quickstart?component=CopilotChat#install-copilotkit-1) [Set up a Copilot Runtime Endpoint](https://docs.copilotkit.ai/quickstart?component=CopilotChat#set-up-a-copilot-runtime-endpoint) [Configure the CopilotKit Provider](https://docs.copilotkit.ai/quickstart?component=CopilotChat#configure-the-copilotkit-provider) [Choose a Copilot UI](https://docs.copilotkit.ai/quickstart?component=CopilotChat#choose-a-copilot-ui-1) [Next Steps](https://docs.copilotkit.ai/quickstart?component=CopilotChat#next-steps) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/(root)/quickstart.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## Message History Management CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this page # Saving and restoring messages Learn how to save and restore message history. See [Loading Message History](https://docs.copilotkit.ai/coagents/persistence/loading-message-history) for an automated way to load the chat history. As you're building agentic experiences, you may want to persist the user's chat history across runs. One way to do this is through the use of `localstorage` where chat history is saved in the browser. In this guide we demonstrate how you can store the state into `localstorage` and how it can be inserted into the agent. The following example shows how to save and restore your message history using `localStorage`: ``` import { useCopilotMessagesContext } from "@copilotkit/react-core"; import { ActionExecutionMessage, ResultMessage, TextMessage } from "@copilotkit/runtime-client-gql"; const { messages, setMessages } = useCopilotMessagesContext(); // save to local storage when messages change useEffect(() => { if (messages.length !== 0) { localStorage.setItem("copilotkit-messages", JSON.stringify(messages)); } }, [JSON.stringify(messages)]); // initially load from local storage useEffect(() => { const messages = localStorage.getItem("copilotkit-messages"); if (messages) { const parsedMessages = JSON.parse(messages).map((message: any) => { if (message.type === "TextMessage") { return new TextMessage({ id: message.id, role: message.role, content: message.content, createdAt: message.createdAt, }); } else if (message.type === "ActionExecutionMessage") { return new ActionExecutionMessage({ id: message.id, name: message.name, scope: message.scope, arguments: message.arguments, createdAt: message.createdAt, }); } else if (message.type === "ResultMessage") { return new ResultMessage({ id: message.id, actionExecutionId: message.actionExecutionId, actionName: message.actionName, result: message.result, createdAt: message.createdAt, }); } else { throw new Error(`Unknown message type: ${message.type}`); } }); setMessages(parsedMessages); } }, []); ``` [Previous\\ \\ Self Hosting (Copilot Runtime)](https://docs.copilotkit.ai/guides/self-hosting) [Next\\ \\ Overview](https://docs.copilotkit.ai/tutorials/ai-todo-app/overview) ### On this page No Headings [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/(root)/guides/messages-localstorage.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## Copilot Suggestions Guide CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageSimple Usage # Copilot Suggestions Learn how to auto-generate suggestions in the chat window based on real time application state. useCopilotChatSuggestions is experimental. The interface is not final and can change without notice. [`useCopilotChatSuggestions`](https://docs.copilotkit.ai/reference/hooks/useCopilotChatSuggestions) is a React hook that generates suggestions in the chat window based on real time application state. ![](https://docs.copilotkit.aihttps://cdn.copilotkit.ai/docs/copilotkit/images/use-copilot-chat-suggestions/use-copilot-chat-suggestions.gif) ### [Simple Usage](https://docs.copilotkit.ai/guides/copilot-suggestions\#simple-usage) ``` import { useCopilotChatSuggestions } from "@copilotkit/react-ui"; export function MyComponent() { useCopilotChatSuggestions( { instructions: "Suggest the most relevant next actions.", minSuggestions: 1, maxSuggestions: 2, }, [relevantState], ); } ``` ### [Dependency Management](https://docs.copilotkit.ai/guides/copilot-suggestions\#dependency-management) ``` import { useCopilotChatSuggestions } from "@copilotkit/react-ui"; export function MyComponent() { useCopilotChatSuggestions( { instructions: "Suggest the most relevant next actions.", minSuggestions: 1, maxSuggestions: 2, }, [relevantState], ); } ``` In the example above, the suggestions are generated based on the given instructions. The hook monitors `relevantState`, and updates suggestions accordingly whenever it changes. ### [Specify `"use client"` (Next.js App Router)](https://docs.copilotkit.ai/guides/copilot-suggestions\#specify-use-client-nextjs-app-router) This is only necessary if you are using Next.js with the App Router. YourComponent.tsx ``` "use client" ``` Like other React hooks such as `useState` and `useEffect`, this is a **client-side** hook. If you're using Next.js with the App Router, you'll need to add the `"use client"` directive at the top of any file using this hook. ## [Next Steps](https://docs.copilotkit.ai/guides/copilot-suggestions\#next-steps) - Check out the [useCopilotChatSuggestions reference](https://docs.copilotkit.ai/reference/hooks/useCopilotChatSuggestions) for more details. [Previous\\ \\ Guardrails](https://docs.copilotkit.ai/guides/guardrails) [Next\\ \\ Bring Your Own LLM](https://docs.copilotkit.ai/guides/bring-your-own-llm) ### On this page [Simple Usage](https://docs.copilotkit.ai/guides/copilot-suggestions#simple-usage) [Dependency Management](https://docs.copilotkit.ai/guides/copilot-suggestions#dependency-management) [Next Steps](https://docs.copilotkit.ai/guides/copilot-suggestions#next-steps) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/(root)/guides/copilot-suggestions.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## CopilotTask Overview CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageExample # CopilotTask CopilotTask is used to execute one-off tasks, for example on button click. This class is used to execute one-off tasks, for example on button press. It can use the context available via [useCopilotReadable](https://docs.copilotkit.ai/reference/hooks/useCopilotReadable) and the actions provided by [useCopilotAction](https://docs.copilotkit.ai/reference/hooks/useCopilotAction), or you can provide your own context and actions. ## [Example](https://docs.copilotkit.ai/reference/classes/CopilotTask\#example) In the simplest case, use CopilotTask in the context of your app by giving it instructions on what to do. ``` import { CopilotTask, useCopilotContext } from "@copilotkit/react-core"; export function MyComponent() { const context = useCopilotContext(); const task = new CopilotTask({ instructions: "Set a random message", actions: [\ {\ name: "setMessage",\ description: "Set the message.",\ argumentAnnotations: [\ {\ name: "message",\ type: "string",\ description:\ "A message to display.",\ required: true,\ },\ ],\ }\ ] }); const executeTask = async () => { await task.run(context, action); } return ( <> ) } ``` Have a look at the [Presentation Example App](https://github.com/CopilotKit/CopilotKit/blob/main/CopilotKit/examples/next-openai/src/app/presentation/page.tsx) for a more complete example. ## [Constructor Parameters](https://docs.copilotkit.ai/reference/classes/CopilotTask\#constructor-parameters) instructionsstringrequired The instructions to be given to the assistant. actionsFrontendAction\[\] An array of action definitions that can be called. includeCopilotReadableboolean Whether to include the copilot readable context in the task. includeCopilotActionsboolean Whether to include actions defined via useCopilotAction in the task. forwardedParametersForwardedParametersInput The forwarded parameters to use for the task. runcontext: CopilotContextParams, data?: T Run the task. contextCopilotContextParamsrequired The CopilotContext to use for the task. Use `useCopilotContext` to obtain the current context. dataT The data to use for the task. [Previous\\ \\ GoogleGenerativeAIAdapter](https://docs.copilotkit.ai/reference/classes/llm-adapters/GoogleGenerativeAIAdapter) [Next\\ \\ Remote Endpoints](https://docs.copilotkit.ai/reference/sdk/python/RemoteEndpoints) ### On this page [Example](https://docs.copilotkit.ai/reference/classes/CopilotTask#example) [Constructor Parameters](https://docs.copilotkit.ai/reference/classes/CopilotTask#constructor-parameters) [Edit on GitHub](https://github.com/CopilotKit/CopilotKit/blob/main/docs/content/docs/reference/classes/CopilotTask.mdx) ![](https://static.scarf.sh/a.png?x-pxid=ffc9f65d-0186-4575-b065-61d62ea9d7d3) ## Copilot Textarea Guide CrewAI CrewAI support is here! Checkout the [Crew](https://docs.copilotkit.ai/crewai-crews) and [Flow](https://docs.copilotkit.ai/crewai-flows) documentation. Search docs `⌘` `K` On this pageInstall @copilotkit/react-textarea # Copilot Textarea Learn how to use the Copilot Textarea for AI-powered autosuggestions. ![](https://docs.copilotkit.aihttps://cdn.copilotkit.ai/docs/copilotkit/images/CopilotTextarea.gif) `` is a React component that acts as a drop-in replacement for the standard `