-
Notifications
You must be signed in to change notification settings - Fork 2.5k
/
Copy pathopenai_moderation.ts
160 lines (138 loc) Β· 3.99 KB
/
openai_moderation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
import { type ClientOptions, OpenAIClient } from "@langchain/openai";
import { ChainValues } from "@langchain/core/utils/types";
import {
AsyncCaller,
AsyncCallerParams,
} from "@langchain/core/utils/async_caller";
import { getEnvironmentVariable } from "@langchain/core/utils/env";
import { BaseChain, ChainInputs } from "./base.js";
/**
* Interface for the input parameters of the OpenAIModerationChain class.
*/
export interface OpenAIModerationChainInput
extends ChainInputs,
AsyncCallerParams {
apiKey?: string;
/** @deprecated Use "apiKey" instead. */
openAIApiKey?: string;
openAIOrganization?: string;
throwError?: boolean;
configuration?: ClientOptions;
}
/**
* Class representing a chain for moderating text using the OpenAI
* Moderation API. It extends the BaseChain class and implements the
* OpenAIModerationChainInput interface.
* @example
* ```typescript
* const moderation = new OpenAIModerationChain({ throwError: true });
*
* const badString = "Bad naughty words from user";
*
* try {
* const { output: moderatedContent, results } = await moderation.call({
* input: badString,
* });
*
* if (results[0].category_scores["harassment/threatening"] > 0.01) {
* throw new Error("Harassment detected!");
* }
*
* const model = new OpenAI({ temperature: 0 });
* const promptTemplate = "Hello, how are you today {person}?";
* const prompt = new PromptTemplate({
* template: promptTemplate,
* inputVariables: ["person"],
* });
* const chain = new LLMChain({ llm: model, prompt });
* const response = await chain.call({ person: moderatedContent });
* console.log({ response });
* } catch (error) {
* console.error("Naughty words detected!");
* }
* ```
*/
export class OpenAIModerationChain
extends BaseChain
implements OpenAIModerationChainInput
{
static lc_name() {
return "OpenAIModerationChain";
}
get lc_secrets(): { [key: string]: string } | undefined {
return {
openAIApiKey: "OPENAI_API_KEY",
};
}
inputKey = "input";
outputKey = "output";
openAIApiKey?: string;
openAIOrganization?: string;
clientConfig: ClientOptions;
client: OpenAIClient;
throwError: boolean;
caller: AsyncCaller;
constructor(fields?: OpenAIModerationChainInput) {
super(fields);
this.throwError = fields?.throwError ?? false;
this.openAIApiKey =
fields?.apiKey ??
fields?.openAIApiKey ??
getEnvironmentVariable("OPENAI_API_KEY");
if (!this.openAIApiKey) {
throw new Error("OpenAI API key not found");
}
this.openAIOrganization = fields?.openAIOrganization;
this.clientConfig = {
...fields?.configuration,
apiKey: this.openAIApiKey,
organization: this.openAIOrganization,
};
this.client = new OpenAIClient(this.clientConfig);
this.caller = new AsyncCaller(fields ?? {});
}
_moderate(text: string, results: OpenAIClient.Moderation): string {
if (results.flagged) {
const errorStr = "Text was found that violates OpenAI's content policy.";
if (this.throwError) {
throw new Error(errorStr);
} else {
return errorStr;
}
}
return text;
}
async _call(values: ChainValues): Promise<ChainValues> {
const text = values[this.inputKey];
const moderationRequest: OpenAIClient.ModerationCreateParams = {
input: text,
};
let mod;
try {
mod = await this.caller.call(() =>
this.client.moderations.create(moderationRequest)
);
} catch (error) {
// eslint-disable-next-line no-instanceof/no-instanceof
if (error instanceof Error) {
throw error;
} else {
throw new Error(error as string);
}
}
const output = this._moderate(text, mod.results[0]);
return {
[this.outputKey]: output,
results: mod.results,
};
}
_chainType() {
return "moderation_chain";
}
get inputKeys(): string[] {
return [this.inputKey];
}
get outputKeys(): string[] {
return [this.outputKey];
}
}