最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Failed to load resource: the server responded with a status of 401 () api.copilotkit.aicopilotkitv1:1 - Stack Overf

programmeradmin1浏览0评论

i am trying to add a copilot ai chatbot which can add tasks and on asking it to add a task, the following console message is showing.

I have used copilot AI documentation for integrating the copilot chatbot My project is built using Node.js for the backend, with the Express.js framework to handle server-side operations and API endpoints. this is my server.js code :

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: '', 
    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}`);
});

I keep getting a 401 Unauthorized error when sending a POST request in postman, using , while it works with a GET request (200 OK). it shows :

{
    "message": "X-CopilotCloud-Public-API-Key header is required",
    "extensions": {
        "code": "UNAUTHORIZED"
      }
}
Headers sent :
Authorization : Bearer OPENAI_API_KEY
X-CopilotCloud-Public-API-Key : OPENAI_API_KEY
Content-Type: application/json

I have verified that my OPENAI_API_KEY is correctly loaded from .env. my .env file looks like :

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

I have tried changing the endpoint from (base url) to /completions and /models but neither works.

And all permissions of my API key are allowed in the API keys section. Can someone clarify if the X-CopilotCloud-Public-API-Key header requires a different key than OPENAI_API_KEY? If so, where can this key be obtained?

i am trying to add a copilot ai chatbot which can add tasks and on asking it to add a task, the following console message is showing.

I have used copilot AI documentation for integrating the copilot chatbot My project is built using Node.js for the backend, with the Express.js framework to handle server-side operations and API endpoints. this is my server.js code :

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}`);
});

I keep getting a 401 Unauthorized error when sending a POST request in postman, using https://api.copilotkit.ai/copilotkit/v1, while it works with a GET request (200 OK). it shows :

{
    "message": "X-CopilotCloud-Public-API-Key header is required",
    "extensions": {
        "code": "UNAUTHORIZED"
      }
}
Headers sent :
Authorization : Bearer OPENAI_API_KEY
X-CopilotCloud-Public-API-Key : OPENAI_API_KEY
Content-Type: application/json

I have verified that my OPENAI_API_KEY is correctly loaded from .env. my .env file looks like :

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

I have tried changing the endpoint from https://api.copilotkit.ai/copilotkit/v1(base url) to /completions and /models but neither works.

And all permissions of my API key are allowed in the API keys section. Can someone clarify if the X-CopilotCloud-Public-API-Key header requires a different key than OPENAI_API_KEY? If so, where can this key be obtained?

Share Improve this question edited Nov 24, 2024 at 23:41 President James K. Polk 42k28 gold badges109 silver badges145 bronze badges asked Nov 22, 2024 at 5:15 Debasish RahaDebasish Raha 11 bronze badge 1
  • The issue lies in a misunderstanding of the purpose of the X-CopilotCloud-Public-API-Key header. This header is a requirement for interacting with the Copilot Cloud API, and it does not use the same key as the OpenAI API key (OPENAI_API_KEY). The X-CopilotCloud-Public-API-Key is a specific API key provided by Copilot Cloud, which is independent of OpenAI's API keys. – Shehan Lakshitha Commented Nov 22, 2024 at 6:53
Add a comment  | 

1 Answer 1

Reset to default 0

Check your X-CopilotCloud-Public-API-Key. The error seems to be there. OPENAI_API_KEY will not be the same as. Restart your server after changing it. If it doesn't work, check if you can get correct results from api endpoints with postman. Or via browser. I hope your problem is solved that.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论