### Local Development Setup: Frontend Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Sets up the frontend for local development, including installing dependencies and starting the development server. ```bash cd frontend pnpm install pnpm dev ``` -------------------------------- ### Local Development Setup: Backend Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Sets up the backend for local development, including installing dependencies and starting the server with necessary API keys. ```bash cd agent poetry install OPENAI_API_KEY=sk-... TAVILY_API_KEY=tvly-... poetry run langgraph_server ``` -------------------------------- ### Run Frontend Application Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/INDEX.md Installs frontend dependencies and starts the development server. Access the frontend at http://localhost:3000. ```bash cd frontend && pnpm install pnpm dev ``` -------------------------------- ### Backend Setup (.env file) Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Example of setting backend environment variables in a .env file for local development. ```bash OPENAI_API_KEY=sk-proj-xxxxx... TAVILY_API_KEY=tvly-xxxxx... PORT=8000 ``` -------------------------------- ### Frontend Production Setup (.env.production.local) Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Example of setting the frontend backend agent endpoint URL in a .env.production.local file for production environments. ```bash # .env.production.local REMOTE_ACTION_URL=https://api.example.com/copilotkit ``` -------------------------------- ### Frontend Development Setup (.env.local) Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Example of setting the frontend backend agent endpoint URL in a .env.local file for local development. ```bash # .env.local REMOTE_ACTION_URL=http://localhost:8000/copilotkit ``` -------------------------------- ### Instantiate AgentState Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/06-types.md Example of how to instantiate the AgentState with initial values. Ensure all required fields are present, even if set to None. ```python state: AgentState = { "messages": [...], "copilotkit": {...}, "haiku": None, "tavily_response": None, "haiku_args": None, "tavily_responses_content": None, "haiku_verification": None } ``` -------------------------------- ### Backend Modules: HTTP Server Setup Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/01-project-overview.md Sets up the HTTP server for the backend agent using the CopilotKit SDK. ```python langgraph_server.py - HTTP server setup with CopilotKit SDK ``` -------------------------------- ### Run Backend Application Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/INDEX.md Installs backend dependencies and runs the LangGraph server. Requires setting OPENAI_API_KEY and TAVILY_API_KEY environment variables. ```bash cd agent && poetry install OPENAI_API_KEY=sk-... TAVILY_API_KEY=tvly-... poetry run langgraph_server ``` ```bash python langgraph_server.py ``` -------------------------------- ### Install Python Dependencies with Poetry Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Installs Python project dependencies using Poetry. This command should be run from the agent directory. ```bash cd agent poetry install ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/copilotkit/agui-demo/blob/main/frontend/README.md Use these commands to start the local development server for your Next.js project. Open http://localhost:3000 in your browser to view the application. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Example .env.local Configuration Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/05-frontend-api-route.md Set the REMOTE_ACTION_URL environment variable to specify the backend endpoint for local development. ```env REMOTE_ACTION_URL=http://localhost:8000/copilotkit ``` -------------------------------- ### Remote Endpoint Configuration Example Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/05-frontend-api-route.md Example configuration for remote endpoints within CopilotRuntime. It specifies the URL for the backend agent, falling back to a default if the environment variable is not set. ```typescript remoteEndpoints: [ { url: process.env.REMOTE_ACTION_URL || "http://localhost:8000/copilotkit", }, ] ``` -------------------------------- ### Add Workflow Edge from START Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/10-quick-reference.md Alternatively, add an edge from the special 'START' node to your desired entry point. This achieves the same result as `set_entry_point`. ```python workflow.add_edge(START, "start_flow") ``` -------------------------------- ### Haiku Generation Example Output Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/02-backend-agent-api.md Example of generated Japanese and English haiku lines after the search_node has collected relevant content. ```python # After search_node collects "climate change impacts on polar ice..." # haiku_generation_node generates: # Japanese: ["北極の氷", "融けて海は", "色を変える"] # English: ["Polar ice melts soft", "Arctic seas transform their hue", "World shifts on its face"] ``` -------------------------------- ### Backend Export: Workflow Start Node Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/01-project-overview.md The entry point function for the agentic workflow. ```python start_flow() - Workflow start node ``` -------------------------------- ### Run Uvicorn Server Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/03-backend-server.md The main entry point function to start the Uvicorn server. It configures the host, port (defaulting to 8000 or from the PORT environment variable), and enables auto-reloading for development. ```python def main(): """Run the uvicorn server.""" port = int(os.getenv("PORT", "8000")) uvicorn.run( "langgraph_server:app", host="0.0.0.0", port=port, reload=True, ) ``` -------------------------------- ### Configure Workflow Entry Point Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/07-workflow-routing.md Sets the initial node for the workflow and adds an edge from the START signal to this entry point. Ensures the workflow always begins at the specified node. ```python workflow.set_entry_point("start_flow") workflow.add_edge(START, "start_flow") ``` -------------------------------- ### Install Node.js Dependencies with pnpm Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Installs project dependencies using the pnpm package manager. Ensure pnpm is installed globally. ```bash pnpm install ``` -------------------------------- ### Example Haiku Arguments for Rendering Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/02-backend-agent-api.md Shows the expected structure of haiku arguments ('japanese' and 'english' arrays) prepared for rendering in the UI. ```python # Haiku prepared for rendering: # { # "japanese": ["北極の氷", "融けて海は", "色を変える"], # "english": ["Polar ice melts soft", "Arctic seas transform their hue", "World shifts on its face"] # } ``` -------------------------------- ### Root Page Component with CopilotKit Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/04-frontend-components.md This snippet shows the basic setup of the root page component, integrating CopilotKit with a specified runtime URL and agent. The AGUI component is rendered as a child. ```typescript export default function Home() { return ( <> ); } ``` -------------------------------- ### Override Frontend Configuration at Runtime Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Example of overriding the frontend backend agent endpoint URL at runtime using environment variables or hosting platform configuration. ```bash # Environment variable or hosting platform configuration REMOTE_ACTION_URL=https://agent-backend.example.com/copilotkit npm run dev ``` -------------------------------- ### Backend Dockerfile Configuration Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Defines the Docker image for the backend service, including Python version, dependency installation, and server startup command. ```dockerfile FROM python:3.11 WORKDIR /app COPY agent/pyproject.toml poetry.lock ./ RUN pip install poetry && poetry install --no-dev COPY agent/ ./ ENV PORT=8000 EXPOSE 8000 CMD ["poetry", "run", "langgraph_server"] ``` -------------------------------- ### Configure CopilotRuntime with Remote Endpoints Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/09-integration-points.md Configure the CopilotRuntime with a list of remote endpoints for handling requests. This example shows how to set up a local endpoint. ```typescript const runtime = new CopilotRuntime({ remoteEndpoints: [{ url: process.env.REMOTE_ACTION_URL || "http://localhost:8000/copilotkit" }] }); ``` -------------------------------- ### Set Workflow Entry Point Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/10-quick-reference.md Use this method to directly set the starting node for a workflow execution. This ensures every workflow begins at the specified entry point. ```python workflow.set_entry_point("start_flow") ``` -------------------------------- ### OpenAI GPT-4o API Call Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/09-integration-points.md Example of invoking an OpenAI GPT-4o model with tool bindings for specific tasks. ```python model = ChatOpenAI(model="gpt-4o") model_with_tools = model.bind_tools([tool_definition]) response = await model_with_tools.ainvoke([ SystemMessage(content="..."), *state["messages"] ], config) ``` -------------------------------- ### Frontend Dockerfile Configuration Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Defines the Docker image for the frontend service, including Node.js version, dependency installation, and build/start commands. ```dockerfile FROM node:18 WORKDIR /app COPY frontend/package.json pnpm-lock.yaml ./ RUN npm install -g pnpm && pnpm install COPY frontend/ ./ ENV REMOTE_ACTION_URL=http://backend:8000/copilotkit RUN pnpm build EXPOSE 3000 CMD ["pnpm", "start"] ``` -------------------------------- ### Conditional Routing: Continue from Start Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/02-backend-agent-api.md Determines if the agent flow should continue after the start node. Use this to end the flow if the user acknowledges a previous response. ```python def should_continue_from_start(state: AgentState) -> str: # If the last user message contains acknowledgment keywords ("thank", "thanks", "appreciated", "great haiku", "nice haiku", "love the haiku"), returns "end" # Otherwise returns "search_node" pass ``` -------------------------------- ### Start Flow Node Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/07-workflow-routing.md Defines the start_flow node which resets state fields and does not modify messages. ```python async def start_flow(state: AgentState, config: RunnableConfig) -> AgentState: state["haiku_verification"] = None state["tavily_responses_content"] = None state["haiku_args"] = None return state ``` -------------------------------- ### Execute Server Startup Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/03-backend-server.md Standard Python construct to ensure the main function is called only when the script is executed directly. ```python if __name__ == "__main__": main() ``` -------------------------------- ### Initialize Search Topics Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/06-types.md Creates an initial list of search topics with their completed status set to False. This is typically used to set up the initial state for tracking search progress. ```python mapped_topics = list(map(lambda x: { 'topic': x, 'completed': False, }, topics)) state['tavily_response'] = mapped_topics ``` -------------------------------- ### Health Check Route Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/03-backend-server.md A simple GET endpoint to check if the server is running and responsive. ```APIDOC ## Health Check Route ### Description Provides a basic health check endpoint for the server. ### Method GET ### Endpoint / ### Response #### Success Response (200) - `message` (str): A status message indicating the server is running. ### Response Example ```json { "message": "Hello World!!" } ``` ``` -------------------------------- ### Initialize FastAPI Application Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/03-backend-server.md Creates a standard FastAPI application instance for handling HTTP requests. ```python app = FastAPI() ``` -------------------------------- ### Configure Language Model Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Sets up the language model to be used, defaulting to 'gpt-4o'. Options to change the model, add temperature control, or set max tokens are provided. ```python model = ChatOpenAI(model="gpt-4o") ``` ```python # Use different model model = ChatOpenAI(model="gpt-4-turbo") # Or any other OpenAI model ``` ```python # Add temperature control model = ChatOpenAI(model="gpt-4o", temperature=0.7) ``` ```python # Add max tokens model = ChatOpenAI(model="gpt-4o", max_tokens=2000) ``` -------------------------------- ### useCopilotChatSuggestions Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/04-frontend-components.md Configures suggested prompts for users, allowing customization of instructions and the number of suggestions displayed. ```APIDOC ## useCopilotChatSuggestions ### Description Configures suggested prompts for users, allowing customization of instructions and the number of suggestions displayed. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **instructions** (string) - Required - Prompt template for generating suggestions - **minSuggestions** (number) - Optional - Minimum suggestions to display (default: 1) - **maxSuggestions** (number) - Optional - Maximum suggestions to display (default: 6) ### Request Example ```typescript useCopilotChatSuggestions({ instructions: suggestionPrompt, minSuggestions: 1, maxSuggestions: 6, }) ``` ### Response #### Success Response (200) N/A (This is a configuration hook) #### Response Example N/A ``` -------------------------------- ### Frontend Modules: Entry Point and CopilotKit Wrapper Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/01-project-overview.md The entry point for the Next.js application, wrapping the main AGUI component with CopilotKit. ```typescript page.tsx - Entry point that wraps AGUI with CopilotKit ``` -------------------------------- ### Initialize Verification State Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/06-types.md Sets up the initial state for verification, including the first step and any provided Japanese and English haiku content. This is called when verification begins. ```python state['haiku_verification'] = { "steps": [ {"task": "Verifying the Haiku with the 🥷 Haiku Master", "completed": False}, ], "japanese": tool_call_args.get("japanese", []), "english": tool_call_args.get("english", []) } ``` -------------------------------- ### Configure Chat Suggestions with useCopilotChatSuggestions Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/04-frontend-components.md Use this hook to set up suggested prompts for users. Configure the instructions, minimum, and maximum number of suggestions to display. ```typescript useCopilotChatSuggestions({ instructions: suggestionPrompt, minSuggestions: 1, maxSuggestions: 6, }) ``` -------------------------------- ### Set Optional Backend and Frontend Environment Variables Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/README.md Configure optional environment variables for the backend port and the frontend's remote action URL. The REMOTE_ACTION_URL should point to your backend service. ```bash # Backend export PORT="8000" # Frontend export REMOTE_ACTION_URL="http://localhost:8000/copilotkit" ``` -------------------------------- ### Start Flow State Reset Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/07-workflow-routing.md Resets specific fields in the state to None, while keeping others unchanged. This is typically done at the beginning of a workflow or a specific stage. ```python { "messages": [...], # Unchanged "haiku": ..., # Unchanged "tavily_response": None, # Reset "haiku_args": None, # Reset "tavily_responses_content": None, # Reset "haiku_verification": None # Reset } ``` -------------------------------- ### Initialize CopilotKit SDK with LangGraph Agent Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/03-backend-server.md Initializes the CopilotKit SDK, registering a LangGraph agent for the AGUI protocol. Ensure the agent name matches frontend references and the graph parameter is the compiled LangGraph workflow. ```python sdk = CopilotKitSDK( agents=[ LangGraphAgent( name="AG_UI", description="An example for showcasing the AGUI protocol using LangGraph.", graph=ag_ui_graph ), ] ) ``` -------------------------------- ### AG-UI Conditional Routing: should_continue_from_start() Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/10-quick-reference.md Determines whether to end the conversation or proceed to a search node based on the content of the last message. Use when starting a new interaction. ```plaintext If last message contains: "thank", "thanks", "appreciated", "great haiku", "nice haiku", "love the haiku" → Return "end" (to END) Else → Return "search_node" ``` -------------------------------- ### Define Health Check Route Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/03-backend-server.md Implements a simple GET route at the root path ('/') for basic server health checks. Returns a JSON object with a status message. ```python @app.get("/") async def root(): return {"message": "Hello World!!"} ``` -------------------------------- ### Instantiate LangGraphAgent Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/06-types.md This code demonstrates how to wrap a LangGraph workflow as a CopilotKit agent. The agent is initialized with a name, description, and the compiled LangGraph workflow. ```python LangGraphAgent( name="AG_UI", description="An example for showcasing the AGUI protocol using LangGraph.", graph=ag_ui_graph ) ``` -------------------------------- ### CopilotKit SDK Initialization Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/03-backend-server.md Initializes the CopilotKit SDK with a LangGraphAgent, defining the agent's name, description, and the associated LangGraph workflow. ```APIDOC ## CopilotKitSDK Initialization ### Description Initializes the CopilotKit SDK with a list of agents. In this case, a single `LangGraphAgent` named "AG_UI" is configured. ### Parameters - `agents` (List[LangGraphAgent]): A list of agent definitions to be managed by the SDK. ### LangGraphAgent Parameters - `name` (str): The unique identifier for the agent, used for frontend referencing. - `description` (str): A human-readable description of the agent's purpose. - `graph` (StateGraph): The compiled LangGraph workflow that the agent will execute. ### Request Example ```python sdk = CopilotKitSDK( agents=[ LangGraphAgent( name="AG_UI", description="An example for showcasing the AGUI protocol using LangGraph.", graph=ag_ui_graph ), ] ) ``` ``` -------------------------------- ### Add Conditional Edges from Start Node Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/07-workflow-routing.md Defines routing logic from the 'start_flow' node. It checks for user acknowledgments in the last message to decide whether to end the conversation or proceed to a search node. ```python workflow.add_conditional_edges( "start_flow", should_continue_from_start, { "search_node": "search_node", "end": END } ) ``` ```python def should_continue_from_start(state: AgentState) -> str: if state.get("messages") and len(state["messages"]) > 0: last_msg = state["messages"][-1] content = getattr(last_msg, "content", "") or "" if any(word in content.lower() for word in ["thank", "thanks", "appreciated", "great haiku", "nice haiku", "love the haiku"]): return "end" return "search_node" ``` -------------------------------- ### User Input to Topics Transformation Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/10-quick-reference.md Demonstrates the transformation of user input into a list of topics using a search node. ```text User: "Create a haiku about climate change" ↓ (search_node) Topics: ["climate change", "global warming", "carbon emissions"] ``` -------------------------------- ### Modify Tavily Search Behavior Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Provides examples of how to modify Tavily search behavior by changing search depth to 'advanced', using a different topic type like 'research', or adjusting the time range to 'month'. ```python # Use advanced search tavily_response_data = tavily_client.search( topic_to_search, 'advanced', # Slower but more comprehensive 'news', 'week', 10, # Request more results 5 # Return more results ) ``` ```python # Use different topic type tavily_response_data = tavily_client.search( topic_to_search, 'basic', 'research', # Use academic/research articles instead of news 'week', 7, 3 ) ``` ```python # Change time range tavily_response_data = tavily_client.search( topic_to_search, 'basic', 'news', 'month', # Last 30 days instead of 7 days 7, 3 ) ``` -------------------------------- ### CopilotKit Component Runtime Configuration - JSX Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/09-integration-points.md Demonstrates runtime configuration for CopilotKit components using props. This includes selecting the backend agent, specifying the frontend API route, and enabling the development console. ```jsx CopilotKit component props ↓ agent="AG_UI" → Selects backend agent ↓ runtimeUrl="api/copilotkit" → Frontend API route ↓ showDevConsole={true} → Enable debugging ``` -------------------------------- ### CopilotChat Suggestions Prompt Configuration Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Define the prompt used to generate chat suggestions. Customize the instructions and the default set of topics. ```typescript export const suggestionPrompt = ` Provide a list of topics for the user to generate a haiku. Make sure to include Politics, Movies, Literature, Science, Technology, and AI as default set for first time. ` ``` ```typescript export const suggestionPrompt = ` Provide haiku topics. Suggest: Physics, Chemistry, Biology, Medicine, History ` ``` -------------------------------- ### Run LangGraph Server with Poetry Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Executes the LangGraph server using a script defined in Poetry's configuration. ```bash poetry run langgraph_server ``` -------------------------------- ### Frontend Modules: Static Prompt Configurations Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/01-project-overview.md Contains static prompt strings used within the frontend application. ```typescript prompts.ts - Static prompt configurations ``` -------------------------------- ### VerificationState Backend Structure Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/06-types.md Defines the backend structure for managing verification steps and associated haiku content. ```python # Backend structure: { "steps": [ { "task": str, "completed": bool } ], "japanese": List[str], "english": List[str] } ``` -------------------------------- ### Create RunnableConfig Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/06-types.md Instantiate RunnableConfig to set execution parameters like recursion depth for LangGraph nodes. ```python config = RunnableConfig(recursion_limit=25) ``` -------------------------------- ### start_flow Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/02-backend-agent-api.md The entry point for the agentic workflow, responsible for routing based on user message intent. ```APIDOC ## Function: start_flow ### Description Entry point for the agentic workflow. Routes based on user message intent and resets specific state fields for a clean start. ### Method async def start_flow(state: AgentState, config: RunnableConfig) -> AgentState ### Parameters - **state** (AgentState) - Current workflow state with messages - **config** (RunnableConfig) - Langchain runnable configuration ### Returns - **AgentState** - Updated state with cleared verification/search fields ### Behavior - Resets `haiku_verification`, `tavily_responses_content`, and `haiku_args` to `None`. - Does not modify messages; routing is handled by conditional edges. - Used as the entry point for every workflow invocation. ``` -------------------------------- ### Backend Environment Variable Loading - Python Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/09-integration-points.md Illustrates how environment variables from .env files are loaded using `load_dotenv()` and accessed via `os.getenv()` in Python, enabling automatic configuration for clients like OpenAI and Tavily. ```text .env files (backend) ↓ load_dotenv() in agent.py ↓ os.getenv() calls in code ↓ Passed to OpenAI, Tavily clients automatically ``` -------------------------------- ### Set Backend API Keys Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/README.md Set the OPENAI_API_KEY and TAVILY_API_KEY environment variables for backend functionality. These are required for the agent to operate. ```bash # Backend export OPENAI_API_KEY="sk-..." export TAVILY_API_KEY="tvly-..." ``` -------------------------------- ### Frontend Environment Variable Injection - Next.js Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/09-integration-points.md Shows how .env.local files are processed in Next.js, with variables available via `process.env` and injected at build or runtime. CopilotRuntime uses `REMOTE_ACTION_URL`. ```text .env.local (frontend) ↓ process.env in Next.js ↓ Injected at build/runtime ↓ CopilotRuntime uses REMOTE_ACTION_URL ``` -------------------------------- ### Suggestion Prompt Configuration Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/04-frontend-components.md Defines a static prompt string used to instruct the LLM for generating chat suggestions. It ensures a default set of topics are provided initially. ```typescript export const suggestionPrompt = ` Provide a list of topics for the user to generate a haiku. Make sure to include Politics, Movies, Literature, Science, Technology, and AI as default set for first time. ` ``` -------------------------------- ### useCopilotAction Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/04-frontend-components.md Registers actions, specifically the `render_haiku` action, which displays final haikus in a formatted card view. ```APIDOC ## useCopilotAction ### Description Registers actions, specifically the `render_haiku` action, which displays final haikus in a formatted card view. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Parameters - **name** (string) - Required - Action identifier (matches backend tool name) - **description** (string) - Required - Tooltip/help text - **followUp** (boolean) - Optional - If false, no follow-up chat suggested (default: true) - **render** (function) - Required - Render function for action display ### Render Function Props: - **status** (string) - Action execution status - **args** (object) - Arguments from `render_haiku` tool call **Arguments Structure:** ```typescript args: { japanese: string[]; english: string[]; } ``` **Behavior:** 1. Extracts `args.japanese` and `args.english` 2. Stores in `haikus` state if not already present (deduplication via JSON comparison) 3. Renders haiku in card format with: - Japanese line (large, dark blue text) - Matching English line (italic, rose-red text) - Three rows for three haiku lines **Example Rendering:** ``` 北極の氷 Polar ice melts soft 融けて海は Arctic seas transform their hue 色を変える World shifts on its face ``` **Card Styling:** - White background with shadow - Rounded corners (rounded-xl) - Padding of 1.5rem (p-6) - Margin top/bottom 1rem (my-4) ### Request Example ```typescript useCopilotAction({ name: "render_haiku", description: "Render the Confirmed haikus", followUp: false, render: ({ status, args }) => ReactNode }) ``` ### Response #### Success Response (200) N/A (This is an action registration hook) #### Response Example N/A ``` -------------------------------- ### Environment Variables for Production Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Specifies the environment variables required for backend and frontend services during production deployment. ```bash # Backend OPENAI_API_KEY=sk-prod-... TAVILY_API_KEY=tvly-prod-... PORT=8000 # Frontend REMOTE_ACTION_URL=https://api.production.com/copilotkit ``` -------------------------------- ### Environment Variables for Development Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Specifies the environment variables required for backend and frontend services during development. ```bash # Backend OPENAI_API_KEY=sk-dev-... TAVILY_API_KEY=tvly-dev-... PORT=8000 # Frontend REMOTE_ACTION_URL=http://localhost:8000/copilotkit ``` -------------------------------- ### Add Conditional Edges from Search Node Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/07-workflow-routing.md Sets up routing from the 'search_node'. It proceeds to 'haiku_generation_node' only if web search results are available in the agent's state; otherwise, it routes to the 'end' node. ```python workflow.add_conditional_edges( "search_node", should_continue_from_search, { "haiku_generation_node": "haiku_generation_node", "end": END } ) ``` ```python def should_continue_from_search(state: AgentState) -> str: if state.get("tavily_responses_content"): return "haiku_generation_node" return "end" ``` -------------------------------- ### Frontend Export: Static Suggestion Prompt Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/01-project-overview.md A static string used for providing suggestions within the UI. ```typescript suggestionPrompt export - Static prompt string ``` -------------------------------- ### Backend Key Imports Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/10-quick-reference.md Essential imports for the CopilotKit backend, including state management, LangGraph integration, and API clients. ```python from copilotkit import CopilotKitState from copilotkit.langgraph import copilotkit_emit_state, copilotkit_exit from langgraph.graph import StateGraph from langchain_openai import ChatOpenAI from tavily import TavilyClient ``` -------------------------------- ### Frontend Key Imports Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/10-quick-reference.md Key imports for the CopilotKit frontend using React, including core components and runtime utilities. ```typescript import { CopilotKit, useCoAgent, useCopilotAction, useCopilotChat } from "@copilotkit/react-core" import { CopilotChat } from "@copilotkit/react-ui" import { NextRequest } from "next/server" import { CopilotRuntime } from "@copilotkit/runtime" ``` -------------------------------- ### Content to Haiku Transformation Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/10-quick-reference.md Illustrates the transformation of retrieved content into a haiku, including both Japanese and English versions, using a language model like GPT-4o. ```text Content: "Climate impacts..." ↓ (GPT-4o) Haiku: { japanese: ["北極の氷", "融けて海は", "色を変える"], english: ["Polar ice melts soft", "Arctic seas transform their hue", "World shifts on its face"] } ``` -------------------------------- ### Backend Port Configuration (Python) Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Configures the server port for the FastAPI/Uvicorn backend. Defaults to '8000' if not specified. ```python port = int(os.getenv("PORT", "8000")) ``` -------------------------------- ### Tavily API Key Usage (Python) Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Automatically uses the TAVILY_API_KEY environment variable for TavilyClient instantiation. ```python tavily_client = TavilyClient() # Uses TAVILY_API_KEY automatically ``` -------------------------------- ### Perform Tavily Search with Basic Configuration Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Executes a Tavily search query with specified parameters for search depth, topic, time range, and result counts. ```python tavily_response_data = tavily_client.search( topic_to_search, # Query string 'basic', # Search depth 'news', # Topic category 'week', # Time range (internally maps to days=7) 7, # Max results 3 # Result count ) ``` -------------------------------- ### should_continue_from_start Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/02-backend-agent-api.md Conditional routing function after `start_flow`. Determines if the agent should continue or end the flow based on user acknowledgment. ```APIDOC ## should_continue_from_start ### Description Conditional routing function after `start_flow`. Allows the agent to end the flow if the user acknowledges a previous response. ### Function Signature ```python def should_continue_from_start(state: AgentState) -> str ``` ### Returns - `"search_node"` | `"end"` ### Logic - If the last user message contains acknowledgment keywords (`"thank"`, `"thanks"`, `"appreciated"`, `"great haiku"`, `"nice haiku"`, `"love the haiku"`), returns `"end"`. - Otherwise returns `"search_node"`. ``` -------------------------------- ### Create Synthetic Tool Call Message for Rendering Haiku Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/09-integration-points.md Constructs a synthetic 'assistant' message with a 'tool_calls' object, specifically for the 'render_haiku' tool, including the arguments containing the haiku verses. ```json { "role": "assistant", "tool_calls": [{ "name": "render_haiku", "arguments": "{\"japanese\": [...], \"english\": [...]}" }] } ``` -------------------------------- ### start_flow Function Signature Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/02-backend-agent-api.md The entry point for the agentic workflow. It resets specific state fields and is invoked by LangGraph internally. ```python async def start_flow(state: AgentState, config: RunnableConfig) -> AgentState ``` -------------------------------- ### Frontend Backend Agent Endpoint Configuration (TypeScript) Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Configures the backend agent endpoint URL for the frontend. Defaults to 'http://localhost:8000/copilotkit' if not specified. ```typescript url: process.env.REMOTE_ACTION_URL || "http://localhost:8000/copilotkit" ``` -------------------------------- ### AGUI Main Component Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/04-frontend-components.md The primary React component for the haiku generation UI, integrating CopilotKit for chat, agent state, and display of generated content. ```typescript export const AGUI = () => ReactNode ``` -------------------------------- ### CopilotChat Suggestions Hook Configuration Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Configure the `useCopilotChatSuggestions` hook to control the number of suggestions displayed. Adjust `minSuggestions` and `maxSuggestions` parameters. ```typescript useCopilotChatSuggestions({ instructions: suggestionPrompt, minSuggestions: 1, maxSuggestions: 6, }) ``` ```typescript useCopilotChatSuggestions({ instructions: suggestionPrompt, minSuggestions: 3, maxSuggestions: 8, }) ``` -------------------------------- ### Update and Emit Verification Step Completion Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/06-types.md Marks a verification step as completed after a delay and emits the updated state to the copilot. This is used to show progress in real-time. ```python for i, step in enumerate(verification_steps): await asyncio.sleep(2.5) verification_steps[i]["completed"] = True state['haiku_verification']["steps"] = verification_steps await copilotkit_emit_state(config, state) ``` -------------------------------- ### Register LangGraphAgent with AGUI Protocol Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/03-backend-server.md Register your LangGraph agent with a name, description, and its associated graph. This makes the agent accessible through the AGUI protocol. ```python LangGraphAgent( name="AG_UI", description="An example for showcasing the AGUI protocol using LangGraph.", graph=ag_ui_graph # From agent.py lines 374-430 ) ``` -------------------------------- ### Override Uvicorn Port via Environment Variable Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/08-configuration.md Demonstrates how to set the PORT environment variable to change the server's listening port when running the Uvicorn server. ```bash PORT=9000 python langgraph_server.py ``` -------------------------------- ### Frontend Modules: Root HTML Structure Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/01-project-overview.md Provides the root HTML structure and metadata for the Next.js application. ```typescript layout.tsx - Root HTML structure and metadata ``` -------------------------------- ### Create Haiku Verification State Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/09-integration-points.md This Python code snippet shows how to create and populate the 'haiku_verification' state, including the steps for verification and the generated haiku verses. ```python state['haiku_verification'] = { "steps": [{"task": "Verifying with 🥷 Haiku Master", "completed": false}], "japanese": [...], "english": [...] } ``` -------------------------------- ### AGUI Component Source: https://github.com/copilotkit/agui-demo/blob/main/_autodocs/04-frontend-components.md The main interactive React component that displays the haiku generation UI and manages all CopilotKit integration. It provides a chat interface, agent state tracking, haiku display with translation, and progress indicators. ```APIDOC ## Component: AGUI ### Description The main functional component that provides: - Chat interface via CopilotChat - Agent state tracking and rendering - Haiku display with Japanese/English translation - Progress indicators for search and verification ### Source `src/app/Components/AGUI.tsx`, lines 17-215 ```