useCopilotAction( { name: "generateCodeAndImplementationTutorial", description: "Create Code Snippet with React.js(Next.js), tailwindcss and an implementation tutorial of the code generated.", parameters: [ { name: "code", type: "string", description: "Code to be generated", required: true, }, { name: "tutorial", type: "string", description: "Markdown of step by step guide tutorial on how to use the generated code accompanied with the code. Include introduction, prerequisites and what happens at every step accompanied with code generated earlier. Don't forget to add how to render the code on browser.", required: true, }, ], handler: async ({ code, tutorial }) => { setCode((prev) => [...prev, code]); setCodeToDisplay(code); setCodeTutorial(tutorial); }, }, [codeToDisplay, codeTutorial] );
exportdefaultfunctionHome() { return ( <> <Header /> <CopilotKiturl="/api/copilotkit"> <CopilotSidebar instructions="Help the user generate code. Ask the user if to generate its tutorial." defaultOpen={true} labels={{ title: "Code & Tutorial Generator", initial: "Hi! 👋 I can help you generate code and its tutorial.", }}> <CodeTutorial /> CopilotSidebar
> CopilotKit> > ); }
// Define a runtime environment variable, indicating the environment where the code is expected to run. exportconst runtime = "edge";
// Define an annotated function for research. This object includes metadata and an implementation for the function. const researchAction: AnnotatedFunction = { name: "research", // Function name. description: "Call this function to conduct research on a certain topic. Respect other notes about when to call this function", // Function description. argumentAnnotations: [ // Annotations for arguments that the function accepts. { name: "topic", // Argument name. type: "string", // Argument type. description: "The topic to research. 5 characters or longer.", // Argument description. required: true, // Indicates that the argument is required. }, ], implementation: async (topic) => { // The actual function implementation. console.log("Researching topic: ", topic); // Log the research topic. returnawait researchWithLangGraph(topic); // Call the research function and return its result. }, };
然后在上述代码下方添加以下代码,定义一个处理POST请求的异步函数。
// Define an asynchronous function that handles POST requests. exportasyncfunctionPOST(req: Request): Promise<Response> { const actions: AnnotatedFunction[] = []; // Initialize an array to hold actions.
// Check if a specific environment variable is set, indicating access to certain functionality. if (process.env.TAVILY_API_KEY) { actions.push(researchAction); // Add the research action to the actions array if the condition is true. }
// Instantiate CopilotBackend with the actions defined above. const copilotKit = new CopilotBackend({ actions: actions, });
// Use the CopilotBackend instance to generate a response for the incoming request using an OpenAIAdapter. return copilotKit.response(req, new OpenAIAdapter()); }