### Start the Frontend and Configure Environment Source: https://github.com/copilotkit/open-research-ana/blob/main/README.md Navigate to the frontend directory, install dependencies, create a .env file with API keys, and start the development server. ```bash cd frontend pnpm install # Create and populate .env cat << EOF > .env OPENAI_API_KEY=your_openai_key LANGSMITH_API_KEY=your_langsmith_key NEXT_PUBLIC_COPILOT_CLOUD_API_KEY=your_copilot_cloud_key EOF # Start the app pnpm run dev ``` -------------------------------- ### Run Frontend Locally Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/quick-reference.md Navigate to the frontend directory, set deployment variables, install dependencies, and start the development server. ```bash cd frontend export DEPLOYMENT=local export LOCAL_DEPLOYMENT_URL=http://localhost:8123 pnpm install pnpm run dev # Open http://localhost:3000 ``` -------------------------------- ### Start Frontend Locally Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md Navigate to the frontend directory and set the deployment environment variables before starting the development server. ```bash cd frontend export DEPLOYMENT=local export LOCAL_DEPLOYMENT_URL=http://localhost:8123 pnpm run dev ``` -------------------------------- ### Start the Agent and Configure Environment Source: https://github.com/copilotkit/open-research-ana/blob/main/README.md Navigate to the agent directory, create a .env file with necessary API keys, and start the agent using the Langgraph CLI. ```bash cd agent # Create and populate .env cat << EOF > .env OPENAI_API_KEY=your_key TAVILY_API_KEY=your_key LANGSMITH_API_KEY=your_key EOF ## Start the agent langgraph up # Note the API URL from the output (e.g., http://localhost:8123) ``` -------------------------------- ### Troubleshoot Agent Startup Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md Steps to troubleshoot issues when the LangGraph agent fails to start, including checking API keys, Python version, and LangGraph CLI installation. ```bash Verify OPENAI_API_KEY, TAVILY_API_KEY, LANGSMITH_API_KEY are set Check Python 3.12 is installed: `python --version` Install LangGraph CLI: `pip install langgraph-cli` Run `langgraph up --debug` for verbose output ``` -------------------------------- ### Start LangGraph Agent Locally Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md Navigate to the agent directory and start the LangGraph agent. Note the URL provided for frontend configuration. ```bash cd agent langgraph up # Note the URL (typically http://localhost:8123) ``` -------------------------------- ### Start Frontend for Remote LangGraph Cloud Deployment Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md Navigate to the frontend directory and run the command to start the development server for a remote LangGraph Cloud deployment. ```bash cd frontend pnpm run remote-lgc-dev ``` -------------------------------- ### Start Frontend Development Server Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/quick-reference.md Run this command to start the frontend development server. Check the browser's F12 console for CopilotKit messages, React warnings, and custom logs. ```bash pnpm run dev ``` -------------------------------- ### Run Backend Locally Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/quick-reference.md Navigate to the agent directory, set necessary API keys, and start the LangGraph service. ```bash cd agent export OPENAI_API_KEY=sk-... export TAVILY_API_KEY=tvly-... export LANGSMITH_API_KEY=ls__... langgraph up # Note: URL (typically http://localhost:8123) ``` -------------------------------- ### DocumentViewer Usage Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-components.md A basic usage example for the DocumentViewer component, specifying the section, zoom level, and edit mode. ```typescript ``` -------------------------------- ### Proposal Structure Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/research-state.md An example of the structure generated by the outline_writer tool. It includes sections, a timestamp, approval status, and remarks. ```json { "sections": { "section1": { "title": "Introduction", "description": "Overview of the research topic", "approved": False }, "section2": { "title": "Methodology", "description": "Research methodology and sources", "approved": False } }, "timestamp": "2024-06-15T10:30:45.123456", "approved": False, "remarks": "" } ``` -------------------------------- ### Sources Structure Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/research-state.md Example of the sources structure populated after search and extract tools. It's a dictionary keyed by URL, containing article details. ```json { "https://example.com/article": { "title": "Article Title", "url": "https://example.com/article", "content": "Summary or snippet", "raw_content": "Full extracted HTML/text", "score": 0.85, "published_date": "2024-06-01" } } ``` -------------------------------- ### Reinstall Backend Dependencies Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/quick-reference.md If the agent won't start, try reinstalling the backend dependencies using pip. ```bash pip install -e . ``` -------------------------------- ### Start Backend in Debug Mode Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/quick-reference.md Use this command to run the backend with detailed logging for prompts, tool calls, and state changes. ```bash langgraph up --debug ``` -------------------------------- ### Setup Backend Agent Environment Variables Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md Create a .env file in the agent directory with required API keys for OpenAI, Tavily, and LangSmith. ```bash cd agent cat << EOF > .env OPENAI_API_KEY=sk-... TAVILY_API_KEY=tvly-... LANGSMITH_API_KEY=ls__... EOF ``` -------------------------------- ### Setup Frontend Local Deployment Environment Variables Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md Create a .env file in the frontend directory for local deployment, specifying the deployment mode, local URL, and API keys. ```bash cd frontend cat << EOF > .env DEPLOYMENT=local LOCAL_DEPLOYMENT_URL=http://localhost:8123 OPENAI_API_KEY=sk-... LANGSMITH_API_KEY=ls__... EOF ``` -------------------------------- ### useResearch Hook Usage Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-components.md Example demonstrating how to use the useResearch hook in a component to start research, display state, and toggle the sources modal. ```typescript import { useResearch } from "@/components/research-context" export default function MyComponent() { const { state, setResearchState, sourcesModalOpen, setSourcesModalOpen, runAgent } = useResearch() return (

{state.title}

) } ``` -------------------------------- ### Sections Structure Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/research-state.md Example of the structure for generated sections after the section_writer tool. Each section includes title, content, footer, index, and ID. ```json [ { "title": "Introduction", "content": "# The Problem\n\nThis research addresses...", "footer": "[^1]: Citation reference\n[^2]: Another reference", "idx": 0, "id": "aB3xK9" } ] ``` -------------------------------- ### Setup Frontend Cloud Deployment Environment Variables Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md Create a .env file in the frontend directory for cloud deployment, specifying the CopilotKit Cloud API key and the remote deployment URL. ```bash cd frontend cat << EOF > .env NEXT_PUBLIC_COPILOT_CLOUD_API_KEY=your_key DEPLOYMENT=remote DEPLOYMENT_URL=https://your-langgraph-deployment.url EOF ``` -------------------------------- ### Usage Example for Config Class LLMs Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/agent-config.md Demonstrates how to use the BASE_LLM for general tasks and FACTUAL_LLM for precise, fact-based tasks after initializing the Config class. ```python from config import Config cfg = Config() # Use the base LLM for general tasks response = cfg.BASE_LLM.invoke("Your prompt here") # Use the factual LLM for precise, fact-based tasks factual_response = cfg.FACTUAL_LLM.invoke("Fact-check this: ...") ``` -------------------------------- ### Proposal Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-types.md An example illustrating the structure of a complete research paper proposal object, including nested sections, timestamp, and approval status. ```typescript { "sections": { "intro": { "title": "Introduction", "description": "Overview", "approved": true }, "conclusion": { "title": "Conclusion", "description": "Summary", "approved": false } }, "timestamp": "2024-06-15T10:30:45.123456", "approved": false, "remarks": "Focus on recent developments in the introduction" } ``` -------------------------------- ### Run Next.js Development Server Source: https://github.com/copilotkit/open-research-ana/blob/main/frontend/README.md Use these commands to start the local development server for your Next.js application. Open http://localhost:3000 in your browser to view the result. ```bash npm run dev # or yarn dev # or pnpm dev # or bun dev ``` -------------------------------- ### Section Interface Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-types.md Demonstrates how to create and access properties of a Section object. ```typescript import { Section } from '@/lib/types' const section: Section = { title: "Introduction", content: "# The Research Question\n\nThis section...", idx: 0, footer: "[^1]: Citation reference", id: "aB3xK9" } console.log(section.title) // "Introduction" console.log(section.content) // Markdown content console.log(section.idx) // 0 ``` -------------------------------- ### Section Writer Usage Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/tools.md Demonstrates how to call the section_writer tool with sample state and parameters, and how to access the generated section content from the returned state. ```python from tools.section_writer import section_writer state = { "outline": { "section0": {"title": "Introduction", "description": "Overview"} }, "sources": { "https://example.com": { "title": "Research Paper", "url": "https://example.com", "content": "AI is transforming industries..." } }, "sections": [], "logs": [], "messages": {} } new_state, message = await section_writer( research_query="Impact of AI on society", section_title="Introduction", idx=0, state=state ) # state["sections"] now contains one section with title, content, footer, idx, id print(new_state["sections"][0]["content"][:100]) ``` -------------------------------- ### Development Deployment Topology Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/architecture.md Illustrates the local development setup, showing the connection between the Next.js frontend, LangGraph local backend, and external APIs. ```text localhost:3000 (Next.js) ↓ /api/copilotkit → localhost:8123 (LangGraph local) ↓ OpenAI API Tavily API ``` -------------------------------- ### DocumentsView Usage Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-components.md Example of how to use the DocumentsView component, which displays research sections. It requires sections, a streaming section, and a selected section, along with a handler for section selection. ```typescript import { DocumentsView } from "@/components/documents-view" export default function HomePage() { const { sections } = useResearch() const [selectedSectionId, setSelectedSectionId] = useState(null) const streamingSection = useStreamingContent(researchState) return ( s.id === selectedSectionId)} onSelectSection={setSelectedSectionId} /> ) } ``` -------------------------------- ### State Mutation Pattern Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/research-state.md Shows how state updates are collected using the command pattern. This snippet demonstrates the structure of the state dictionary being prepared for updates. ```python # In tool_node tool_state = { "title": new_state.get("title", ""), "outline": new_state.get("outline", {}), "sections": new_state.get("sections", []), "sources": new_state.get("sources", {}), "proposal": new_state.get("proposal", {}), "logs": new_state.get("logs", []), "tool": new_state.get("tool", {}), "messages": msgs } ``` -------------------------------- ### Sources Interface and Iteration Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-types.md Shows how to define and iterate over the Sources object, accessing individual source details. ```typescript import { Source, Sources } from '@/lib/types' const sources: Sources = { "https://example.com": { title: "Research Paper", url: "https://example.com", content: "Summary...", published_date: "2024-06-15", score: 0.92 } } // Iterate over sources Object.entries(sources).forEach(([url, source]) => { console.log(source.title) // "Research Paper" console.log(source.score) // 0.92 }) ``` -------------------------------- ### Check Python Version Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/quick-reference.md Verify that the correct Python version (3.12) is installed for the backend. ```bash python --version # Should be 3.12 ``` -------------------------------- ### Example Usage of IProposalItem Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/types-reference.md Demonstrates how to structure an object conforming to the IProposalItem type alias. ```typescript { "intro": { title: "Introduction", description: "...", approved: false }, "methods": { title: "Methods", description: "...", approved: true } } ``` -------------------------------- ### Progress Component Usage Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-components.md Example of using the Progress component within a custom render function. It conditionally renders the Progress component if there are logs available. ```typescript import { Progress } from "@/components/progress" useCoAgentStateRender({ name: 'agent', render: ({ state }) => { if (state.logs?.length > 0) { return } return null }, }, [researchState]) ``` -------------------------------- ### Import necessary modules for CopilotKit runtime Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-api-endpoint.md Import the required classes and functions from the CopilotKit runtime and OpenAI SDK. This setup is essential for initializing the runtime and its adapters. ```typescript import { CopilotRuntime, OpenAIAdapter, copilotRuntimeNextJSAppRouterEndpoint, langGraphPlatformEndpoint, } from '@copilotkit/runtime' import OpenAI from 'openai' import { NextRequest } from 'next/server' const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY }) const serviceAdapter = new OpenAIAdapter({ openai }) ``` -------------------------------- ### Build System Prompt for ResearchAgent Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/research-agent.md Constructs a dynamic system prompt for the LLM based on the current research state. This prompt guides the LLM's behavior, tool usage, and response generation. ```python prompt = agent._build_system_prompt(state) # Returns: "Today's date is 15/06/2024.\nYou are an expert research assistant..." # Plus context about outline and sections if they exist ``` -------------------------------- ### Chat Component Usage Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-components.md Demonstrates how to use the Chat component in a React application, including setting up an onSubmitMessage handler to clear logs before a new research task. ```typescript import Chat from "@/components/chat" export default function HomePage() { return ( { // Clear logs before starting new research setResearchState({ ...researchState, logs: [] }) await new Promise((resolve) => setTimeout(resolve, 30)) }} /> ) } ``` -------------------------------- ### Section Structure Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/tools.md Illustrates the expected structure of a section object within the research state. Includes fields for title, content, footer, index, and a unique ID. ```python { "title": "Introduction", "content": "# The Problem\n\nThis research addresses...", "footer": "[^1]: Reference 1\n[^2]: Reference 2", "idx": 0, "id": "aB3xK9" # Random 6-character ID } ``` -------------------------------- ### Check Frontend Deployment Configuration Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/quick-reference.md Inspect the DEPLOYMENT and LOCAL_DEPLOYMENT_URL environment variables to ensure the frontend is configured correctly for local development. ```bash echo $DEPLOYMENT echo $LOCAL_DEPLOYMENT_URL ``` -------------------------------- ### Initialize Tools for ResearchAgent Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/research-agent.md Sets up the tool registry and name-to-tool mapping within the ResearchAgent. This method populates the agent's available tools for runtime use. ```python agent._initialize_tools() # agent.tools is now [tavily_search, tavily_extract, outline_writer, section_writer, review_proposal] # agent.tools_by_name is {"tavily_search": , "tavily_extract": , ...} ``` -------------------------------- ### Initialize Config Class Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/agent-config.md Instantiates the Config class to manage LLM and configuration settings. ```python class Config: def __init__(self) ``` -------------------------------- ### Configure Frontend for CopilotKit Cloud Deployment Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md Set the NEXT_PUBLIC_COPILOT_CLOUD_API_KEY environment variable in the frontend configuration for CopilotKit Cloud deployment. ```bash NEXT_PUBLIC_COPILOT_CLOUD_API_KEY=your_key ``` -------------------------------- ### Check API Keys Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/quick-reference.md Confirm that your essential API keys (OpenAI, Tavily, LangSmith) are set in the environment. ```bash echo $OPENAI_API_KEY echo $TAVILY_API_KEY echo $LANGSMITH_API_KEY ``` -------------------------------- ### Initialize and Register Tools Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/tools.md Tools are initialized and registered within the ResearchAgent._initialize_tools() method. This ensures all necessary tools are available for the agent. ```python self.tools = [tavily_search, tavily_extract, outline_writer, section_writer, review_proposal] self.tools_by_name = {tool.name: tool for tool in self.tools} ``` -------------------------------- ### Troubleshoot Frontend-Agent Connection Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md Steps to troubleshoot when the frontend cannot reach the agent, including verifying URLs, deployment settings, and network connectivity. ```bash Verify LOCAL_DEPLOYMENT_URL matches the `langgraph up` output Check DEPLOYMENT variable is set correctly ("local" or "remote") Run `curl http://localhost:8123/health` to test agent connection Verify firewall allows port 8123 ``` -------------------------------- ### Instantiate Config Class at Module Load Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/agent-config.md Shows the instantiation of the Config class once at module load time, typically in agent/graph.py, for shared use across graph nodes. ```python cfg = Config() ``` -------------------------------- ### ResearchAgent Class Definition Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/INDEX.md Defines the main orchestrator class for the research agent, including its initialization, tool setup, workflow building, and asynchronous node calling methods. ```python class ResearchAgent: def __init__(): def _initialize_tools(self) -> None def _build_workflow(self) -> None def _build_system_prompt(self, state: ResearchState) -> str async def call_model_node(self, state: ResearchState, config: RunnableConfig) -> Command async def tool_node(self, state: ResearchState, config: RunnableConfig) -> Command @staticmethod async def process_feedback_node(self, state: ResearchState, config: RunnableConfig) ``` -------------------------------- ### Production Deployment Topology (CopilotKit Cloud) Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/architecture.md Shows the production deployment using CopilotKit Cloud, highlighting the path through CopilotKit's managed service to the LangGraph deployment and APIs. ```text your-domain.com (Next.js) ↓ → cloud.copilotkit.ai/v1 (managed by CopilotKit) ↓ → your-deployment.cloud.langserve.com ↓ OpenAI API, Tavily API ``` -------------------------------- ### Frontend API Endpoint Reference Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/MANIFEST.txt Details on the API endpoints available for frontend interactions. This section guides developers on how to access and utilize the project's backend services from the frontend. ```APIDOC ## API Endpoints This section details the API endpoints available for frontend interactions. Refer to `frontend-api-endpoint.md` for specific details. ### Finding API Endpoints To find a specific API endpoint, consult the `frontend-api-endpoint.md` file and use the `quick-reference.md` for common tasks. ``` -------------------------------- ### Progress Logs Tool Execution Flow Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/architecture.md Describes the flow for emitting and displaying progress logs during tool execution, from initial log entry to completion. ```text Tool execution: ├─ Tool appends log entry with done=false ├─ copilotkit_emit_state sends to frontend ├─ Progress component re-renders with new log ├─ Tool completes, sets done=true ├─ Final emit shows completion └─ Log fades or clears ``` -------------------------------- ### TypeScript Optional Chaining Example Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/types-reference.md Demonstrates safe access to potentially undefined properties using optional chaining and the nullish coalescing operator. This is useful for handling state variables that might not be initialized. ```typescript const title = researchState?.title || "Untitled" ``` -------------------------------- ### process_feedback_node Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/research-agent.md Interrupts the graph to get user feedback on the proposal via the frontend, processes approvals, and routes back to call_model_node. It pauses execution to wait for frontend feedback, processes approved sections, and updates the state. ```APIDOC ## `process_feedback_node(state: ResearchState, config: RunnableConfig) -> Command[...]` (async, static) ### Description Interrupts the graph to get user feedback on the proposal via the frontend, processes approvals, and routes back to `call_model_node`. This function is responsible for pausing the workflow to allow user interaction and then resuming with updated state information. ### Method Signature ```python @staticmethod async def process_feedback_node( state: ResearchState, config: RunnableConfig ) -> Command[...] ``` ### Parameters #### Path Parameters * None #### Query Parameters * None #### Request Body * None ### Parameters - **state** (ResearchState) - Required - Current workflow state with proposal. - **config** (RunnableConfig) - Required - LangGraph runtime config. ### Returns - **Command** — Routes to `call_model_node` with updated state. ### Description of Functionality 1. Calls `interrupt(state.get("proposal", {{}}))` to pause and wait for frontend feedback via CopilotKit. 2. Extracts approved sections from the feedback. 3. Builds the `outline` dict from approved sections: `{section_key: {title, description}}`. 4. Updates `state["proposal"]` with the reviewed data. 5. Adds a SystemMessage to notify the LLM that feedback was received. 6. Returns a Command with all state updates routing to `call_model_node`. ### Frontend Interaction The `ProposalViewer` component on the frontend renders the proposal and allows users to: - Check/uncheck sections for approval. - Add remarks/feedback. - Submit (approved=True) or reject (approved=False). ### Throws - Interruption is caught and resumed by the CopilotKit runtime. ### Example ```python # Example usage within the workflow (conceptual) # Assume state contains a proposal that needs review # result = await agent.process_feedback_node(state, config) # The workflow will pause here until user provides feedback via the frontend. # Upon feedback, the state is updated and the graph continues to call_model_node. ``` ``` -------------------------------- ### Configure Frontend for Remote LangGraph Cloud Deployment Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md Set environment variables in the frontend's .env file for remote deployment to LangGraph Cloud, including the deployment URL and LangSmith API key. ```bash DEPLOYMENT=remote DEPLOYMENT_URL=https://your-deployment-id-xxxx.cloud.langserve.com LANGSMITH_API_KEY=your_key ``` -------------------------------- ### Backend Graph Structure Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/architecture.md Illustrates the flow of execution within the backend graph, including decision points for tool calls and feedback processing. ```mermaid entry_point │ ▼ call_model_node (LLM decision point) │ ├─ If tool_calls exist: │ └─ tool_node │ ├─ tavily_search? │ ├─ tavily_extract? │ ├─ outline_writer? │ ├─ section_writer? │ └─ review_proposal? → process_feedback_node │ └─ No tool calls: __end__ tool_node │ ├─ Execute selected tool ├─ Update state ├─ Emit to frontend │ └─ → call_model_node process_feedback_node (interrupt) │ ├─ Wait for frontend feedback ├─ Extract approved sections ├─ Update outline │ └─ → call_model_node ``` -------------------------------- ### Clear Frontend Cache and Restart Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/quick-reference.md Troubleshoot frontend connection issues by removing the Next.js cache and restarting the development server. ```bash rm -rf frontend/.next pnpm run dev ``` -------------------------------- ### Tool Invocation in tool_node Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/architecture.md Demonstrates how a tool is invoked within the tool_node, including state injection and message formatting. ```python # Extract tool call from LLM response tool_call = state["messages"][-1].tool_calls[0] # Inject state into args tool_call["args"]["state"] = state # Invoke tool new_state, tool_msg = await tool.ainvoke(tool_call["args"]) # Wrap in ToolMessage ToolMessage(content=tool_msg, name=tool.name, tool_call_id=tool_call["id"]) # Extract fields for commit { "title": new_state.get("title"), "outline": new_state.get("outline"), # ... other fields } ``` -------------------------------- ### Initialize ResearchAgent Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/research-agent.md Instantiates the ResearchAgent class to set up its research workflow capabilities. ```python from graph import ResearchAgent agent = ResearchAgent() # Agent is now ready with workflow compiled ``` -------------------------------- ### Environment variables for CopilotKit integration Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-api-endpoint.md Lists the required environment variables for both production and local CopilotKit deployments, including API keys and deployment URLs. ```bash # LLM OPENAI_API_KEY=sk-... # LangSmith (tracing and deployment) LANGSMITH_API_KEY=ls__... # Deployment selection DEPLOYMENT=local # or "remote" # Deployment URLs LOCAL_DEPLOYMENT_URL=http://localhost:8123 # For local development DEPLOYMENT_URL=https://your-langgraph-deployment.url # For production # Frontend NEXT_PUBLIC_COPILOT_CLOUD_API_KEY=your_key # If using CopilotKit Cloud ``` -------------------------------- ### Configure LLM Models in Backend Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/quick-reference.md Modify the agent's configuration file to change the base and factual LLM models, including their parameters like temperature. ```python self.BASE_LLM = ChatOpenAI(model="gpt-4-turbo", temperature=0.3) self.FACTUAL_LLM = ChatOpenAI(model="gpt-4o", temperature=0.0) ``` -------------------------------- ### Frontend Local Development Environment Variables Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/README.md Required environment variables for the frontend when deploying locally. Specifies the deployment mode and the URL for the local backend. ```dotenv DEPLOYMENT=local LOCAL_DEPLOYMENT_URL=http://localhost:8123 ``` -------------------------------- ### Proposal Review Flow Steps Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/architecture.md Outlines the sequential steps involved in the proposal review process, from user request to final report generation. ```text 1. User asks agent to write a report 2. Agent decides structure is ready 3. Agent calls review_proposal tool 4. tool_node routes to process_feedback_node 5. process_feedback_node calls interrupt(proposal) 6. Graph pauses; CopilotKit holds execution 7. Frontend renders ProposalViewer 8. User checks sections, adds remarks 9. User clicks "Approve Proposal" 10. ProposalViewer calls resolve() with JSON 11. Graph resumes with reviewed_outline 12. process_feedback_node extracts approved sections 13. state["outline"] now has only approved sections 14. Command routes to call_model_node 15. Agent sees outline; calls section_writer for approved sections 16. Sections written one-by-one 17. Agent finishes; graph ends ``` -------------------------------- ### Metadata Configuration Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-layout.md Sets the HTML page title and meta description for the application. ```typescript export const metadata: Metadata = { title: "Open Research ANA", description: "Open Research Agent Native Application for AI research", } ``` -------------------------------- ### Troubleshoot CopilotKit Cloud Connection Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md Steps to troubleshoot connection failures with CopilotKit Cloud, including API key validation, URL reachability, and LangSmith access. ```bash Verify NEXT_PUBLIC_COPILOT_CLOUD_API_KEY is valid Check DEPLOYMENT_URL is reachable: `curl $DEPLOYMENT_URL/health` Verify LangSmith API key has access to the deployment ``` -------------------------------- ### Production Deployment Topology (LangGraph Cloud) Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/architecture.md Depicts the production deployment architecture using LangGraph Cloud, detailing the routing from the domain to the LangGraph deployment and APIs. ```text your-domain.com (Next.js) ↓ /api/copilotkit → your-deployment.cloud.langserve.com ↓ OpenAI API Tavily API ``` -------------------------------- ### Type Conversion: Backend to Frontend Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/types-reference.md Illustrates the serialization process from a Python dictionary to a JSON object, then to a TypeScript ResearchState interface. ```text Python dict → JSON → TypeScript ResearchState ``` -------------------------------- ### Configure LangGraph Deployment Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/research-agent.md Configure the research agent graph in the langgraph.json file for deployment. ```json { "graphs": { "agent": "./graph.py:graph" } } ``` -------------------------------- ### Type Conversion: Tool Arguments Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/types-reference.md Describes the data flow for tool arguments and return values between the frontend and backend, involving JSON, Pydantic, and tool functions. ```text Frontend sends: JSON → Pydantic model (validation) → Tool function Tool returns: Tuple[Dict, str] → JSON → Frontend ``` -------------------------------- ### Initializing and Modifying ResearchState Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-types.md Demonstrates how to initialize a ResearchState object and add log entries or sections to it. ```typescript import { ResearchState } from '@/lib/types' const state: ResearchState = { title: "AI Impact Study", sections: [], sources: {}, proposal: { sections: {}, timestamp: new Date().toISOString(), approved: false, remarks: "" }, outline: {}, tool: "outline_writer", messages: [], logs: [] } // Add a log entry state.logs.push({ message: "🌐 Searching the web", done: false }) // Add a section state.sections.push({ title: "Introduction", content: "...", idx: 0, id: "abc123" }) ``` -------------------------------- ### Open a Tunnel to Local Agent Source: https://github.com/copilotkit/open-research-ana/blob/main/README.md Use the CopilotKit CLI to create a tunnel to your local agent, specifying the port it's running on. ```bash npx copilotkit@latest dev --port 8123 ``` -------------------------------- ### Backend Import Paths Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/INDEX.md Imports necessary modules for the main graph, state management, configuration, and tools used in the backend research agent. ```python # Main graph from graph import graph, ResearchAgent from state import ResearchState from config import Config # Tools from tools.tavily_search import tavily_search from tools.tavily_extract import tavily_extract from tools.outline_writer import outline_writer from tools.section_writer import section_writer ``` -------------------------------- ### Global CSS Imports Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-layout.md Imports necessary CSS files for CopilotKit UI and custom global styles. ```typescript import "@copilotkit/react-ui/styles.css" import "./globals.css" ``` -------------------------------- ### Add a New Tool to Backend Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/quick-reference.md Define a new tool in its own Python file, import it into the graph definition, and add it to the list of available tools. ```python from langchain_core.tools import tool from pydantic import BaseModel, Field class MyToolInput(BaseModel): param1: str = Field(description="...") state: Optional[Dict] = Field(description="...") @tool("my_tool", args_schema=MyToolInput, return_direct=True) async def my_tool(param1: str, state: Dict): # Modify state # return state, message ``` ```python from tools.my_tool import my_tool self.tools = [..., my_tool] ``` -------------------------------- ### Frontend Remote Deployment Environment Variables Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/README.md Required environment variables for the frontend when deploying remotely. Specifies the deployment mode, the URL for the remote backend, and the LangSmith API key. ```dotenv DEPLOYMENT=remote DEPLOYMENT_URL=https://... LANGSMITH_API_KEY=ls__... ``` -------------------------------- ### Bind Tools to FACTUAL_LLM Instance Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/agent-config.md Illustrates binding tools to the FACTUAL_LLM instance within the call_model_node function for specific tool usage. ```python model = cfg.FACTUAL_LLM.bind_tools(self.tools, parallel_tool_calls=False) ``` -------------------------------- ### Agent configuration object Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-api-endpoint.md Defines the configuration for an agent, including its name and description. This object must match backend and frontend configurations. ```typescript { name: 'agent', description: 'Research assistant' } ``` -------------------------------- ### System Prompt for Focused Search Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/quick-reference.md Configure the agent's system message to use fewer, more focused search queries for better performance. ```python "When searching, use 2-3 focused queries rather than many queries" ``` -------------------------------- ### ProposalViewer State Initialization Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-components.md Illustrates how to initialize the local state for the reviewed proposal within the ProposalViewer component using the useState hook. ```typescript const [reviewedProposal, setReviewedProposal] = useState(proposal) ``` -------------------------------- ### Frontend Component Architecture Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/architecture.md This diagram outlines the frontend component structure, including layout, CopilotKit integration, and specific UI components like Chat and DocumentsView. It details the usage of custom hooks and third-party libraries. ```text Layout ├─ CopilotKit (provider) ├─ TooltipProvider (Radix) ├─ ResearchProvider (context) │ └─ useResearch hook │ └─ HomePage ├─ Chat │ └─ CopilotChat (from @copilotkit/react-ui) │ ├─ Divider (draggable) │ └─ DocumentsView ├─ DocumentOptions (mode toggle, edit) ├─ DocumentViewer (markdown rendering) ├─ DocumentsScrollbar (section navigator) │ └─ DocumentFooter └─ SourcesModal Overlays (via hooks): ├─ Progress (shows logs) └─ ProposalViewer (interrupt handler) ``` -------------------------------- ### Backend Environment Variables Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/README.md Required environment variables for the backend (agent/). These include API keys for OpenAI, Tavily, and LangSmith. ```dotenv OPENAI_API_KEY=sk-... TAVILY_API_KEY=tvly-... LANGSMITH_API_KEY=ls__... ``` -------------------------------- ### Frontend Import Paths Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/INDEX.md Imports essential components, hooks, types, and constants for the frontend of the research application. ```typescript // Context and hooks import { useResearch, ResearchProvider } from "@/components/research-context" import { useCoAgent, useCopilotChat, useCopilotStateRender } from "@copilotkit/react-core" // Components import Chat from "@/components/chat" import { DocumentsView } from "@/components/documents-view" import { ProposalViewer } from "@/components/structure-proposal-viewer" // Types import type { ResearchState, Section, Proposal, Source } from "@/lib/types" // Constants import { MAIN_CHAT_INSTRUCTIONS, INITIAL_MESSAGE } from "@/lib/consts" ``` -------------------------------- ### LangGraph Configuration Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md The langgraph.json file configures the LangGraph deployment, specifying graph exports, environment file location, and Python version. ```json { "dockerfile_lines": [], "graphs": { "agent": "./graph.py:graph" }, "env": ".env", "python_version": "3.12", "dependencies": [ "." ] } ``` -------------------------------- ### Agent Tools Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/INDEX.md Lists the available tools for the research agent, including their function signatures and purpose. ```python 1. tavily_search(sub_queries: List[TavilyQuery], state: Dict) -> Tuple[Dict, str] 2. tavily_extract(urls: List[str], state: Dict) -> Tuple[Dict, str] 3. outline_writer(research_query: str, state: Dict) -> Tuple[Dict, str] 4. section_writer(research_query: str, section_title: str, idx: int, state: Dict) -> Tuple[Dict, str] 5. review_proposal(proposal: str) -> str (routing tool) ``` -------------------------------- ### DocumentsView State Initialization Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/frontend-components.md Shows the initialization of the document options state in the DocumentsView component, controlling the view mode and edit mode. ```typescript const [documentOptionsState, setDocumentOptionsState] = useState({ mode: 'full', editMode: false }) ``` -------------------------------- ### Research Agent Model Configuration Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/configuration.md The Config class in agent/config.py defines the base and factual language models, along with a debug flag. The BASE_LLM uses gpt-4 with a temperature of 0.2 for general reasoning, while FACTUAL_LLM uses gpt-4o-mini with a temperature of 0.0 for deterministic outputs. ```python class Config: def __init__(self): self.BASE_LLM = ChatOpenAI(model="gpt-4", temperature=0.2) self.FACTUAL_LLM = ChatOpenAI(model="gpt-4o-mini", temperature=0.0) self.DEBUG = False ``` -------------------------------- ### Tool Execution Pattern Source: https://github.com/copilotkit/open-research-ana/blob/main/_autodocs/architecture.md Standard Python decorator and function signature for defining tools, including state modification and frontend emission. ```python @tool("tool_name", args_schema=InputSchema, return_direct=True) async def tool_name(param1: Type1, param2: Type2, state: Dict) -> Tuple[Dict, str]: """ Modifies state and returns (updated_state, tool_message). """ # Modify state state["field"] = new_value # Emit progress to frontend await copilotkit_emit_state(config, state) # Return for tool_message return state, "Tool completed" ```