Skip to content

Commit

Permalink
feat: 使用最新的ChatGPT API
Browse files Browse the repository at this point in the history
  • Loading branch information
JimmyLv committed Mar 2, 2023
1 parent 5097db2 commit 6afbccc
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 10 deletions.
4 changes: 2 additions & 2 deletions pages/api/summarize.ts
Original file line number Diff line number Diff line change
Expand Up @@ -58,8 +58,8 @@ export default async function handler(
const prompt = getSummaryPrompt(title, text);

const payload = {
model: "text-davinci-003",
prompt,
model: "gpt-3.5-turbo",
messages: [{ role: "user" as const, content: prompt }],
temperature: 0.5,
top_p: 1,
frequency_penalty: 0,
Expand Down
26 changes: 18 additions & 8 deletions utils/OpenAIResult.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,10 +4,16 @@ import {
ReconnectInterval,
} from "eventsource-parser";

export type ChatGPTAgent = "user" | "system";

export interface ChatGPTMessage {
role: ChatGPTAgent;
content: string;
}
export interface OpenAIStreamPayload {
api_key?: string;
model: string;
prompt: string;
messages: ChatGPTMessage[];
temperature: number;
top_p: number;
frequency_penalty: number;
Expand All @@ -22,6 +28,14 @@ function checkApiKey(str: string) {
return pattern.test(str);
}

function formatResult(result: any) {
const answer = result.choices[0].message?.content || "";
if (answer.startsWith("\n\n")) {
return answer.substring(2);
}
return answer;
}

export async function OpenAIResult(
payload: OpenAIStreamPayload,
apiKey?: string
Expand All @@ -34,7 +48,7 @@ export async function OpenAIResult(
throw new Error("OpenAI API Key Format Error");
}

const res = await fetch("https://api.openai.com/v1/completions", {
const res = await fetch("https://api.openai.com/v1/chat/completions", {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${openai_api_key ?? ""}`,
Expand All @@ -49,11 +63,7 @@ export async function OpenAIResult(

if (!payload.stream) {
const result = await res.json();
const answer = result.choices[0].text;
if (answer.startsWith("\n\n")) {
return answer.substring(2);
}
return answer;
return formatResult(result);
}

let counter = 0;
Expand All @@ -71,7 +81,7 @@ export async function OpenAIResult(
}
try {
const json = JSON.parse(data);
const text = json.choices[0].text;
const text = formatResult(json);
console.log("=====text====", text);
if (counter < 2 && (text.match(/\n/) || []).length) {
// this is a prefix character (i.e., "\n\n"), do nothing
Expand Down

1 comment on commit 6afbccc

@vercel
Copy link

@vercel vercel bot commented on 6afbccc Mar 2, 2023

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please sign in to comment.