| 2 | import type { Message } from 'types/pipe'; |
| 3 | |
| 4 | export async function moderate({ |
| 5 | openai, |
| 6 | prompt |
| 7 | }: { |
| 8 | openai: OpenAI; |
| 9 | prompt: { |
| 10 | messages: Message[]; |
| 11 | variables: any[]; |
| 12 | }; |
| 13 | }) { |
| 14 | // Construct a string representation of the prompt |
| 15 | let promptText = ''; |
| 16 | |
| 17 | // Process messages if they exist |
| 18 | if (prompt.messages && prompt.messages.length > 0) { |
| 19 | for (const message of prompt.messages) { |
| 20 | promptText += message.content + '\n'; |
| 21 | } |
| 22 | } |
| 23 | |
| 24 | // Process variables if they exist |
| 25 | if (prompt.variables && prompt.variables.length > 0) { |
| 26 | for (const variable of prompt.variables) { |
| 27 | promptText += `${variable.name}: ${variable.value}\n`; |
| 28 | } |
| 29 | } |
| 30 | |
| 31 | // Perform moderation on the constructed prompt text |
| 32 | const moderation = await openai.moderations.create({ |
| 33 | model: 'omni-moderation-latest', |
| 34 | input: promptText |
| 35 | }); |
| 36 | const result = moderation?.results[0]; |
| 37 | // dlog('moderation:', result); |
| 38 | |
| 39 | // Content is flagged by OpenAI's moderation |
| 40 | if (result.flagged) { |
| 41 | // Filter categories to only include those that are true |
| 42 | const flaggedCategories = Object.entries(result.categories) |
| 43 | .filter(([, value]) => value === true) |
| 44 | .map(([key]) => key.replace('/', ' or ')); // Replace slashes for readability |
| 45 | |
| 46 | const reasons = flaggedCategories.join(', '); |
| 47 | |
| 48 | // Construct and return the error message |
| 49 | return { |
| 50 | flagged: result.flagged, |
| 51 | reason: `Content flagged by OpenAI moderation endpoint due to: ${reasons}` |
| 52 | }; |
| 53 | } |
| 54 | |
| 55 | return { |
| 56 | flagged: result.flagged, |
| 57 | reason: 'Content passed OpenAI moderation successfully' |
| 58 | }; |
| 59 | } |