Skip to content
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 17 additions & 1 deletion src/__tests__/unit/checks/moderation-secret-keys.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,23 @@ describe('moderation guardrail', () => {
const result = await moderationCheck({}, 'safe text', ModerationConfig.parse({}));

expect(result.tripwireTriggered).toBe(false);
expect(result.info?.error).toBe('Moderation API call failed');
expect(result.executionFailed).toBe(true);
expect(result.originalException).toBeDefined();
expect(result.info?.error).toContain('network down');
});

it('returns executionFailed for API key errors to support raiseGuardrailErrors', async () => {
const apiKeyError = new Error(
'Incorrect API key provided: sk-invalid. You can find your API key at https://platform.openai.com/account/api-keys.'
);
createMock.mockRejectedValue(apiKeyError);

const result = await moderationCheck({}, 'test text', ModerationConfig.parse({}));

expect(result.tripwireTriggered).toBe(false);
expect(result.executionFailed).toBe(true);
expect(result.originalException).toBe(apiKeyError);
expect(result.info?.error).toContain('Incorrect API key');
});

it('uses context client when available', async () => {
Expand Down
59 changes: 39 additions & 20 deletions src/checks/moderation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,6 +89,17 @@ function isNotFoundError(error: unknown): boolean {
return !!(error && typeof error === 'object' && 'status' in error && error.status === 404);
}

/**
* Ensure a value is an Error instance.
* Converts non-Error values to Error instances with a string representation.
*
* @param error The error value to convert
* @returns An Error instance
*/
function ensureError(error: unknown): Error {
return error instanceof Error ? error : new Error(String(error));
}
Comment on lines +99 to +101
Copy link

Copilot AI Nov 4, 2025

Choose a reason for hiding this comment

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

The ensureError helper function is duplicating error normalization logic that exists in user-defined-llm.ts (line 139). Consider extracting this to a shared utility module to maintain consistency and reduce code duplication across guardrail implementations.

Copilot uses AI. Check for mistakes.
Copy link
Collaborator Author

Choose a reason for hiding this comment

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

[nit] I don't think we need to address this


/**
* Call the OpenAI moderation API.
*
Expand Down Expand Up @@ -144,8 +155,9 @@ export const moderationCheck: CheckFn<ModerationContext, string, ModerationConfi
if (ctx) {
const contextObj = ctx as Record<string, unknown>;
const candidate = contextObj.guardrailLlm;
if (candidate && candidate instanceof OpenAI) {
client = candidate;
// Just use whatever is provided, let the try-catch handle validation
if (candidate) {
client = candidate as OpenAI;
}
}

Expand All @@ -162,25 +174,30 @@ export const moderationCheck: CheckFn<ModerationContext, string, ModerationConfi
try {
resp = await callModerationAPI(new OpenAI(), data);
} catch (fallbackError) {
// If fallback fails, provide a helpful error message
const errorMessage = fallbackError instanceof Error
? fallbackError.message
: String(fallbackError);

// Check if it's an API key error
if (errorMessage.includes('api_key') || errorMessage.includes('OPENAI_API_KEY')) {
return {
tripwireTriggered: false,
info: {
checked_text: data,
error: 'Moderation API requires OpenAI API key. Set OPENAI_API_KEY environment variable or pass a client with valid credentials.',
},
};
}
throw fallbackError;
// If fallback fails, return execution failure
// This allows runGuardrails to handle based on raiseGuardrailErrors flag
return {
tripwireTriggered: false,
executionFailed: true,
originalException: ensureError(fallbackError),
info: {
checked_text: data,
error: ensureError(fallbackError).message,
},
};
}
} else {
throw error;
// Non-404 error from context client - return execution failure
// This allows runGuardrails to handle based on raiseGuardrailErrors flag
return {
tripwireTriggered: false,
executionFailed: true,
originalException: ensureError(error),
info: {
checked_text: data,
error: ensureError(error).message,
},
};
}
}
} else {
Expand Down Expand Up @@ -232,9 +249,11 @@ export const moderationCheck: CheckFn<ModerationContext, string, ModerationConfi
console.warn('AI-based moderation failed:', error);
return {
tripwireTriggered: false,
executionFailed: true,
originalException: ensureError(error),
info: {
checked_text: data,
error: 'Moderation API call failed',
error: ensureError(error).message,
},
};
}
Expand Down