Giter Site home page Giter Site logo

chatgpt-api's Introduction

Agentic

AI agent stdlib that works with any LLM and TypeScript AI SDK.

Build Status NPM MIT License Prettier Code Formatting

Agentic

Intro

Agentic is a standard library of AI functions / tools which are optimized for both normal TS-usage as well as LLM-based usage. Agentic works with all of the major TS AI SDKs (LangChain, LlamaIndex, Vercel AI SDK, OpenAI SDK, etc).

Agentic clients like WeatherClient can be used as normal TS classes:

import { WeatherClient } from '@agentic/stdlib'

// Requires `process.env.WEATHER_API_KEY` (free from weatherapi.com)
const weather = new WeatherClient()

const result = await weather.getCurrentWeather({
  q: 'San Francisco'
})
console.log(result)

Or you can use these clients as LLM-based tools where the LLM decides when and how to invoke the underlying functions for you.

This works across all of the major AI SDKs via adapters. Here's an example using Vercel's AI SDK:

// sdk-specific imports
import { openai } from '@ai-sdk/openai'
import { generateText } from 'ai'
import { createAISDKTools } from '@agentic/ai-sdk'

// sdk-agnostic imports
import { WeatherClient } from '@agentic/stdlib'

const weather = new WeatherClient()

const result = await generateText({
  model: openai('gpt-4o-mini'),
  // this is the key line which uses the `@agentic/ai-sdk` adapter
  tools: createAISDKTools(weather),
  toolChoice: 'required',
  prompt: 'What is the weather in San Francisco?'
})

console.log(result.toolResults[0])

You can use our standard library of thoroughly tested AI functions with your favorite AI SDK – without having to write any glue code!

Here's a slightly more complex example which uses multiple clients and selects a subset of their functions using the AIFunctionSet.pick method:

// sdk-specific imports
import { ChatModel, createAIRunner } from '@dexaai/dexter'
import { createDexterFunctions } from '@agentic/dexter'

// sdk-agnostic imports
import { PerigonClient, SerperClient } from '@agentic/stdlib'

async function main() {
  // Perigon is a news API and Serper is a Google search API
  const perigon = new PerigonClient()
  const serper = new SerperClient()

  const runner = createAIRunner({
    chatModel: new ChatModel({
      params: { model: 'gpt-4o-mini', temperature: 0 }
    }),
    functions: createDexterFunctions(
      perigon.functions.pick('search_news_stories'),
      serper
    ),
    systemMessage: 'You are a helpful assistant. Be as concise as possible.'
  })

  const result = await runner(
    'Summarize the latest news stories about the upcoming US election.'
  )
  console.log(result)
}

Docs

Full docs are available at agentic.so.

AI SDKs

Vercel AI SDK

Agentic adapter docs for the Vercel AI SDK

LangChain

Agentic adapter docs for LangChain

LlamaIndex

Agentic adapter docs for LlamaIndex

Firebase Genkit

Agentic adapter docs for Genkit

Dexa Dexter

Agentic adapter docs for Dexter

OpenAI

Agentic adapter docs for OpenAI

GenAIScript

Agentic support in GenAIScript

Tools

Service / Tool Package Docs Description
Bing @agentic/bing docs Bing web search.
Calculator @agentic/calculator docs Basic calculator for simple mathematical expressions.
Clearbit @agentic/clearbit docs Resolving and enriching people and company data.
Dexa @agentic/dexa docs Answers questions from the world's best podcasters.
Diffbot @agentic/diffbot docs Web page classification and scraping; person and company data enrichment.
E2B @agentic/e2b docs Hosted Python code intrepreter sandbox which is really useful for data analysis, flexible code execution, and advanced reasoning on-the-fly.
Exa @agentic/exa docs Web search tailored for LLMs.
Firecrawl @agentic/firecrawl docs Website scraping and structured data extraction.
HackerNews @agentic/hacker-news docs Official HackerNews API.
Hunter @agentic/hunter docs Email finder, verifier, and enrichment.
Jina @agentic/jina docs URL scraper and web search.
Midjourney @agentic/midjourney docs Unofficial Midjourney client for generative images.
Novu @agentic/novu docs Sending notifications (email, SMS, in-app, push, etc).
People Data Labs @agentic/people-data-labs docs People & company data (WIP).
Perigon @agentic/perigon docs Real-time news API and web content data from 140,000+ sources. Structured and enriched by AI, primed for LLMs.
Polygon @agentic/polygon docs Stock market and company financial data.
PredictLeads @agentic/predict-leads docs In-depth company data including signals like fundraising events, hiring news, product launches, technologies used, etc.
Proxycurl @agentic/proxycurl docs People and company data from LinkedIn & Crunchbase.
Searxng @agentic/searxng docs OSS meta search engine capable of searching across many providers like Reddit, Google, Brave, Arxiv, Genius, IMDB, Rotten Tomatoes, Wikidata, Wolfram Alpha, YouTube, GitHub, etc.
SerpAPI @agentic/serpapi docs Lightweight wrapper around SerpAPI for Google search.
Serper @agentic/serper docs Lightweight wrapper around Serper for Google search.
Slack @agentic/slack docs Send and receive Slack messages.
SocialData @agentic/social-data docs Unofficial Twitter / X client (readonly) which is much cheaper than the official Twitter API.
Tavily @agentic/tavily docs Web search API tailored for LLMs.
Twilio @agentic/twilio docs Twilio conversation API to send and receive SMS messages.
Twitter @agentic/twitter docs Basic Twitter API methods for fetching users, tweets, and searching recent tweets. Includes support for plan-aware rate-limiting. Uses Nango for OAuth support.
Weather @agentic/weather docs Basic access to current weather data based on location.
Wikidata @agentic/wikidata docs Basic Wikidata client.
Wikipedia @agentic/wikipedia docs Wikipedia page search and summaries.
Wolfram Alpha @agentic/wolfram-alpha docs Wolfram Alpha LLM API client for answering computational, mathematical, and scientific questions.

For more details, see the docs.

Contributors

License

MIT © Travis Fischer

To stay up to date or learn more, follow @transitive_bs on Twitter.

chatgpt-api's People

Contributors

0x7030676e31 avatar 189 avatar billylo1 avatar danielehrhardt avatar easydu2002 avatar fuergaosi233 avatar gencay avatar ikechan8370 avatar kodjunkie avatar maxlibin avatar mrloldev avatar noelzappy avatar nucks avatar oceanlvr avatar optionsx avatar pawanosman avatar pelikhan avatar simon300000 avatar skippyyy avatar timkmecl avatar timmsgithub avatar transitive-bullshit avatar waylaidwanderer avatar wong2 avatar xtremehpx avatar yi-ge avatar youking-lib avatar yunyu950908 avatar zeke avatar zhengxs2018 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

chatgpt-api's Issues

I overcome Cloudflare with puppeteer

the code is here

const fs = require('fs')
const puppeteer = require('puppeteer-extra')
puppeteer.use(require('puppeteer-extra-plugin-stealth')())

const sleep = duration => new Promise(resolve => setTimeout(resolve, duration))

async function start() {
  const browser = await puppeteer.launch({
    executablePath: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
    headless: false,
    args: ['--proxy-server=127.0.0.1:7890'],
    ignoreHTTPSErrors: true
  })
  const page = (await browser.pages())[0]

  await page.goto('https://chat.openai.com')
  await page.waitForSelector('#__next .btn-primary')
  // wait for networkidle
  await sleep(10 * 1000)
  await page.click('#__next .btn-primary')

  await page.waitForNavigation({
    waitUntil: 'networkidle0'
  })

  await page.type('#username', 'username')
  await page.click('button[name="action"]')

  await page.waitForSelector('#password')

  // await page.screenshot({
  //   path: 'screenshot.png'
  // })

  await page.type('#password', 'password')
  await page.click('button[name="action"]')

  await page.waitForNavigation({
    waitUntil: 'networkidle0'
  })

  fs.writeFileSync('cookies.json', JSON.stringify(await page.cookies()))

  // await sleep(60 * 1000)
  await browser.close()
}

start()
  .then(() => {
    process.exit(0)
  })
  .catch(() => {
    process.exit(1)
  })

Handle response timeouts

Sometimes the request will freeze and never finish, might be useful to have a timeout in ms attribute.

Thoughts on using Google to bypass reCAPTCHA/hCAPTCHA?

By login using Google, the only thing that requires user operations appears to be the 2-step verification from Google, and this can be done away using your smart phone.

Or is it going to be detected by Google after a few tries?

Like this:

...
await page.goto('https://chat.openai.com/auth/login')
await page.waitForSelector('#__next .btn-primary', { timeout })
await delay(1000)
try {
    if (email && password) {
        await Promise.all([
            page.click('#__next .btn-primary'),
            page.waitForNavigation({
                waitUntil: 'networkidle0'
            })
        ])
        await page.waitForSelector('button[data-provider="google"]', { timeout });
        await page.click('button[data-provider="google"]');
        await page.waitForNavigation({
            waitUntil: 'networkidle0'
        })
        await page.type('input[type="email"]', email, { delay: 50 })
        await page.keyboard.press("Enter");
        await delay(3000);
        await page.keyboard.type(password, { delay: 50 });
        await page.keyboard.press("Enter");
    }
} catch (err) {
    await browser.close();
    throw err;
}
await page.waitForSelector("items-center");
...

Add an automated way to fetch and refresh session tokens

This is currently the biggest hindrance with this package (and any other approach which uses the unofficial REST API).

At some point, session tokens expire. This is currently recognized and handled by throwing an error with the message ChatGPT failed to refresh auth token. Error: session token has expired, but most long-running integrations will need a better solution for this going forwards.

webpack bundle error

webpack 5.66.0 compiled successfully in 3940 ms
Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: xxx/node_modules/chatgpt/build/index.js
require() of ES modules is not supported.
require() of xxx/node_modules/chatgpt/build/index.js from xxx/dist/src/modules/chat/Chat.service.js is an ES module file as it is a .js file whose nearest parent package.json contains "type": "module" which defines all .js files in that package scope as ES modules.
Instead rename index.js to end in .cjs, change the requiring code to use import(), or remove "type": "module" from xxx/node_modules/chatgpt/package.json.

TODO

  • Add message and conversation IDs
  • Add support for streaming responses
  • Add basic unit tests

This browser or app may not be secure.

When trying to log in with Google I get...

This browser or app may not be secure.
Try using a different browser. If you’re already using a supported browser, you can try again to sign in.

Windows issue using chatgpt as commonjs package

My error is in the chatgpt package, it says that it needs a main module but it is not finding any. I am trying to use this package with react native.

The error:

Error: While trying to resolve module chatgpt from file D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\src\screens\Home\Home.tsx, the package D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\chatgpt\package.json was successfully found. However, this package itself specifies a main module field that could not be resolved (D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\chatgpt\index. Indeed, none of these files exist:

  • D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\chatgpt\index(.native|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
  • D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\chatgpt\index\index(.native|.android.js|.native.js|.js|.android.jsx|.native.jsx|.jsx|.android.json|.native.json|.json|.android.ts|.native.ts|.ts|.android.tsx|.native.tsx|.tsx)
    at DependencyGraph.resolveDependency (D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\metro\src\node-haste\DependencyGraph.js:277:17)
    at Object.resolve (D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\metro\src\lib\transformHelpers.js:170:21)
    at resolveDependencies (D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\metro\src\DeltaBundler\graphOperations.js:466:33)
    at processModule (D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\metro\src\DeltaBundler\graphOperations.js:232:31)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
    at async addDependency (D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\metro\src\DeltaBundler\graphOperations.js:361:18)
    at async Promise.all (index 4)
    at async processModule (D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\metro\src\DeltaBundler\graphOperations.js:279:3)
    at async addDependency (D:\Acadamics and Work\Work\Software Projects\ChatgptAssistant\frontend\node_modules\metro\src\DeltaBundler\graphOperations.js:361:18)
    at async Promise.all (index 2)

Switching to direct API requests

Headless Chrome seems a bit overkill for a Node.js API wrapper, and may not work on all machines (see line 36 in chatgpt-api.ts). The ChatGPT API allows direct requests given a CSRF token (which doesn't seem to change in my testing) and a session token, which can be obtained through the /api/auth/session endpoint.

How can I close a conversation?

It seems that if I don't close a conversion, the speed will become slower and slower.

Is there a way to close a conversation?

Issue with published cjs version of package

wondering if i'm doing something wrong but

with version 1.3.0 installed like this:

{
    "dependencies": {
        "chatgpt": "^1.3.0" 
    }
}

and trying to import it like this:

let { ChatGPTAPI } = require("chatgpt");

i'm still getting this error:

Error [ERR_REQUIRE_ESM]: Must use import to load ES Module: /var/task/node_modules/chatgpt/build/index.js require() of ES modules is not supported.

am i doing anything wrong?

Add better support for conversations

  • Expose message IDs to the user
  • Store the latest message ID as the default conversationId
  • Automatically update the default conversation ID if no conversationId is passed

See #26 which I need to review

[Bug] TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["cookie"]. Is ChatGPT API update?

image

here is error:

AggregateError: 
    Error: ChatGPT failed to refresh auth token. TypeError [ERR_INVALID_CHAR]: Invalid character in header content ["cookie"]
        at w.refreshAccessToken (/var/task/dist/index-6d56a3b6.js:21385:2251)
        at async w.sendMessage (/var/task/dist/index-6d56a3b6.js:21385:1039)
        at async search (/var/task/dist/index-6d56a3b6.js:21400:10)
        at async /var/task/dist/index-6d56a3b6.js:21483:24
        at async Promise.all (index 1)
        at async middleware (/var/task/node_modules/.pnpm/@[email protected]/node_modules/@octokit/webhooks/dist-node/index.js:355:5)
        at async Server.<anonymous> (/var/task/___vc/__helpers.js:813:13)

Does this work in browser js?

Forgive the noob question, but can I run this in browser js? I tried putting it into a static webpage, but I got some errors. Now I think I'm realizing this is only intended to run in node.js.

Fetch

(node:1754) ExperimentalWarning: The Fetch API is an experimental feature. This feature could change at any time
(Use node --trace-warnings ... to show where the warning was created)

How do i get rid of it?, this is generated when I used console.log();

Error: Failed to launch the browser process

Error: Failed to launch the browser process! spawn /Applications/Google Chrome.app/Contents/MacOS/Google Chrome ENOENT


TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md

    at onClose (C:\Users\User\Desktop\New folder\node_modules\puppeteer-core\lib\cjs\puppeteer\node\BrowserRunner.js:299:20)
    at ChildProcess.<anonymous> (C:\Users\User\Desktop\New folder\node_modules\puppeteer-core\lib\cjs\puppeteer\node\BrowserRunner.js:293:24)
    at ChildProcess.emit (node:events:513:28)
    at ChildProcess._handle.onexit (node:internal/child_process:289:12)
    at onErrorNT (node:internal/child_process:476:16)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Error: Failed to launch the browser process! spawn /Applications/Google Chrome.app/Contents/MacOS/Google Chrome ENOENT


TROUBLESHOOTING: https://github.com/puppeteer/puppeteer/blob/main/docs/troubleshooting.md

    at onClose (C:\Users\User\Desktop\New folder\node_modules\puppeteer-core\lib\cjs\puppeteer\node\BrowserRunner.js:299:20)
    at ChildProcess.<anonymous> (C:\Users\User\Desktop\New folder\node_modules\puppeteer-core\lib\cjs\puppeteer\node\BrowserRunner.js:293:24)
    at ChildProcess.emit (node:events:513:28)
    at ChildProcess._handle.onexit (node:internal/child_process:289:12)
    at onErrorNT (node:internal/child_process:476:16)
    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)

getting a 403 Forbidden error when use version 2.2

Hello, I am now getting a 403 Forbidden error when use chatgpt-api version 2.2.

After modify demo-conversation.ts file's api paramter, run it,then throw exception as below:

(node:6860) ExperimentalWarning: The Fetch API is an experimental feature. This
feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
ChatGPTError: ChatGPT failed to refresh auth token. Error: 403 Forbidden
    at ChatGPTAPI.refreshAccessToken (c:\Users\Administrator\Desktop\TestChatGPT
\chatgpt-api-main (1)\src\chatgpt-api.ts:342:21)
    at process.processTicksAndRejections (node:internal/process/task_queues:95:5
)
    at ChatGPTAPI.ensureAuth (c:\Users\Administrator\Desktop\TestChatGPT\chatgpt
-api-main (1)\src\chatgpt-api.ts:264:12)
    at main (c:\Users\Administrator\Desktop\TestChatGPT\chatgpt-api-main (1)\dem
os\demo-conversation.ts:36:3) {
  response: Response {
    [Symbol(realm)]: null,
    [Symbol(state)]: {
      aborted: false,
      rangeRequested: false,
      timingAllowPassed: true,
      requestIncludesCredentials: true,
      type: 'default',
      status: 403,
      timingInfo: [Object],
      cacheState: '',
      statusText: 'Forbidden',
      headersList: [HeadersList],
      urlList: [Array],
      body: [Object]
    },
    [Symbol(headers)]: HeadersList {
      [Symbol(headers map)]: [Map],
      [Symbol(headers map sorted)]: null
    }
  },
  statusCode: 403,
  statusText: 'Forbidden',
  originalError: ChatGPTError: 403 Forbidden
      at <anonymous> (c:\Users\Administrator\Desktop\TestChatGPT\chatgpt-api-mai
n (1)\src\chatgpt-api.ts:298:25)
      at process.processTicksAndRejections (node:internal/process/task_queues:95
:5)
      at ChatGPTAPI.refreshAccessToken (c:\Users\Administrator\Desktop\TestChatG
PT\chatgpt-api-main (1)\src\chatgpt-api.ts:292:19)
      at ChatGPTAPI.ensureAuth (c:\Users\Administrator\Desktop\TestChatGPT\chatg
pt-api-main (1)\src\chatgpt-api.ts:264:12)
      at main (c:\Users\Administrator\Desktop\TestChatGPT\chatgpt-api-main (1)\d
emos\demo-conversation.ts:36:3) {
    response: Response {
      [Symbol(realm)]: null,
      [Symbol(state)]: [Object],
      [Symbol(headers)]: [HeadersList]
    },
    statusCode: 403,
    statusText: 'Forbidden'
  }
}

and my demo-conversation.ts as below

import dotenv from 'dotenv-safe'
import { oraPromise } from 'ora'

import { ChatGPTAPI } from '../src'
import { getOpenAIAuthInfo } from './openai-auth-puppeteer'

//dotenv.config()

/**
 * Demo CLI for testing conversation support.
 *
 * ```
 * npx tsx src/demo-conversation.ts
 * ```
 */
async function main() {
  //const email = process.env.EMAIL
  //const password = process.env.PASSWORD

/*
  const authInfo = await getOpenAIAuthInfo({
    email,
    password
  })

  const api = new ChatGPTAPI({ ...authInfo })
  */
  const api = new ChatGPTAPI({
  sessionToken: "**my sessionToken*",
  clearanceToken: "IGIXGUiyKUrNckUjBZ.NiGTOYn7bKjjfmRDYAmU8aXQ-1670850561-0-160",
  userAgent: 'Mozilla/5.0 (Windows NT 6.3; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/108.0.0.0 Safari/537.36' // needs to match your browser's user agent
})

  
  
  await api.ensureAuth()

  const conversation = api.getConversation()

  const prompt = 'What is OpenAI?'

  const response = await oraPromise(conversation.sendMessage(prompt), {
    text: prompt
  })

  console.log(response)

  const prompt2 = 'Did they made OpenGPT?'

  console.log(
    await oraPromise(conversation.sendMessage(prompt2), {
      text: prompt2
    })
  )

  const prompt3 = 'Who founded this institute?'

  console.log(
    await oraPromise(conversation.sendMessage(prompt3), {
      text: prompt3
    })
  )

  const prompt4 = 'Who is that?'

  console.log(
    await oraPromise(conversation.sendMessage(prompt4), {
      text: prompt4
    })
  )
}

main().catch((err) => {
  console.error(err)
  process.exit(1)
})

Contribution to your project

Hi,

I want to contribute to your project. I can make translation, code, 2D graphics - icons, logos. Will you be interested?

Thank you in advance.

Valeriia Zhuravska

Why throw this error (`ChatGPTAPI error ${res.status || res.statusText}`)

file:///code/node_modules/chatgpt/src/fetch-sse.ts:13
    throw new Error(`ChatGPTAPI error ${res.status || res.statusText}`)
          ^
Error: ChatGPTAPI error 503
    at fetchSSE (file:///code/node_modules/chatgpt/src/fetch-sse.ts:13:11)
    at processTicksAndRejections (node:internal/process/task_queues:96:5)

env version: node: 16.18.0

image

getting _undici.fetch error

I'm getting this error when authenticating, but I did verify I have the undici library installed. I'm on windows... maybe doing something dumb?

(node:11744) UnhandledPromiseRejectionWarning: Error: ChatGPT failed to refresh auth token. TypeError: _undici.fetch is not a function

Front-end cross-domain

hi ,I'm use react.js build,but show a CORS error :

Access to fetch at 'https://chat.openai.com/api/auth/session' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

ChatGPT failed to refresh auth token. Error: Unauthorized, request returns code 304

Hi! Very excited to use this lib, looks very polished for the amount of time that has passed since chatGPT was launched! I am trying to initialise a client, but keep getting an ChatGPT failed to refresh auth token. Error: Unauthorized error. I copy the value for the __Secure-next-auth.session-token cookie. Have tried the other ones as well, but they don't work either.

When I look at the requests being sent, I can see that the session request returns a 304, and the body is empty. I assume that that is not what is supposed to happen, as the same request on the openAI website does not return an empty body. Any ideas why this could be happening?

about the "undici" error

hello,when I send a message about "Write a singleton pattern in Java.",it throw a "undici" error:

/app/qqbot/service/bin/node_modules/undici/lib/fetch/index.js:1921
fetchParams.controller.controller.error(new TypeError('terminated', {
^

TypeError: terminated
at Fetch.onAborted (/app/qqbot/service/bin/node_modules/undici/lib/fetch/index.js:1921:49)
at Fetch.emit (node:events:390:28)
at Fetch.emit (node:domain:475:12)
at Fetch.terminate (/app/qqbot/service/bin/node_modules/undici/lib/fetch/index.js:93:10)
at Object.onError (/app/qqbot/service/bin/node_modules/undici/lib/fetch/index.js:2062:34)
at Request.onError (/app/qqbot/service/bin/node_modules/undici/lib/core/request.js:265:27)
at null.errorRequest (/app/qqbot/service/bin/node_modules/undici/lib/client.js:1739:13)
at TLSSocket.onSocketClose (/app/qqbot/service/bin/node_modules/undici/lib/client.js:998:5)
at TLSSocket.emit (node:events:402:35)
at TLSSocket.emit (node:domain:475:12)


how can i do for that?

Can I use Chatgpt api in react-native app?

Hi, first of all thanks for your effort for publishing this api.
This is greatly helpful for making project in my side.
Due to problem for implementing this api to my hybrid app, I am asking this question.
Is it possible to use this api in my react-native app?
Please give me an answer with update.
Regards.

Fix history so the bot knows previous messages + misc cookie issue

Been playing around with the api. Here are a couple fixes that could make it work better

  • parentId should always be updated to the previous message sent by the bot
  • conversation id should be populated after initial message received from bot (comes in parsedData)

its not working for me with sessionToken (kept getting unauthorized), so i modified it to use the entire cookie string and it works.

Add support for browser-like edge runtimes

It shouldn't take much effort to make this package work in both Node.js + browser environments.

This could be really important, for instance, for running on Edge runtimes like CF workers, Vercel edge functions, trusted code in Chrome extensions, etc.

Note
This package is not meant to be run client-side in a browser because it contains a reference to your private session token.

Add ability to override auth url

Currently the ChatGPTAPI constructor allows you to set the apiBaseURL and the backendAPIBaseURL however the auth url used for authentication in the refreshAccessTokens function is hardcoded to https://chat.openai.com/api/auth/session. To avoid issues with CORS I would like to be able to modify the auth url so it would go through a koa proxy.

Alternatively this could be resolved by implementing a proxy configuration as described by #47

Quietly exit for no reason

Thanks for making the API, it works pretty well until a very annoying bug surfaces:

if you make multiple queries consecutively, after about several queries, calling api.sendMessage() would exit without the program any error output at the console.

I'm using node v16.18.1, if that matters.

getting captcha'd for every prompt

Appreciate your effort getting things to work after Dec 11 changes 🙏

I built a simple node app that can take a prompt and print the response on terminal window.

In my case it seems to always open a new Chrome window/instance (thus prompting a new captcha) each time I enter a new prompt. I haven't used puppeteer before but looks like it's opening a new window each time, but there might be a way to reuse an already open window? 🤔 Please ignore if it already does that.

Some digging led me to links below:
https://medium.com/@jaredpotter1/connecting-puppeteer-to-existing-chrome-window-8a10828149e0

puppeteer/puppeteer#1788

[ERROR] Error: ChatGPTAPI error 429

Hello,

Was able to install and use it for simple requests, but when it takes a bit to formulate a response I get the error

[ERROR] Error: ChatGPTAPI error 429

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.