Skip to content

Commit

Permalink
fix(next/api): fix ai classify failed
Browse files Browse the repository at this point in the history
  • Loading branch information
NotEvenANeko committed Nov 21, 2023
1 parent 14c88d6 commit 6c9b901
Showing 1 changed file with 25 additions and 17 deletions.
42 changes: 25 additions & 17 deletions next/api/src/service/openai.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
import { Category } from '@/model/Category';
import _ from 'lodash';
import { Configuration, OpenAIApi } from 'openai';
import { OpenAI } from 'openai';
import { HttpsProxyAgent } from 'https-proxy-agent';
import { z } from 'zod';

export const TicketClassifyPrompt = (categories: Category[]) => `
你是我的工单内容分类助手,我会为你提供各种分类以及它们的描述,以及一个工单的内容,我需要你帮助我将下面的这一个工单分到某一个分类中,并给出你认为的置信度。只按照我给出的格式输出,如果你觉得这个工单不属于我给出的任何分类,输出 null。下面的输出 JSON 格式中,category 表示分类的名字,confidence 表示你给出的置信度,你可以给出对这个工单所有待选的分类,无需额外解释说明。
输出使用的 JSON 格式:"""
[
{ "category": "..", "confidence": 0.123456789 }
{ "category": "..", "confidence": 0.12345678 }
]
{ "category": "..", "confidence": 0.123456789 }
"""
以下是各种分类的 ID 以及他们的含义,由 '-' 开头,每个占一行:
${categories
.map(
Expand All @@ -21,20 +20,22 @@ ${categories
.join('\n')}
`;

export interface TicketClassifyResult {
category: string;
confidence: number;
}
const OpenAIOutputSchema = z.object({
category: z.string(),
confidence: z.number(),
});

export type TicketClassifyResult = z.infer<typeof OpenAIOutputSchema>;

export class OpenAIService {
active: boolean;
instance: InstanceType<typeof OpenAIApi>;
instance: InstanceType<typeof OpenAI>;
agent?: InstanceType<typeof HttpsProxyAgent>;

constructor() {
const apiKey = process.env.OPENAI_API_KEY;
const httpProxy = process.env.http_proxy;
this.instance = new OpenAIApi(new Configuration({ apiKey }));
this.instance = new OpenAI({ apiKey });

if (!apiKey) {
console.warn('OPENAI_API_KEY not provided, disabling openAIService...');
Expand Down Expand Up @@ -63,9 +64,12 @@ export class OpenAIService {
const res = await (async () => {
try {
const res = (
await this.instance.createChatCompletion(
await this.instance.chat.completions.create(
{
model: 'gpt-3.5-turbo',
response_format: {
type: 'json_object',
},
model: process.env.OPENAI_MODEL ?? 'gpt-3.5-turbo',
messages: [
{
role: 'system',
Expand All @@ -78,12 +82,16 @@ export class OpenAIService {
],
temperature: 0.6,
},
{ timeout: 20 * 1000, httpsAgent: this.agent }
{ timeout: 20 * 1000, httpAgent: this.agent }
)
).data.choices[0].message?.content;
).choices[0].message?.content;

if (res) {
return JSON.parse(res) as TicketClassifyResult[];
try {
return OpenAIOutputSchema.parse(JSON.parse(res.trim()));
} catch {
console.log(`parse GPT result error:`, res);
}
}
} catch (err) {
console.error(err);
Expand All @@ -92,7 +100,7 @@ export class OpenAIService {
})();

if (res) {
return categoryById[res[0].category];
return categoryById[res.category];
}
}
}
Expand Down

0 comments on commit 6c9b901

Please sign in to comment.