You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

CopilotKit集成遇401错误:X-CopilotCloud-Public-API-Key疑问求助

问题描述

集成可添加任务的Copilot AI聊天机器人时,请求添加任务控制台出现Failed to load resource: the server responded with a status of 401 () api.copilotkit.ai/copilotkit/v1:1错误。

项目基于Node.js + Express.js,已参照文档集成,server.js代码如下:

import express from 'express';
import cors from 'cors';
import path from 'path';
import { fileURLToPath } from 'url';
import { CopilotRuntime, OpenAIAdapter, copilotRuntimeNextJSAppRouterEndpoint } from '@copilotkit/runtime';
import OpenAI from 'openai';
import dotenv from 'dotenv';
import axios from 'axios';

dotenv.config();

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);  

console.log("Loaded API Key:", process.env.OPENAI_API_KEY);

const app = express();
const port = 5000; 

app.use(cors());
app.use(express.json());

const corsOptions = { 
  origin: '*', // Allow all origins 
  methods: ['GET', 'POST'], // Allow GET and POST methods 
  allowedHeaders: ['Content-Type', 'Authorization'], 
  }; 
  app.use(cors(corsOptions)); // Apply CORS middleware 
  app.use(express.json());

const openai = new OpenAI({ apiKey: process.env.OPENAI_API_KEY });
const serviceAdapter = new OpenAIAdapter({ openai });
const runtime = new CopilotRuntime();

const handleRequest = copilotRuntimeNextJSAppRouterEndpoint({ 
runtime, 
serviceAdapter, 
endpoint: '/api/copilotkit', 
}).handleRequest;

app.post('/api/copilotkit', async (req, res) => {
  try{
    const token = `Bearer ${process.env.OPENAI_API_KEY}`;
    console.log("Authorization Token:",token);
    console.log("Request Payload:", req.body);

    const response = await axios({ 
    method: 'post', 
    url: 'https://api.copilotkit.ai/copilotkit/v1', 
    headers: { 
    Authorization: token,
    'Content-Type': 'application/json',
    }, 
    data: req.body,
    });
    res.status(response.status || 200).send(response.body || {});
}catch (error) {
  console.error("Error in /api/copilotkit route:", error.response?.data || error.message);
  res.status(500).send({ error: "An error occurred while processing your request." });
}
});

app.use(express.static(path.join(__dirname, 'dist')));
app.get('*', (req, res) => {
  res.sendFile(path.join(__dirname, 'dist', 'index.html'));
});
app.listen(port, () => {
  console.log(`Server running at http://localhost:${port}`);
});

用Postman向https://api.copilotkit.ai/copilotkit/v1发送POST请求返回401错误,GET请求正常,错误信息:

{
    "message": "X-CopilotCloud-Public-API-Key header is required",
    "extensions": {
        "code": "UNAUTHORIZED"
      }
}

发送的请求头:

  • Authorization: Bearer OPENAI_API_KEY
  • X-CopilotCloud-Public-API-Key: OPENAI_API_KEY
  • Content-Type: application/json

已确认.env中OPENAI_API_KEY加载正常,配置如下:

OPENAI_API_KEY= api key
VITE_OPENAI_API_KEY=api key
API_ENDPOINT=http://localhost:5000

尝试更换端点为/completions和/models无效,OPENAI_API_KEY权限已全开。疑问:X-CopilotCloud-Public-API-Key是否需要与OPENAI_API_KEY不同的密钥?若需要,该如何获取?

解决方案
  • X-CopilotCloud-Public-API-Key与OPENAI_API_KEY是不同的密钥
    你当前用OPENAI_API_KEY填充X-CopilotCloud-Public-API-Key是错误的,这两个密钥分属不同服务:

    • OPENAI_API_KEY是OpenAI平台的密钥,用于调用OpenAI的模型接口
    • X-CopilotCloud-Public-API-Key是CopilotCloud平台的专属密钥,用于验证对CopilotKit云服务的访问权限
  • 获取X-CopilotCloud-Public-API-Key的步骤

    1. 注册并登录CopilotCloud官方平台
    2. 进入控制台的API密钥管理页面
    3. 创建新的Public API密钥,复制保存该密钥
  • 代码修正

    1. 在.env中添加新的变量:
      COPILOT_CLOUD_PUBLIC_KEY=你的CopilotCloud公钥
      
    2. 修改server.js中请求https://api.copilotkit.ai/copilotkit/v1的请求头,添加正确的X-CopilotCloud-Public-API-Key:
      const response = await axios({ 
        method: 'post', 
        url: 'https://api.copilotkit.ai/copilotkit/v1', 
        headers: { 
          Authorization: token,
          'X-CopilotCloud-Public-API-Key': process.env.COPILOT_CLOUD_PUBLIC_KEY,
          'Content-Type': 'application/json',
        }, 
        data: req.body,
      });
      
    3. 同时确保CORS配置中允许X-CopilotCloud-Public-API-Key请求头,修改corsOptions:
      const corsOptions = { 
        origin: '*', 
        methods: ['GET', 'POST'], 
        allowedHeaders: ['Content-Type', 'Authorization', 'X-CopilotCloud-Public-API-Key'], 
      }; 
      

内容的提问来源于stack exchange,提问作者Debasish Raha

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.16 01:23:14